Chapter-effective rosters, reviewed extraction and atomic Work drafts.
Named groups preserve chapter-effective membership, reviewed suggestions, transactional drafts and reciprocal rosters. Required native gates pass; independent review findings are addressed, with minor refactoring/order observations recorded.
Initial full UI at 9b165ecd: phone 262 passed + 2 expected device-only skips (264 audited IDs), iPad 33/33. Revised-source PR fixes: Latest alias-refusal correction: Core 3,644 / 351 suites, quick 1,893, affected Workmerge phone 1/1 and Personal simulator compile passed. Earlier three-consumer phone, broader phone 11/11, iPad 3/3 and scope check retain their original source qualification. Core JUnit expands parameter cases; no coverage report is available.
Ready to push
The initial full phone/iPad gates qualify 9b165ecd (264/33 canonical methods). After the reviewed Core and ordinary-editor corrections, unfiltered Core/quick and targeted affected phone/iPad consumers passed on the revised frozen content. Unchanged UI evidence is retained with its original source qualification; the page JUnit totals show the revised-source verification, not a new full UI run. Independent reuse, quality, efficiency and spec reviews completed; material findings have regression coverage. Native xcresult summaries supply all gate counts below. Core JUnit comes from Swift Testing’s native writer; quick and UI JUnit transcode actual public xcresult test nodes, retaining case identities and outcomes. Compact native summaries also retain gate-level totals. Coverage data is unavailable.
a11b53a0b5822e481065eba1905917a5e3c21573 T-2491: qualify alias conflict merge refusal 3a54f2dcbdbd084f5f7e2306505ee5a0561d0ef6 Refuse Work merge while group aliases conflict b1100ccc064194b73e20936236488c137a823f37 T-2491: qualify concurrent merge and hydration corrections 7d91b6dde595b56580bf9241520f46027b6cdecd Preserve group histories across concurrent merge heads c6fa34cff045162cf36be95d277161892b5ec3ee T-2491: qualify extraction and conflict review corrections 9bd4ca30ac1e9f007e67e41dbfaecc00113fe873 T-2491: arbitrate extraction and resolve transition conflicts dd2f1d3850db818e0ac7cf9cc4e41edd2b979375 T-2491: qualify PR corrections and retained UI evidence 48b221f59a9465aa74e92e7948baad267d9fa39e T-2491: preserve partial rosters and current link corrections 9b165ecdcfd1bba50db24d44e27a2dab4f11e02b T-2491: record full phone and iPad qualification 9441bf386e610bcc3a7744221fecb3d6f9c19475 T-2491: document reviewed implementation and validation progress bd910b10c91095df7f3d254e221217d10231451b T-2491: preserve group history and UI test viewport 085f9943bca22b25e01e38adae6fde6a4be24be8 T-2491: document softer shared status selection e7a09ea863fa2706b138da5ee70a5e247603a483 T-2491: soften cyan across status selectors 8c1f3ebb1ddda64ce69b20718da7571789cbdc08 T-2491: retain generated group deletion explanation 4216ba838dcb8ac0a24c110a821956bf066fc8dd T-2491: document scoped cyan native selection 74fc5b9cb453f9a83e49aa240f4c662390ab2e41 T-2491: restore cyan selection on native segmented controls 48d4b3c6698b4985822fadd42de1a02f3580fc07 T-2491: document native sheet chrome correction 1585f33e5833b38b00dc6956a45c8c40dbd4577f T-2491: use native group editor sheet roles 52aadda516d38cce368a63124f1831b2a4d332b3 T-2491: reconcile control refinement localization catalog 21429630d594e107f43961664632741295ec63e6 T-2491: document direct deletion and shared glass controls 31d92e1a235ca128350c79302912b1307d58322b T-2491: unify group controls with native glass a649310617e3e2cda9a99c141afffe4700131ac6 T-2491: reconcile transactional editor localization catalog 9851ebb61f40b246022085ccafc732aeab9c616e T-2491: document transactional group acceptance fixes 1ae940f449b12e726a004c9faf9d3fe3c2e322c5 Make character group edits transactional 5c1e801f9ad91b50d35bab1ca8d5cacf22d8971d T-2491: reconcile corrected build localization catalog 17631abe3c18623d0cba8c11bdd392a93e7679aa T-2491: document acceptance corrections 174d75b6ac357fd268052acab03d3267174cb21e feat: review named group membership changes bad32db3492c3770ae9bbb792683ca29897ecde3 T-2491: retain generated group localization entries 2a3079496b123e3d58d4c991d484617b649135c7 T-2491: document completed named group implementation 9a5f9036f9e62190388521d4911da211e55a8eab Complete named group journeys and reconciliation 57f3dcac2a970e8aa064614d13252f33878ea3b5 Add ordinary chapter association remove and restore 885695e7d4a9f919c505d8b2c07fcf54d2bef6d8 feat: add named character group editor and rosters 0d674f6a794825cd7086f03b3c005fbefa0996bf T-2491: ground and review named group proposals 87f0dfe8f3ff14897136cb5efa12f5a431f034c5 T-2491: preserve group history through record operations c5d19c8f3abe63f0574c49ee5ab1bf422cfa458d T-2491: archive named group history in V21 format 92f8de9fe09c8e2b327551b9ceebe2c66060928d T-2491: reconcile named group history in bounded batches fed6384a1cb2e77512148211b00b8c726b1ffdfa Complete group commands and saved-note link paths 3cb1abadf29d5cc87315b1c4d2e87fb51b406c07 Add group save linking and edit transaction 14c03fc7f26ca20f4e59e018ddf013186c7eafb1 Add typed group support and complete-name resolution d6b23cb3eb9a57a1df9fb6aa287c4560dd682166 T-2491: fold causal group rosters 1c7a9137aa0aaf922583b6018223dddbedd65463 T-2491: introduce V22 group storage schema 5d2c470f5ff8664f84c7cc81d17e8a0554b62d1a spec: finalize reviewed group task plan 3eb62b31c3be8e0461d783d8299e50c281738f8c spec: draft named groups implementation tasks 76344ad72a00ff8c6f4d98ec772afb0ca47ed49b spec: record approved group design 13c18546ed9edbb45fd435c9b5673d5ed7b71706 spec: prepare reviewed group design packet 927ecfa063c7fda63b9f188daf7d263def860c1a spec: resolve design compatibility and correction contracts e688bd86fd1f7dfcf5ab0681ce9c8b109e7b386b spec: draft named groups architecture 6de27a738537672be2d90afc26fa5de8e5127a3b spec: record approved group requirements a01fcae20b6151829a3b2ae598a42b75aea52f75 T-2491: record final requirements review outcome c2a3bf44e28f4907fa1c2e3ec69cd62cf894c75f T-2491: carry existing link safety into group requirements 77cec4ca85af9ac5d231d78f433cac5a3ec6a58a T-2491: incorporate owner group membership annotations 211f85dd7e37e71c6facdefd03db1f5569f9cab0 T-2491: remove unapproved roster assumptions from review draft a2a914f2c65e5b8f40760c0f9e5abbe9355a74de T-2491: synthesize requirements reviews and open decisions 6e24f6f791539992d58d49a46be43345849d1bb4 T-2491: draft core group requirements and open decisions 0175992bbc3920774a967489da4347f40ba775f6 T-2491: assess named character group spec scope ### What changed
A Work can contain named groups such as Team Loser. A character can belong to several groups. Membership starts in the joining chapter and includes the leaving chapter. Later chapters carry the last accepted membership forward. Mentioning a group links its members according to that chapter's roster, rather than today's roster. Empty groups do not invent members.
Readers can record who belonged together at each point in a story. Both a group and a character show the reciprocal membership ranges. Existing notes survive link removal and record changes. Group edits stay drafts until the enclosing Work Save; Cancel discards them.
A roster is the membership list at a chapter. An alias is another explicitly saved name for the same group. Suggestions require review; a group name cannot silently become a new character. Remove/Restore actions control ordinary chapter links.
### Changes overview
V22 adds three UUID-addressed tables and archive21/schema22 preserves their raw records. `GroupRoster` folds accepted facts and transitions into immutable ranges. `GroupReferenceResolver` arbitrates complete name spans across groups, characters and places. Save-time matching and historical reconciliation consume the same projection. Group references contribute support to individual character links.
The Work model owns value drafts, including nested group edits. Group-bearing Work saves use a composite repository transaction covering staged Work, record, link, site and roster edits with one final save. Core owns all SwiftData writes. Causal event ancestry and physical variants remain available across import and merges; ambiguous or incomplete evidence is withheld rather than guessed.
Extraction receives known group names and aliases, filters duplicate/type-colliding new-entity proposals, and presents grounded create/join/leave suggestions. Durable Skip decisions remain scoped to their evidence. Ordinary Remove/Restore links retain authored notes and suppression behavior. Historical edits trigger bounded Work-local recalculation, with unrelated chapters excluded.
Causal raw history costs additional storage and validation but preserves concurrent edits and archive fidelity. Chapter-order anomalies remain explicitly deferred. Shared native segmented controls preserve system geometry and scoped cyan styling; a narrow five-option Reading selector uses a readable stacked fallback rather than compressing its labels. The fallback is not native glass.
### Technical deep dive
Projection validates coherent physical copies and complete causal chains before electing live heads. Root tombstones remain authoritative; merge successors retain their ancestry. Equivalent concurrent heads transfer through one successor observing every head; incompatible values retain separate survivor-addressable successors for the ordinary editor. Explicit deletion tombstones the complete source root. Work merge refuses unresolved group names, live alias conflicts or unsafe histories atomically before deleting the source, while coherently deleted groups do not block a merge. An indexed global transition-metadata read discovers foreign-Work successors connected to transferred roots, retaining every physical variant; the same selection feeds projection and the history digest. Inherited group-fact physical parent closure also feeds both reads, so late hydration cannot leave a completed historical cursor unchanged. Chapter processing remains scoped to affected Works. Membership ranges use the existing chapter spine with inclusive start and end checks. Cross-kind equally complete name claims remain unresolved; longer complete spans win without substring-based entity guessing. Automatic recognition rechecks that same arbitration against final saved evidence before writing. Generic notes have no chapter expansion, and existing explicit kind choices/Restore retain their guarded authority. Compatible divergent transition heads stay withheld but are available as empty chapter/action fields in the ordinary editor; an explicit choice writes a successor over every observed head under the complete current basis. Untouched conflicts survive unrelated drafts, and no automatic winner, separate provenance panel or autosave flow was added.
Group-derived association support includes transition evidence, allowing saved-note changes and roster corrections to retire stale support while preserving independent links and authored annotation history. An unavailable accepted join/leave anchor withholds the affected member rather than discarding one endpoint and inventing an open interval. Retirement requires coherent removal: physical conflicts, incomplete ancestry, missing chapter anchors and disputed semantic claims preserve existing support until evidence resolves. Recovery keeps the original acceptance and exact authored note. If a coherent new proof changes the association generation, the existing explicit detached-note recovery action can attach that exact note to the current link; no automatic attachment policy was added. Remove captures refreshed direct aliases only when direct support is active, so a group-only longest match cannot suppress later independent direct evidence. Retrospective reconciliation operates in bounded batches and records its progress without scanning unrelated Works as if they were affected. Reprocessing and record operations share repository locks and save boundaries; refusal/failure preserves the user's editable draft.
The app and share extension receive immutable projections. The extension retains its current-generation-only, non-migrating, non-mirroring contract. The app retains the V16–V22 lightweight migration chain and opens prior accepted readiness markers; archives convert only the explicitly supported predecessor generations. No custom CloudKit engine, relationship expansion or automatic disbanding was introduced.
Model availability and generated candidate quality remain platform-dependent; regressions cover actual candidate assembly and arbitration with synthetic data. Simulator checks do not prove device CloudKit delivery. Mac UI automation and extension-hosted UI coverage have the limits recorded in `verification-run.md`. Chapter reorder/tie behavior was deferred by the owner, not inferred as a new rule. A recorded nonblocking limitation remains: equivalent skipped AI transitions can reappear after an unrelated note edit if the model chooses a different valid quote extent. This suggestion-repeat edge case is not claimed fixed.
Packages/AsterismCore/Sources/AsterismCore/GroupRoster.swift
Why it matters. Historical group references must use that chapter’s roster.
What to look at. GroupRoster.project / GroupProjection
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetailEdit.swift
Why it matters. Nested Done/Delete must not bypass enclosing Cancel.
What to look at. commitWorkDetailEdit
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupHistory.swift
Why it matters. Roster corrections must update older individual links without touching unrelated chapters.
What to look at. reconcileGroupHistory
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecognisedCharacters.swift
Why it matters. Existing groups must not become duplicate characters or disappear from leave review.
What to look at. guarded final-note arbitration and explicit-authority paths
Packages/AsterismCore/Sources/AsterismCore/BackupV21Exporter.swift
Why it matters. Membership history must survive backup/import and merges.
What to look at. archive21/schema22 payload and V22 migration plan
Packages/AsterismCore/Sources/ConstellationKit/ConstellationRecipes.swift
Why it matters. Group, sort and status controls need consistent readable selection.
What to look at. ConstellationLiquidGlassSegmentedControl
Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swift
Why it matters. A withheld membership must remain editable without an automatic winner.
What to look at. conflict choices, full-basis operations and Work draft preview
The owner explicitly deferred reorder/tie edge cases. No new universal ordering policy is inferred.
Remove/Restore uses existing link and note semantics, with suppression against unchanged evidence. No bespoke provenance interface.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Concurrent alias Work merge | A live source alias conflict became an ordinary absent alias after merge despite preserved raw parents. | Extend existing atomic refusal to canonical unresolved alias spellings. Real repository red/green preserves both Works/facts on refusal, then ordinary resolution permits merge; final commit bars and affected phone consumer pass. |
| major | Concurrent merge history | Equivalent concurrent heads were skipped during Work/character moves; divergent source history lost its surviving editor basis. | Rebind every coherent head, coalescing equivalent values and retaining incompatible choices; explicit removal tombstones source roots. Refuse unsafe/name-disputed Work merges atomically and preserve ordinary deleted-group behavior. Real SwiftData red/green and affected app consumers passed. |
| major | Late fact hydration | Historical inventory omitted inherited fact ancestors, allowing a completed cursor to miss newly effective membership while target IDs stayed unchanged. | Use the same complete physical fact-parent closure as projection; two-group late-hydration regression and scope check passed. |
| major | Record conversion | A converted character retained group transitions and blocked other historical reconciliation. | Tombstone membership in the same transaction; regression proved red before fix and covers rollback and notes. |
| major | Work merge and subsequent group edits | Mutation validation omitted source ancestry and used immutable root addresses after transfer. | Load bounded ancestry, retain current-work optimistic bases and use the resolved surviving head; repeated merge, stale, rollback and divergent-copy tests. |
| major | Physical alias fact variants | Filtering foreign-Work copies before coherence checks allowed an unprojectable rename to commit. | Check all physical variants of selected current-group fact IDs; loaded-basis twin regression refuses without appending facts. |
| major | Transferred group sync and reversible retirement | New foreign-Work events sharing transferred roots were absent from roster/history reads; incomplete or disputed evidence could retire existing support. | Index connected transition metadata and physical variants; require coherent removal before retirement, preserving acceptance and notes through repair. Repository regressions and independent re-review passed. |
| major | Largest-text status journey | A status-option test tapped near the navigation bar before its target entered the content viewport. | Retain dialog/cancel/state assertions and wait for post-scroll content coordinates; four focused diagnostic/final runs passed. Full UI gate remains required. |
| major | Leave review wording | Caption incorrectly said removal starts in the leaving chapter. | State inclusive final-chapter membership and verify actual review caption/quote. |
| major | Unavailable leave anchors | Discarding an accepted leave with an unavailable chapter invented an open membership and later links. | Withhold the affected member, forward canonical anchor uncertainty and retain earlier recoverable roots; real SwiftData tests cover hydration, unrelated members and exact explicit note recovery. |
| major | Remove after direct receipt refresh | Immutable legacy keys omitted a currently matching alias; unconditional raw capture would also suppress inactive nested direct names. | Capture current validated direct keys only when a direct root is active, retaining group keys; unchanged replay, Restore and group-only-to-direct lifecycles passed red/green. |
| major | Automatic existing-character arbitration | The recognised-existing extraction path could bypass longest/cross-kind group arbitration and create false individual links. | Re-evaluate the final saved evidence at the guarded Core commit with the shared three-kind resolver, preserving explicit kind choices/Restore and unanchored generic-note semantics. Raw coordinator and real repository regressions passed. |
| major | Explicit divergent membership resolution | A complete observed transition basis was still refused because the resolved roster omits divergent heads, leaving no ordinary editor route. | Separate compatible conflict metadata, empty reader choices in the existing editor, complete causal basis validation, and atomic outer Save/Cancel. Phone/iPad light/dark journeys and preview regressions passed. |
| minor | Skip quote extent | Equivalent AI transition evidence may reappear after an unrelated edit if the model chooses a different valid quote extent. | Recorded nonblocking suggestion-repeat limitation; not claimed fixed in this correction. |
| minor | Support reads | Repeated note resolution and full member scans multiplied per individual pair. | Cache resolution per chapter per invocation and check addressed member ranges. |
| minor | Suggestion tracking | Empty group proposal buckets kept retired Works tracked. | Prune empty buckets; regression verifies context release and no subsequent unnecessary candidate read. |
| minor | Code reuse | Some transition coherence and Work metadata construction are repeated. | Deferred structural refactoring: no semantic mismatch found; avoid expanding the release fix scope. |
| minor | Archive ordering | Raw fact variants tied on current sort keys can retain fetch-dependent array order. | No demonstrated loss or failed round-trip; all variants preserved. Recorded as minor, not a clean deterministic-order claim. |
Source: local run at 2026-10-27T16:03:24.592574+00:00 · snapshot a11b53a0b5822e481065eba1905917a5e3c21573
Baseline: none
Execution: passed · JUnit: 3 files · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 6084 passed · 0 failed · 56 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 ecbe812f2a04ef8fcc622d6a354ebd8418490c5a.
181 files: 167 code · 14 docs. Click to expand.
diff --git a/Asterism/Asterism/CharacterExtraction/CharacterExtractionCoordinator.swift b/Asterism/Asterism/CharacterExtraction/CharacterExtractionCoordinator.swiftindex d1403c5e..e53da61a 100644--- a/Asterism/Asterism/CharacterExtraction/CharacterExtractionCoordinator.swift+++ b/Asterism/Asterism/CharacterExtraction/CharacterExtractionCoordinator.swift@@ -58,6 +58,9 @@ final class CharacterExtractionCoordinator { /// 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]]] = [:]+ /// Group claims have identities separate from character/place proposal keys.+ private var groupProposals: [UUID: [GroundedGroupSuggestion]] = [:]+ private var groupPlans: [String: (groupID: UUID, transitionID: UUID)] = [:] /// 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>?@@ -97,9 +100,18 @@ final class CharacterExtractionCoordinator { } /// Whether the work's page shows the proposals indicator (Req 2.1).- func hasProposals(for work: UUID) -> Bool { !held(for: work).isEmpty }+ func heldGroups(for work: UUID) -> [GroundedGroupSuggestion] {+ groupProposals[work, default: []]+ } - var worksWithProposals: Set<UUID> { Set(ledger.worksWithProposals.filter { !held(for: $0).isEmpty }) }+ func hasProposals(for work: UUID) -> Bool {+ !held(for: work).isEmpty || !heldGroups(for: work).isEmpty+ }++ var worksWithProposals: Set<UUID> {+ Set(ledger.worksWithProposals.filter { !held(for: $0).isEmpty })+ .union(groupProposals.compactMap { !$0.value.isEmpty ? $0.key : nil })+ } /// 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).@@ -148,6 +160,85 @@ final class CharacterExtractionCoordinator { } } + /// The review sheet keeps each grounded group claim until this one-save+ /// Core decision succeeds. Its planned UUIDs stay stable across retries.+ func acceptGroup(_ id: String, workID: UUID) async throws -> GroupEditOutcome {+ guard let proposal = heldGroups(for: workID).first(where: { $0.id == id }) else {+ return .refused(.stale)+ }+ let plan: (groupID: UUID, transitionID: UUID)+ if let existing = groupPlans[id] { plan = existing }+ else {+ plan = (UUID(), UUID()); groupPlans[id] = plan+ }+ let approval = GroupSuggestionApproval(chapterID: proposal.chapterID,+ sourceFingerprint: proposal.sourceFingerprint, groupName: proposal.groupName,+ characterName: proposal.characterName, quote: proposal.quote,+ action: proposal.kind == .leave ? .leave : .join,+ plannedGroupID: plan.groupID, plannedTransitionID: plan.transitionID)+ let outcome = try await library.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(approval)], currentChapterID: proposal.chapterID)+ if case .committed = outcome {+ discardGroup(proposal)+ if proposal.kind == .join {+ groupProposals[workID, default: []].removeAll { $0.kind == .create &&+ RecordNameKey.normalize($0.groupName) == RecordNameKey.normalize(proposal.groupName)+ }+ discardEmptyGroupBucket(for: workID)+ }+ await finishGroupSourceIfDecided(proposal)+ await onMutation()+ }+ return outcome+ }++ func skipGroup(_ id: String, workID: UUID) async throws -> GroupEditOutcome {+ guard let proposal = heldGroups(for: workID).first(where: { $0.id == id }) else {+ return .refused(.stale)+ }+ let outcome = try await library.skipGroupSuggestion(proposal.skipIdentity,+ sourceFingerprint: proposal.sourceFingerprint)+ if case .committed = outcome {+ discardGroup(proposal)+ await finishGroupSourceIfDecided(proposal)+ }+ return outcome+ }++ private func discardGroup(_ proposal: GroundedGroupSuggestion) {+ groupProposals[proposal.workID, default: []].removeAll { $0.id == proposal.id }+ discardEmptyGroupBucket(for: proposal.workID)+ groupPlans[proposal.id] = nil+ }++ private func discardEmptyGroupBucket(for workID: UUID) {+ if groupProposals[workID]?.isEmpty == true {+ groupProposals[workID] = nil+ }+ }++ private func finishGroupSourceIfDecided(_ proposal: GroundedGroupSuggestion) async {+ let sourceRef = SourceRef.entry(proposal.chapterID)+ guard !heldGroups(for: proposal.workID).contains(where: {+ $0.chapterID == proposal.chapterID &&+ $0.sourceFingerprint == proposal.sourceFingerprint+ }), !held(for: proposal.workID).contains(where: {+ $0.citedRevisions[sourceRef] == proposal.sourceFingerprint+ }) else { return }+ do {+ guard let row = try await library.extractionCandidates(limit: 1,+ workIDs: [proposal.workID]).first,+ let source = row.sources.first(where: {+ $0.ref == sourceRef && $0.fingerprint == proposal.sourceFingerprint+ }) else { return }+ _ = try await library.advanceCoverage(workID: proposal.workID,+ sources: [source.completedSource])+ } catch {+ CharacterExtractionLog.failure("group decision coverage advance failed — "+ + CharacterExtractionLog.describe(error))+ }+ }+ /// Q66/Q110: applies a `.reRouted` refusal's payload to the row it was /// about, so the refreshed sheet re-presents it against the record it /// really resolves onto rather than re-reading the row that just refused.@@ -249,7 +340,7 @@ final class CharacterExtractionCoordinator { /// same place rule suggestion's `reconcile()` is called from. The comparison /// is the ledger's; this only performs the read. func reconcile() async {- let tracked = ledger.trackedWorks+ let tracked = ledger.trackedWorks.union(groupProposals.keys) guard !tracked.isEmpty else { return } let rows: [ExtractionCandidate] do {@@ -277,6 +368,17 @@ final class CharacterExtractionCoordinator { for work in tracked where states[work] == nil { contexts[work] = nil } let invalidated = ledger.reconcile(against: states)+ for work in tracked {+ let current = groupProposals[work, default: []].filter { proposal in+ guard let row = rows.first(where: { $0.workID == work }),+ let source = row.sources.first(where: { $0.ref.entryID == proposal.chapterID })+ else { return false }+ return source.isChapter && source.fingerprint == proposal.sourceFingerprint+ }+ groupProposals[work] = current.isEmpty ? nil : current+ }+ let heldGroupIDs = Set(groupProposals.values.flatMap { $0.map(\.id) })+ groupPlans = groupPlans.filter { heldGroupIDs.contains($0.key) } for row in rows { ledger.refreshMentionDecisions(for: row.workID, index: row.mentionIndex) } for row in rows { await routeHeldRecognised(in: row) } pruneContexts()@@ -297,7 +399,7 @@ final class CharacterExtractionCoordinator { /// attempted or in flight — so that is the bound, stated once here and /// applied after the two places that add to the dictionary. private func pruneContexts() {- let tracked = ledger.trackedWorks+ let tracked = ledger.trackedWorks.union(groupProposals.keys) contexts = contexts.filter { tracked.contains($0.key) } capturedEvidence = capturedEvidence.filter { tracked.contains($0.key) } }@@ -314,6 +416,8 @@ final class CharacterExtractionCoordinator { // The retained reads go with the rows they were kept to preview. contexts.removeAll() capturedEvidence.removeAll()+ groupProposals.removeAll()+ groupPlans.removeAll() if ledger.memoryWarning() != nil { attemptTask?.cancel() } } @@ -351,7 +455,8 @@ final class CharacterExtractionCoordinator { await process(candidate, pass: .manual) let held = held(for: workID)- manualOutcomes[workID] = held.isEmpty ? .noProposals : .proposals(held.count)+ manualOutcomes[workID] = held.isEmpty && heldGroups(for: workID).isEmpty+ ? .noProposals : .proposals(held.count + heldGroups(for: workID).count) } // MARK: - One work@@ -391,7 +496,11 @@ final class CharacterExtractionCoordinator { } let outcome = await attempt( source, context: context, revisions: revisions, pass: pass)- if outcome == .producedNone, !ledger.held(for: candidate.workID).contains(where: { $0.citedRevisions[source.source] != nil }) {+ if outcome == .producedNone,+ !ledger.held(for: candidate.workID).contains(where: { $0.citedRevisions[source.source] != nil }),+ !heldGroups(for: candidate.workID).contains(where: {+ source.source.entryID == $0.chapterID && source.fingerprint == $0.sourceFingerprint+ }) { covered.append( CompletedSource(ref: source.source, fingerprint: source.fingerprint, mentionEligibilityDigest: source.mentionEligibilityDigest)) }@@ -532,6 +641,32 @@ final class CharacterExtractionCoordinator { self.contexts[source.workID] = routingContext } let grounded = self.recoverPendingCandidates(outcome.candidates, source: source, context: routingContext)+ let skippedGroups = try await self.library.groupSuggestionSkips(workID: source.workID)+ let acceptedGroups = try await self.library.characterGroups(workID: source.workID)+ var groundedGroups: [GroundedGroupSuggestion] = []+ for proposal in outcome.groups {+ if pass == .automatic && skippedGroups.contains(proposal.skipIdentity) { continue }+ if proposal.kind == .create {+ let key = RecordNameKey.normalize(proposal.groupName)+ if acceptedGroups.contains(where: { group in+ ([group.name].compactMap { $0 } + group.aliases).contains {+ RecordNameKey.normalize($0) == key+ }+ }) { continue }+ } else if let characterName = proposal.characterName {+ let membershipIsEffective = try await self.library.groupSuggestionMembershipIsEffective(+ workID: proposal.workID, chapterID: proposal.chapterID,+ groupName: proposal.groupName, characterName: characterName)+ if proposal.kind == .join && membershipIsEffective { continue }+ if proposal.kind == .leave,+ !(try await self.library.groupSuggestionLeaveIsApplicable(+ workID: proposal.workID, chapterID: proposal.chapterID,+ groupName: proposal.groupName, characterName: characterName)) {+ continue+ }+ }+ groundedGroups.append(proposal)+ } for candidate in grounded { guard var evidence = candidate.sourceEvidence else { continue } evidence.isDecisionBasis = false@@ -557,11 +692,22 @@ final class CharacterExtractionCoordinator { if routed.didCommit { await self.onMutation() } return .unsettled }+ var currentGroupProposals = self.groupProposals[source.workID, default: []]+ currentGroupProposals.removeAll {+ $0.chapterID == source.source.entryID &&+ $0.sourceFingerprint == source.fingerprint+ }+ let existing = Set(currentGroupProposals.map(\.id))+ currentGroupProposals += groundedGroups.filter {+ !existing.contains($0.id)+ }+ self.groupProposals[source.workID] = currentGroupProposals.isEmpty+ ? nil : currentGroupProposals 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+ return routed.review.isEmpty && groundedGroups.isEmpty ? .producedNone : .produced } catch { CharacterExtractionLog.failure("\(label): pending review was not published — \(CharacterExtractionLog.describe(error))") self.settle(key, error is CancellationError ? .cancelled : .failed,
diff --git a/Asterism/Asterism/CharacterExtraction/CharacterExtractor.swift b/Asterism/Asterism/CharacterExtraction/CharacterExtractor.swiftindex acfd7ca1..a9c3b700 100644--- a/Asterism/Asterism/CharacterExtraction/CharacterExtractor.swift+++ b/Asterism/Asterism/CharacterExtraction/CharacterExtractor.swift@@ -37,7 +37,8 @@ actor CharacterExtractor { /// the three differ only in the log line (Req 1.8). func attempt( _ source: ExtractionSource- ) async throws -> (candidates: [GroundedCandidate], modelPhase: Duration) {+ ) async throws -> (candidates: [GroundedCandidate], groups: [GroundedGroupSuggestion],+ modelPhase: Duration) { // Locals: `addTask`'s closure is not isolated to this actor, so reading // the stored properties inside it would need an `await` that the // closure's own suspension points make unnecessary.@@ -53,14 +54,17 @@ actor CharacterExtractor { // 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) })+ places: result.places.map { .init(name: $0.name) },+ groups: result.groups, groupJoins: result.groupJoins,+ groupLeaves: result.groupLeaves) let grounded = CharacterGrounding.ground(names, from: source)+ let groups = GroupExtractionGrounding.ground(names, from: source) for drop in grounded.drops { CharacterExtractionLog.note( "\(CharacterExtractionLog.describe(source.source)): dropped a \(drop.kind.rawValue) " + "candidate — \(drop.reason.rawValue)", content: "name=\"\(drop.name)\"") }- return (grounded.candidates, started.duration(to: .now))+ return (grounded.candidates, groups, started.duration(to: .now)) } }
diff --git a/Asterism/Asterism/CharacterExtraction/CharacterReviewModel.swift b/Asterism/Asterism/CharacterExtraction/CharacterReviewModel.swiftindex 8eba265c..4bb1119a 100644--- a/Asterism/Asterism/CharacterExtraction/CharacterReviewModel.swift+++ b/Asterism/Asterism/CharacterExtraction/CharacterReviewModel.swift@@ -132,6 +132,7 @@ final class CharacterReviewModel: Identifiable { /// The rows still undecided. Decided rows leave immediately; a refused /// acceptance keeps its row, because there is still a decision owed. private(set) var rows: [CharacterReviewRow] = []+ private(set) var groupRows: [GroundedGroupSuggestion] = [] /// What the last refusal was, in the reader's words. Nil when nothing has /// been refused (Req 2.7's disclosure). private(set) var disclosure: String?@@ -140,7 +141,7 @@ final class CharacterReviewModel: Identifiable { /// resolved. private(set) var routesToCheckLibrary = false - var isEmpty: Bool { rows.isEmpty }+ var isEmpty: Bool { rows.isEmpty && groupRows.isEmpty } private let workID: UUID /// Everything a row is drawn and previewed against: both kinds'@@ -181,6 +182,9 @@ final class CharacterReviewModel: Identifiable { /// 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 hasUndecidedGroupSource: @MainActor (SourceRef, String) -> Bool+ private let onGroupDecision: @MainActor (String, DecisionAction) async throws -> GroupEditOutcome+ private let currentHeldGroups: @MainActor () -> [GroundedGroupSuggestion] 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@@ -191,6 +195,7 @@ final class CharacterReviewModel: Identifiable { init( workID: UUID, proposals: [ExtractionProposal],+ groupProposals: [GroundedGroupSuggestion] = [], characters: [WorkRecordPresentation], places: [WorkRecordPresentation] = [], captureOrder: [UUID: Int] = [:],@@ -200,7 +205,10 @@ final class CharacterReviewModel: Identifiable { onReRoute: @escaping @MainActor (ProposalKey, UUID?) -> Void, onReclassify: @escaping @MainActor (ProposalKey, RecordKind, UUID?) -> Void, refresh: @escaping @MainActor () async -> [ExtractionProposal],- currentHeld: (@MainActor () -> [ExtractionProposal])? = nil+ currentHeld: (@MainActor () -> [ExtractionProposal])? = nil,+ hasUndecidedGroupSource: @escaping @MainActor (SourceRef, String) -> Bool = { _, _ in false },+ onGroupDecision: @escaping @MainActor (String, DecisionAction) async throws -> GroupEditOutcome = { _, _ in .refused(.stale) },+ currentHeldGroups: @escaping @MainActor () -> [GroundedGroupSuggestion] = { [] } ) { self.workID = workID self.inputs = ReviewInputs(@@ -214,9 +222,13 @@ final class CharacterReviewModel: Identifiable { self.onReclassify = onReclassify self.refresh = refresh self.currentHeld = currentHeld+ self.hasUndecidedGroupSource = hasUndecidedGroupSource+ self.onGroupDecision = onGroupDecision+ self.currentHeldGroups = currentHeldGroups // Snapshot at open (Req 2.7). let inputs = self.inputs self.rows = proposals.map { Self.row(from: $0, inputs: inputs) }+ self.groupRows = groupProposals syncPreviewedTargets() } @@ -322,6 +334,33 @@ final class CharacterReviewModel: Identifiable { func skip(_ rowID: String) async { await decide(rowID, action: .skip) } + func acceptGroup(_ rowID: String) async { await decideGroup(rowID, action: .accept) }+ func skipGroup(_ rowID: String) async { await decideGroup(rowID, action: .skip) }++ private func decideGroup(_ rowID: String, action: DecisionAction) async {+ guard !isSubmitting, let proposal = groupRows.first(where: { $0.id == rowID }) else { return }+ isSubmitting = true+ defer { isSubmitting = false }+ disclosure = nil+ do {+ switch try await onGroupDecision(rowID, action) {+ case .committed:+ groupRows.removeAll { row in+ row.id == rowID || action == .accept && proposal.kind == .join && row.kind == .create &&+ RecordNameKey.normalize(row.groupName) == RecordNameKey.normalize(proposal.groupName)+ }+ case .refused:+ disclosure = "That chapter or group changed. Review the latest suggestion before trying again."+ _ = await refresh()+ groupRows = currentHeldGroups()+ }+ } catch {+ disclosure = "That could not be saved. Try again."+ CharacterExtractionLog.failure("group decision failed — "+ + CharacterExtractionLog.describe(error))+ }+ }+ private func decide(_ rowID: String, action: DecisionAction) async { guard !isSubmitting, let row = rows.first(where: { $0.id == rowID }) else { return } guard action == .skip || !row.hasNoteConflict else { return }@@ -362,6 +401,9 @@ final class CharacterReviewModel: Identifiable { proposal.nameKey == row.proposal.nameKey { return false } return true }+ request.completedSources.removeAll { source in+ hasUndecidedGroupSource(source.ref, source.fingerprint)+ } if row.proposal.isNoteFirst { // Guard every captured source, but certify only sources whose last // key is settling. Generic/standalone notes have no chapter marker.
diff --git a/Asterism/Asterism/Localizable.xcstrings b/Asterism/Asterism/Localizable.xcstringsindex fdcd7bb3..d9bf079d 100644--- a/Asterism/Asterism/Localizable.xcstrings+++ b/Asterism/Asterism/Localizable.xcstrings@@ -196,6 +196,10 @@ } } },+ "%@, group" : {+ "comment" : "A button that expands or collapses a group of characters. The argument is the name of the group.",+ "isCommentAutoGenerated" : true+ }, "%@. %@" : { "comment" : "A label for a button that opens a sheet. The argument is the title of the choice.", "isCommentAutoGenerated" : true,@@ -417,6 +421,10 @@ }, "Add ${url} as to read" : { + },+ "Add %@ from this chapter" : {+ "comment" : "A button that adds a character from a chapter to the current chapter.",+ "isCommentAutoGenerated" : true }, "Add Page as To Read" : { "comment" : "Title of the \"Add this as to read\" intent.",@@ -442,6 +450,10 @@ "comment" : "Text for the shortcut to add a page to read.", "isCommentAutoGenerated" : true },+ "Add group" : {+ "comment" : "A button that adds a new group to a work.",+ "isCommentAutoGenerated" : true+ }, "Add it as “%@”?" : { "comment" : "The title of the intent.", "isCommentAutoGenerated" : true@@ -462,12 +474,20 @@ "comment" : "A button that adds a work to a series.", "isCommentAutoGenerated" : true },+ "Add transition" : {+ "comment" : "A button that adds a new transition to a character group.",+ "isCommentAutoGenerated" : true+ }, "Adds a web page to your library as a new work to read, after you confirm its title." : { "comment" : "Description of the AddPageToReadIntent intent.", "isCommentAutoGenerated" : true }, "After" : { + },+ "Aliases (one per line)" : {+ "comment" : "A label for the user to enter the aliases of a group.",+ "isCommentAutoGenerated" : true }, "Already resolved" : { @@ -572,6 +592,10 @@ "comment" : "A label for the chapter designation field in the entry correction form.", "isCommentAutoGenerated" : true },+ "Chapter for membership change" : {+ "comment" : "A label for the chapter selection in a character group editor.",+ "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@@ -604,6 +628,22 @@ }, "Chapters · review needed" : { + },+ "Character" : {+ "comment" : "A label for selecting a character from the picker.",+ "isCommentAutoGenerated" : true+ },+ "Character for membership change" : {+ "comment" : "A label for selecting a character for a membership change.",+ "isCommentAutoGenerated" : true+ },+ "Character group" : {+ "comment" : "The title of the character group editor.",+ "isCommentAutoGenerated" : true+ },+ "Character groups" : {+ "comment" : "A heading for the list of character groups.",+ "isCommentAutoGenerated" : true }, "Check Library" : { "comment" : "A button that opens a screen to check the library.",@@ -625,10 +665,24 @@ "comment" : "A loading message for the library diagnostics view.", "isCommentAutoGenerated" : true },+ "Choose a chapter and Join or Leave to resolve this membership change." : {+ "comment" : "Guidance for resolving a conflicting group membership change."+ }, "Choose an earlier source to review" : { "comment" : "A button that opens a view for selecting an earlier source to review.", "isCommentAutoGenerated" : true },+ "Choose both a chapter and Join or Leave to resolve the membership change." : {+ "comment" : "Validation message when only one part of a group membership resolution was chosen."+ },+ "Choose chapter" : {+ "comment" : "A label for a picker that lets the user choose a chapter.",+ "isCommentAutoGenerated" : true+ },+ "Choose character" : {+ "comment" : "A label for a picker that lets the user choose a character.",+ "isCommentAutoGenerated" : true+ }, "Choose file…" : { },@@ -763,6 +817,10 @@ "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 },+ "Create this group" : {+ "comment" : "A button caption that creates a group from a character.",+ "isCommentAutoGenerated" : true+ }, "Created straight away, and kept even if you cancel this edit." : { "comment" : "A description of the benefits of creating a new creator.", "isCommentAutoGenerated" : true@@ -842,6 +900,10 @@ "comment" : "A button that deletes a creator.", "isCommentAutoGenerated" : true },+ "Delete group" : {+ "comment" : "A button that deletes a group and its membership history.",+ "isCommentAutoGenerated" : true+ }, "Delete its notes too" : { },@@ -867,6 +929,10 @@ }, "Delete work, keep its notes" : { + },+ "Deletes this group and its membership history when you save." : {+ "comment" : "A description of the action of deleting a character group.",+ "isCommentAutoGenerated" : true }, "Destination" : { "comment" : "A section header for the list of possible destinations for a work record copy.",@@ -1030,6 +1096,10 @@ "comment" : "A button that opens a web page for a work item.", "isCommentAutoGenerated" : true },+ "Group" : {+ "comment" : "A section for editing a character group's details.",+ "isCommentAutoGenerated" : true+ }, "Hiatus Return Date" : { "comment" : "The title of a sheet that lets the user set a hiatus", "isCommentAutoGenerated" : true@@ -1083,6 +1153,10 @@ "comment" : "A description of a saved source that is not a decision basis.", "isCommentAutoGenerated" : true },+ "Join" : {+ "comment" : "A button to join a group",+ "isCommentAutoGenerated" : true+ }, "Keep" : { },@@ -1126,6 +1200,10 @@ }, "Latest unknown" : { + },+ "Leave" : {+ "comment" : "A button that lets the user change the action of a character's membership in a group.",+ "isCommentAutoGenerated" : true }, "Left unattached" : { "comment" : "A description of a book that was left without a work.",@@ -1228,6 +1306,10 @@ "comment" : "A button that marks a work as finished.", "isCommentAutoGenerated" : true },+ "Membership history" : {+ "comment" : "A section in the character group editor that displays the user's membership history.",+ "isCommentAutoGenerated" : true+ }, "Merge" : { "comment" : "A button that merges two or more works into one.", "isCommentAutoGenerated" : true@@ -1380,6 +1462,10 @@ "comment" : "A description for the empty state when the search query has no matches.", "isCommentAutoGenerated" : true },+ "No members" : {+ "comment" : "A label displayed when a group has no members.",+ "isCommentAutoGenerated" : true+ }, "No notes were first captured on this day." : { "comment" : "A message displayed when a day's breakdown is empty.", "isCommentAutoGenerated" : true@@ -1783,6 +1869,10 @@ "comment" : "A button that removes a token from a list of selected tokens. The argument is the label of the token to be removed.", "isCommentAutoGenerated" : true },+ "Remove %@ from this chapter" : {+ "comment" : "A reader-reviewed suggestion to record that a character leaves a group in this chapter.",+ "isCommentAutoGenerated" : true+ }, "Remove alias %@" : { "comment" : "A button that removes an alias.", "isCommentAutoGenerated" : true@@ -1807,6 +1897,10 @@ "comment" : "A button that removes a date from a work's hiatus.", "isCommentAutoGenerated" : true },+ "Remove membership change" : {+ "comment" : "A button that removes a user's membership change.",+ "isCommentAutoGenerated" : true+ }, "Remove the credit for %@" : { "comment" : "The button that removes a credit from a work. The argument is the name of the creator.", "isCommentAutoGenerated" : true@@ -1870,6 +1964,10 @@ "comment" : "The title of a view that shows that the copies have been resolved.", "isCommentAutoGenerated" : true },+ "Restore" : {+ "comment" : "A button that restores a chapter link.",+ "isCommentAutoGenerated" : true+ }, "Restore %lld entries, %lld works?" : { "comment" : "A headline and two subheadings. The first subheading is the number of entries and works in the backup. The second subheading is the number of entries and works in the user's library. The third subheading is the date the backup was exported.", "isCommentAutoGenerated" : true,@@ -2206,7 +2304,7 @@ "Suggested as both a character and a place" : { },- "Suggested characters and places" : {+ "Suggested characters, places and groups" : { "comment" : "The title of the view.", "isCommentAutoGenerated" : true },@@ -2353,6 +2451,9 @@ }, "This entry received changes after it was combined. Review its note and rating before using it as a chapter." : { + },+ "This membership change will be removed when you save the Work." : {+ "comment" : "Explains a staged removal in the character group editor." }, "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." : { @@ -2418,6 +2519,9 @@ "comment" : "A button that undoes the action of marking a release as not having an episode.", "isCommentAutoGenerated" : true },+ "Undo remove" : {+ "comment" : "Restores a staged group membership change before the Work is saved."+ }, "Unlock your device to use your Asterism library." : { "comment" : "Error message shown when the user tries to access the library while the device is locked.", "isCommentAutoGenerated" : true@@ -2654,4 +2758,4 @@ } }, "version" : "1.1"-}+}
diff --git a/Asterism/Asterism/UITestLaunchSupport.swift b/Asterism/Asterism/UITestLaunchSupport.swiftindex 423f84ae..58ca2a60 100644--- a/Asterism/Asterism/UITestLaunchSupport.swift+++ b/Asterism/Asterism/UITestLaunchSupport.swift@@ -269,6 +269,15 @@ enum UITestLaunchSupport { static let cannedExtractionResult = ExtractionResult( characters: [ExtractedCharacter(name: "Ada/Nightjar"), ExtractedCharacter(name: "Brede"), ExtractedCharacter(name: "Selkie")], places: [ExtractedPlace(name: "Kestrel Head"), ExtractedPlace(name: "Selkie")])+ /// A group proposal and an exact saved-note join for the named-group UI+ /// journey. Existing extraction scenarios keep their original answer.+ static let namedGroupsExtractionResult = ExtractionResult(+ groups: [ExtractedGroup(name: "The Night Crew")],+ groupJoins: [ExtractedGroupJoin(groupName: "The Night Crew",+ characterName: "Brede", quote: "Brede joins The Night Crew")])+ static let namedGroupLeaveExtractionResult = ExtractionResult(+ groupLeaves: [ExtractedGroupLeave(groupName: "The Night Crew",+ characterName: "Brede", quote: "Brede leaves The Night Crew")]) static func characterExtractionClient( environmentProvider: any ProcessEnvironmentProviding = SystemProcessEnvironment()@@ -276,6 +285,10 @@ enum UITestLaunchSupport { switch environmentProvider.environment[extractionKey] { case "canned": return StubCharacterExtractionModelClient(result: cannedExtractionResult)+ case "named-groups":+ return StubCharacterExtractionModelClient(result: namedGroupsExtractionResult)+ case "named-groups-leave":+ return StubCharacterExtractionModelClient(result: namedGroupLeaveExtractionResult) case "empty": // Both arrays empty: the source grounds to nothing of either kind // and covers at pass time (Req 1.4).
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex cd8de832..0dbbcdb7 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 BackupV20SnapshotProviding).- private var backupRepository: (any BackupV20SnapshotProviding)?+ /// Retains the concrete repository for backup export (conforms to BackupV21SnapshotProviding).+ private var backupRepository: (any BackupV21SnapshotProviding)? /// 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.@@ -2977,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() -> BackupV20Exporter? {+ private func backupExporter() -> BackupV21Exporter? { guard let repo = backupRepository, let config = resolvedConfiguration else { return nil } let stagingDir = config.rootDirectory .appending(path: "Library/Caches/BackupExports")- return BackupV20Exporter(repository: repo, stagingDirectory: stagingDir)+ return BackupV21Exporter(repository: repo, stagingDirectory: stagingDir) } /// The per-entry markdown export model (Req 1.5), staged beside the backup@@ -3254,6 +3254,9 @@ public final class AppLibraryModel { /// *proposals* is seeded — grounding, assembly, matching and every decision /// are the shipping ones. private func seedCharactersFixture(in repo: LibraryRepository) async throws {+ let groupJourney = ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_GROUP_JOURNEY"] == "1"+ let groupLeaveJourney = ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_GROUP_LEAVE_JOURNEY"] == "1"+ let namedGroupJourney = groupJourney || groupLeaveJourney let entry = try await repo.capture(CaptureDraft( captureTitle: ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_SOURCE_ROWS"] == "1" ? "The Lamp Room — arrival at the old harbour" : "Chapter 1 - The Lamp Room",@@ -3263,7 +3266,9 @@ public final class AppLibraryModel { // live citation: Kestrel Head's other quote sits in the work's // generic notes, which cite no entry, so without this the entry // detail's Places section (Req 4.4) could never be reached.- note: "Brede rows the tender out at dusk, past Kestrel Head."))+ note: groupLeaveJourney ? "Brede leaves The Night Crew after this chapter." :+ namedGroupJourney ? "Brede joins The Night Crew." :+ "Brede rows the tender out at dusk, past Kestrel Head.")) let work = try await repo.createWork( NewWorkDraft(displayTitle: "The Lamp Room", hostname: "characters.test"))@@ -3307,6 +3312,46 @@ public final class AppLibraryModel { displayedKeys: ["brede"], proposedName: "Brede")) guard case .committed = outcome else { throw LibraryRepositoryError.invalidInput(operation: "seeding known character", reason: "synthetic seed refused") } }+ if groupLeaveJourney {+ let detail = try await repo.workDetail(id: work.id)+ guard let brede = detail.characters.first(where: { $0.name == "Brede" }) else {+ throw LibraryRepositoryError.invalidInput(operation: "seeding group leave review", reason: "Brede was not seeded")+ }+ let groupID = UUID()+ let transitionID = UUID()+ let outcome = try await repo.commitGroupEdits(workID: work.id, operations: [+ .create(groupID: groupID, name: "The Night Crew"),+ .transition(rootID: transitionID, groupID: groupID,+ characterID: brede.id, chapterID: entry.id, action: .join)+ ], currentChapterID: entry.id)+ guard case .committed = outcome else {+ throw LibraryRepositoryError.invalidInput(operation: "seeding group leave review", reason: "group membership was refused")+ }+ }+ if ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_GROUP_CONFLICT"] == "1" {+ let recognised = try await repo.commitDecision(.init(workID: work.id,+ kind: .character, action: .accept, displayedKeys: ["brede"],+ proposedName: "Brede"))+ guard case .committed = recognised,+ let brede = try await repo.workDetail(id: work.id).characters.first(where: {+ $0.name == "Brede"+ }) else {+ throw LibraryRepositoryError.invalidInput(operation: "seeding group conflict",+ reason: "Brede was not seeded")+ }+ let groupID = UUID(), rootID = UUID()+ let created = try await repo.commitGroupEdits(workID: work.id,+ operations: [.create(groupID: groupID, name: "The Night Crew"),+ .transition(rootID: rootID, groupID: groupID,+ characterID: brede.id, chapterID: entry.id, action: .join)],+ currentChapterID: entry.id)+ guard case .committed = created else {+ throw LibraryRepositoryError.invalidInput(operation: "seeding group conflict",+ reason: "the original membership was refused")+ }+ try await repo.seedConflictedGroupTransitionForUITest(workID: work.id,+ rootID: rootID)+ } #endif Self.logger.debug("Seeded the character-extraction UI test fixture") }
diff --git a/Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swift b/Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swiftnew file mode 100644index 00000000..63f1b860--- /dev/null+++ b/Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swift@@ -0,0 +1,214 @@+import AsterismCore+import Foundation+import Observation++struct CharacterGroupDraft: Sendable, Equatable {+ let workID: UUID+ let groupID: UUID+ let original: GroupSummary?+ var name: String+ var aliases: String+ var transitions: [GroupTransitionFact]+ var conflictResolutions: [UUID: GroupTransitionResolution]+ var isDeleted: Bool++ var previewTransitions: [GroupTransitionFact] {+ // A summary carries the current resolved head for each root, not every+ // ancestor needed to replay its immutable event chain. Display preview+ // therefore normalizes each final head into a self-contained claim.+ // Persistence still derives corrections from the original event ids.+ func resolved(_ value: GroupTransitionFact) -> GroupTransitionFact? {+ guard value.action != .remove else { return nil }+ return GroupTransitionFact(id: value.rootID, rootID: value.rootID,+ workID: workID, groupID: groupID, characterID: value.characterID,+ chapterID: value.chapterID, action: value.action)+ }+ let oldRoots = Set(original?.transitions.map(\.rootID) ?? [])+ let retained = (original?.transitions ?? []).compactMap { old in+ transitions.first(where: { $0.rootID == old.rootID }).flatMap(resolved)+ }+ let added = transitions.filter { !oldRoots.contains($0.rootID) }.compactMap(resolved)+ let resolvedConflicts = (original?.conflictedTransitions ?? []).compactMap { conflict -> GroupTransitionFact? in+ guard let choice = conflictResolutions[conflict.rootID],+ let chapterID = choice.chapterID, let action = choice.action,+ action != .remove else { return nil }+ return GroupTransitionFact(id: conflict.rootID, rootID: conflict.rootID,+ workID: workID, groupID: groupID, characterID: conflict.characterID,+ chapterID: chapterID, action: action)+ }+ return retained + added + resolvedConflicts+ }++ var operations: [GroupEditOperation] {+ if isDeleted, let original {+ return [.fact(groupID: groupID, expectedEventIDs: original.factEventIDs,+ operation: .delete)]+ }+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)+ let aliasValues = Set(aliases.split(separator: "\n").map {+ String($0).trimmingCharacters(in: .whitespacesAndNewlines)+ }.filter { !$0.isEmpty })+ var result: [GroupEditOperation] = []+ if let original {+ func fact(_ operation: GroupFactOperation) -> GroupEditOperation {+ .fact(groupID: groupID, expectedEventIDs: original.factEventIDs,+ operation: operation)+ }+ if trimmed != original.name { result.append(fact(.setName(trimmed))) }+ for alias in Set(original.aliases).subtracting(aliasValues).sorted() {+ result.append(fact(.removeAlias(alias)))+ }+ for alias in aliasValues.subtracting(original.aliases).sorted() {+ result.append(fact(.addAlias(alias)))+ }+ for old in original.transitions {+ let updated = transitions.first { $0.rootID == old.rootID }+ if updated?.chapterID != old.chapterID || updated?.action != old.action {+ result.append(.reviseTransition(rootID: old.rootID,+ expectedEventIDs: original.transitionEventIDs[old.rootID] ?? [old.id],+ chapterID: updated?.chapterID ?? old.chapterID,+ action: updated?.action ?? .remove))+ }+ }+ for conflict in original.conflictedTransitions {+ guard let choice = conflictResolutions[conflict.rootID],+ let action = choice.action,+ let chapterID = choice.chapterID ?? (action == .remove+ ? conflict.heads.first?.chapterID : nil) else { continue }+ result.append(.reviseTransition(rootID: conflict.rootID,+ expectedEventIDs: conflict.expectedEventIDs,+ chapterID: chapterID, action: action))+ }+ } else {+ result.append(.create(groupID: groupID, name: trimmed))+ for alias in aliasValues.sorted() {+ result.append(.fact(groupID: groupID, expectedEventIDs: [],+ operation: .addAlias(alias)))+ }+ }+ let oldRoots = Set(original?.transitions.map(\.rootID) ?? [])+ for transition in transitions where !oldRoots.contains(transition.rootID) {+ result.append(.transition(rootID: transition.rootID, groupID: groupID,+ characterID: transition.characterID, chapterID: transition.chapterID,+ action: transition.action))+ }+ return result+ }+}++struct GroupTransitionResolution: Sendable, Equatable {+ var chapterID: UUID?+ var action: GroupTransitionAction?+}++struct CharacterGroupMemberOption: Identifiable, Equatable {+ let id: UUID+ let name: String+ let isTorn: Bool+}++@MainActor @Observable+final class CharacterGroupEditorModel: Identifiable {+ let id = UUID()+ let groupID: UUID+ let workID: UUID+ var name: String+ var aliases: String+ var transitions: [GroupTransitionFact]+ var conflictResolutions: [UUID: GroupTransitionResolution]+ var errorMessage: String?+ private(set) var isSaving = false+ private let original: GroupSummary?+ private let onStage: @MainActor (CharacterGroupDraft) -> Void+ var canDelete: Bool { original != nil }++ init(workID: UUID, group: GroupSummary? = nil, draft: CharacterGroupDraft? = nil,+ onStage: @escaping @MainActor (CharacterGroupDraft) -> Void) {+ self.workID = workID; self.onStage = onStage+ if let draft { original = draft.original }+ else { original = group }+ groupID = draft?.groupID ?? group?.groupID ?? UUID()+ name = draft?.name ?? group?.name ?? ""+ aliases = draft?.aliases ?? group?.aliases.joined(separator: "\n") ?? ""+ transitions = draft?.transitions ?? group?.transitions ?? []+ conflictResolutions = draft?.conflictResolutions ?? [:]+ }++ func addMember(characterID: UUID, chapterID: UUID, action: GroupTransitionAction) {+ let root = UUID()+ transitions.append(.init(id: root, rootID: root, workID: workID,+ groupID: groupID, characterID: characterID, chapterID: chapterID, action: action))+ }+ func revise(_ transition: GroupTransitionFact, chapterID: UUID, action: GroupTransitionAction) {+ guard let index = transitions.firstIndex(where: { $0.rootID == transition.rootID }) else { return }+ let isPersistedRoot = original?.transitions.contains(where: { $0.rootID == transition.rootID }) == true+ transitions[index] = .init(id: isPersistedRoot ? UUID() : transition.rootID,+ rootID: transition.rootID, workID: workID,+ groupID: groupID, characterID: transition.characterID, chapterID: chapterID, action: action)+ }+ func remove(_ transition: GroupTransitionFact) {+ guard let index = transitions.firstIndex(where: { $0.rootID == transition.rootID }) else { return }+ guard original?.transitions.contains(where: { $0.rootID == transition.rootID }) == true else {+ transitions.remove(at: index)+ return+ }+ transitions[index] = .init(id: UUID(), rootID: transition.rootID, workID: workID,+ groupID: groupID, characterID: transition.characterID,+ chapterID: transition.chapterID, parentHeadIDs: transition.parentHeadIDs,+ action: .remove)+ }+ var conflictedTransitions: [GroupTransitionConflict] {+ original?.conflictedTransitions ?? []+ }+ func conflictChapter(_ rootID: UUID) -> UUID? {+ conflictResolutions[rootID]?.chapterID+ }+ func conflictAction(_ rootID: UUID) -> GroupTransitionAction? {+ conflictResolutions[rootID]?.action+ }+ func chooseConflictChapter(_ rootID: UUID, chapterID: UUID?) {+ var choice = conflictResolutions[rootID] ?? .init(chapterID: nil, action: nil)+ choice.chapterID = chapterID+ if choice.action == .remove { choice.action = nil }+ conflictResolutions[rootID] = choice+ errorMessage = nil+ }+ func chooseConflictAction(_ rootID: UUID, action: GroupTransitionAction?) {+ var choice = conflictResolutions[rootID] ?? .init(chapterID: nil, action: nil)+ choice.action = action+ conflictResolutions[rootID] = choice+ errorMessage = nil+ }+ func toggleConflictRemoval(_ rootID: UUID) {+ if conflictResolutions[rootID]?.action == .remove {+ conflictResolutions.removeValue(forKey: rootID)+ } else {+ conflictResolutions[rootID] = .init(chapterID: nil, action: .remove)+ }+ errorMessage = nil+ }+ func save(deleting: Bool = false) async -> Bool {+ guard !isSaving else { return false }+ guard !deleting || original != nil else {+ errorMessage = "Save the group before deleting it."+ return false+ }+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)+ guard deleting || !trimmed.isEmpty else { errorMessage = "Enter a group name."; return false }+ guard deleting || conflictResolutions.values.allSatisfy({ choice in+ choice.action == .remove || (choice.chapterID == nil && choice.action == nil) ||+ (choice.chapterID != nil && choice.action != nil)+ }) else {+ errorMessage = String(localized:+ "Choose both a chapter and Join or Leave to resolve the membership change.")+ return false+ }+ isSaving = true+ defer { isSaving = false }+ onStage(CharacterGroupDraft(workID: workID, groupID: groupID,+ original: original, name: trimmed, aliases: aliases,+ transitions: transitions, conflictResolutions: conflictResolutions,+ isDeleted: deleting))+ return true+ }+}
diff --git a/Asterism/Asterism/ViewModels/EntryDetailModel.swift b/Asterism/Asterism/ViewModels/EntryDetailModel.swiftindex b3856ab9..bf2e7b3b 100644--- a/Asterism/Asterism/ViewModels/EntryDetailModel.swift+++ b/Asterism/Asterism/ViewModels/EntryDetailModel.swift@@ -276,7 +276,7 @@ public final class EntryDetailModel { let snapshot = detail.entry self.entry = snapshot self.teachingDetail = detail- self.chapterAssociations = detail.chapterAssociations.filter { !$0.activeAcceptanceIDs.isEmpty }+ self.chapterAssociations = detail.chapterAssociations.filter { !$0.activeAcceptanceIDs.isEmpty || $0.isRemoved } self.draftTitle = snapshot.authoredTarget?.title ?? "" self.draftSourceURL = snapshot.sourceURLs.first ?? "" self.draftNote = snapshot.note@@ -296,13 +296,23 @@ public final class EntryDetailModel { do { let values = try await library.chapterAssociations(entryID: entryID) guard !Task.isCancelled else { return }- chapterAssociations = values.filter { !$0.activeAcceptanceIDs.isEmpty }+ chapterAssociations = values.filter { !$0.activeAcceptanceIDs.isEmpty || $0.isRemoved } } 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 }+ guard chapterAssociations.contains(where: { $0.pair == pair && !$0.activeAcceptanceIDs.isEmpty }) else { return nil } return AssociationNoteEditorModel(pair: pair, library: library) }+ func correctChapterAssociation(_ association: ChapterAssociationSnapshot) async {+ do {+ let changed = association.isRemoved+ ? try await library.restoreChapterAssociation(pair: association.pair)+ : try await library.removeChapterAssociation(pair: association.pair)+ if changed { await refreshAssociations() }+ } catch {+ Self.logger.error("Chapter association correction failed: \(String(describing: error), privacy: .public)")+ }+ } func skippedCharacterLinksModel() -> SkippedCharacterLinksModel { SkippedCharacterLinksModel(entryID: entryID, library: library, chapterTitle: screenTitle) { [weak self] in await self?.associationNoteSaved()
diff --git a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift b/Asterism/Asterism/ViewModels/SettingsBackupModel.swiftindex 3aa42a16..e22aec03 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 `BackupV20Exporter` to this protocol via extension below.+/// surface. Conforms `BackupV21Exporter` 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,7 +19,7 @@ public protocol BackupExporting: Sendable { } extension BackupV19Exporter: BackupExporting {}-extension BackupV20Exporter: BackupExporting {}+extension BackupV21Exporter: BackupExporting {} // MARK: - Export Stage
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel.swift b/Asterism/Asterism/ViewModels/WorkDetailModel.swiftindex 96a59418..c0e58a5f 100644--- a/Asterism/Asterism/ViewModels/WorkDetailModel.swift+++ b/Asterism/Asterism/ViewModels/WorkDetailModel.swift@@ -22,6 +22,82 @@ public final class WorkDetailModel { /// The whole §6 read (Reqs 5.1–5.4), from one call so the counts, the /// last-noted URL and the chapter rows describe one moment of the store. public private(set) var presentation: WorkDetailPresentation?+ private var storedCharacterGroups: [GroupSummary] = []+ private var stagedCharacterGroups: [UUID: CharacterGroupDraft] = [:]+ public var characterGroups: [GroupSummary] {+ guard !stagedCharacterGroups.isEmpty else { return storedCharacterGroups }+ var groups = storedCharacterGroups.filter { stagedCharacterGroups[$0.groupID]?.isDeleted != true }+ var byID = Dictionary(uniqueKeysWithValues: groups.map { ($0.groupID, $0) })+ for draft in stagedCharacterGroups.values.sorted(by: { $0.groupID.uuidString < $1.groupID.uuidString })+ where !draft.isDeleted {+ let original = byID[draft.groupID] ?? draft.original+ let updated = GroupSummary(groupID: draft.groupID,+ name: draft.name.trimmingCharacters(in: .whitespacesAndNewlines),+ aliases: Self.groupAliasValues(draft.aliases),+ members: original?.members ?? [:], factEventIDs: original?.factEventIDs ?? [],+ transitions: draft.previewTransitions,+ conflictedTransitions: (original?.conflictedTransitions ?? []).filter {+ draft.conflictResolutions[$0.rootID] == nil+ },+ transitionEventIDs: original?.transitionEventIDs ?? [:])+ byID[draft.groupID] = updated+ if let index = groups.firstIndex(where: { $0.groupID == draft.groupID }) {+ groups[index] = updated+ } else {+ groups.append(updated)+ }+ }+ let facts = groups.flatMap { group -> [GroupFact] in+ guard let name = group.name, !name.isEmpty else { return [] }+ return [GroupFact(id: group.groupID, groupID: group.groupID, workID: workID,+ operation: .create(name: name))]+ }+ let chapterFacts = chapterRowsByChapter.map { GroupChapter(id: $0.id, label: $0.displayTitle) }+ let resolvedTransitions = groups.flatMap { group in+ group.transitions.compactMap { transition -> GroupTransitionFact? in+ guard transition.action != .remove else { return nil }+ return GroupTransitionFact(id: transition.rootID, rootID: transition.rootID,+ workID: workID, groupID: group.groupID, characterID: transition.characterID,+ chapterID: transition.chapterID, action: transition.action)+ }+ }+ let projected = GroupRoster.project(workID: workID, chapters: chapterFacts,+ facts: facts, transitions: resolvedTransitions).groups+ return projected.compactMap { projection in+ guard let source = byID[projection.groupID] else { return nil }+ return GroupSummary(groupID: source.groupID, name: source.name,+ aliases: source.aliases, members: projection.members.filter { characterID, _ in+ !source.conflictedTransitions.contains { $0.characterID == characterID }+ },+ factEventIDs: source.factEventIDs, transitions: source.transitions,+ conflictedTransitions: source.conflictedTransitions,+ transitionEventIDs: source.transitionEventIDs)+ }+ }++ func groupEditor(_ group: GroupSummary? = nil) -> CharacterGroupEditorModel {+ let staged = group.flatMap { stagedCharacterGroups[$0.groupID] }+ return CharacterGroupEditorModel(workID: workID, group: group, draft: staged) { [weak self] draft in+ self?.stagedCharacterGroups[draft.groupID] = draft+ }+ }++ var groupCharacterOptions: [CharacterGroupMemberOption] {+ let persisted = characters.map {+ CharacterGroupMemberOption(id: $0.id, name: $0.name, isTorn: $0.isTorn)+ }+ let staged = createdRecordIDs(of: .character).compactMap { id in+ recordDrafts[id].map { CharacterGroupMemberOption(id: id, name: $0.name, isTorn: false) }+ }+ return persisted + staged+ }++ private static func groupAliasValues(_ text: String) -> [String] {+ Array(Set(text.split(separator: "\n").map {+ String($0).trimmingCharacters(in: .whitespacesAndNewlines)+ }.filter { !$0.isEmpty })).sorted()+ }+ /// The Work the presentation describes. Read off the presentation rather /// than stored beside it: two fields set from one load are two fields that /// can disagree, and every other §6 read on this model is already derived.@@ -696,6 +772,7 @@ public final class WorkDetailModel { state = .loading do { let detail = try await library.workDetail(id: workID)+ storedCharacterGroups = detail.characterGroups // One statement for both orders (Q13): a Chapter order assigned // separately is a second moment, and a reload that failed between // the two would leave the spine sorting rows the screen no longer@@ -2467,6 +2544,7 @@ public final class WorkDetailModel { // `adoptRecordDrafts` refuses to replace the drafts of a session that // is still open. isEditing = false+ stagedCharacterGroups = [:] restoreDraftsFromSnapshot() draftWorkURL = baselineWorkURL acceptedSuggestedURL = false@@ -2513,11 +2591,6 @@ public final class WorkDetailModel { // every write, so an unparseable type refuses the whole commit rather // than half of it (`specs/bugfixes/edit-views-write-before-save/`). guard validateLinkDraftsBeforeCommit() else { return }- var committedURL = false- if hasUnsavedWorkURLChange {- guard await commitWorkURLDraft() else { return }- committedURL = true- } // Derived once. It JSON-encodes every record's facts to decide what // differs, and the state it reads cannot move between here and the // commit: `adoptRecordDrafts` refuses to touch a staged session, and@@ -2528,8 +2601,60 @@ public final class WorkDetailModel { // their reason: what the tail reloads on must be decided before the // commits that clear them. let linkOperations = stagedLinkEdits()- let hasConnectionChanges = !linkOperations.isEmpty || hasUnsavedMembershipRemovals+ let groupOperations = stagedCharacterGroups.values+ .sorted { $0.groupID.uuidString < $1.groupID.uuidString }+ .flatMap(\.operations)+ let hasGroupChanges = !groupOperations.isEmpty let hadMetadataChanges = hasUnsavedChanges+ if hasGroupChanges {+ var workURLContract: WorkURLContract?+ if hasUnsavedWorkURLChange {+ guard let request = workURLRequestForDraft() else { return }+ switch request {+ case .confirmCandidate(let value), .replaceManual(let value):+ if let message = hostMismatchMessage(for: value) {+ workURLStatusMessage = message+ return+ }+ case .clear: break+ }+ do {+ workURLContract = try await library.projectWorkURL(+ workID: workID, hostname: selectedWorkURLHostname, request: request)+ } catch {+ workURLStatusMessage = error.localizedDescription+ return+ }+ }+ var metadataEdit = hadMetadataChanges ? transactionMetadataEdit() : nil+ guard !hadMetadataChanges || metadataEdit != nil else {+ didRefusePosition = true+ return+ }+ if let workURLContract, workURLContract.basis.membershipID == nil,+ let currentMetadata = metadataEdit {+ metadataEdit = WorkDetailMetadataEdit(+ basis: currentMetadata.basis.addingSiteFreeMembership(+ hostname: workURLContract.basis.siteHostname.value),+ draft: currentMetadata.draft, calendar: currentMetadata.calendar)+ }+ await commitWorkDetailTransaction(+ metadata: metadataEdit,+ recordOperations: recordOperations,+ linkOperations: linkOperations,+ groupOperations: groupOperations,+ workURL: workURLContract,+ membershipRemovalHostnames: stagedMembershipRemovals.sorted(),+ offerEvent: offerEvent,+ offerGeneration: offerGeneration)+ return+ }+ var committedURL = false+ if hasUnsavedWorkURLChange {+ guard await commitWorkURLDraft() else { return }+ committedURL = true+ }+ let hasConnectionChanges = !linkOperations.isEmpty || hasUnsavedMembershipRemovals || hasGroupChanges if hadMetadataChanges { // One reload, not two: a later step's reload is the one that@@ -2547,6 +2672,9 @@ public final class WorkDetailModel { // staged edits intact. guard await commitLinkStep(linkOperations) else { return } guard await commitMembershipRemovals() else { return }+ // Groups commit last: if any earlier Work edit step refuses, every+ // group draft remains only in this session and can still be cancelled.+ guard await commitGroupStep(groupOperations) else { return } // Dropped before the reload, so the re-adopt below is allowed to replace // the drafts with what the store now holds.@@ -2582,6 +2710,154 @@ public final class WorkDetailModel { } } + private func transactionMetadataEdit() -> WorkDetailMetadataEdit? {+ guard case .membership(let membership) = seriesDraft else { return nil }+ let draft = WorkMetadataDraft(+ displayTitle: draftTitle, typeAssignment: draftAssignment,+ genreTags: draftTags, genericNotes: draftNotes,+ publicationEdit: publicationEdit, readingStatus: draftReadingStatus,+ verdict: draftVerdict, releaseDays: ReleaseDay.canonical(draftReleaseDays),+ membership: membership, credits: creditsDraft, thumbnail: thumbnailWrite,+ chapterCaptureDefault: draftChapterCaptureDefault)+ let basis = editorWorkBasis ?? work.map(WorkEditBasis.init(work:))+ ?? WorkEditBasis(+ displayTitle: draftTitle, typeAssignment: draftAssignment,+ genreTags: draftTags, genericNotes: draftNotes, memberships: [],+ lastParsedTitle: nil, titleProvenance: .manual,+ workStatus: draftWorkStatus, readingStatus: draftReadingStatus,+ verdict: draftVerdict, membership: work?.membership,+ thumbnail: thumbnailBaseline.identity,+ releaseDays: ReleaseDay.canonical(draftReleaseDays))+ return WorkDetailMetadataEdit(basis: basis, draft: draft, calendar: calendar)+ }++ private func workURLRequestForDraft() -> WorkURLRequest? {+ guard !draftWorkURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ return .clear+ }+ guard WorkURLPlanner.isValidHTTPURL(draftWorkURL) else {+ workURLStatusMessage = "Enter an absolute HTTP or HTTPS URL before saving."+ return nil+ }+ return .replaceManual(draftWorkURL)+ }++ private func commitWorkDetailTransaction(+ metadata: WorkDetailMetadataEdit?,+ recordOperations: [RecordEditOperation],+ linkOperations: [WorkLinkEditOperation],+ groupOperations: [GroupEditOperation],+ workURL: WorkURLContract?,+ membershipRemovalHostnames: [String],+ offerEvent: UUID?,+ offerGeneration: Int+ ) async {+ guard !isSubmitting else { return }+ isSubmitting = true+ state = .submitting+ cancelThumbnailPick()+ errorMessage = nil+ recordRefusalRoutesToCheckLibrary = false+ do {+ let outcome = try await library.commitWorkDetailEdit(WorkDetailEditTransaction(+ workID: workID, metadata: metadata,+ recordOperations: recordOperations, linkOperations: linkOperations,+ groupOperations: groupOperations, workURL: workURL,+ membershipRemovalHostnames: membershipRemovalHostnames))+ switch outcome {+ case .metadataRefused(let receipt):+ if case .conflict(let conflict) = receipt.outcome {+ errorMessage = EntryDetailModel.conflictMessage(conflict)+ state = .error(message: errorMessage ?? "")+ await onConflict(conflict)+ if case .seriesMissing(_, let missingSeriesID) = conflict {+ let carried = work?.series.flatMap {+ $0.id == missingSeriesID ? nil : $0+ }+ seriesOptions = await seriesPickerOptions(carrying: carried)+ if draftSeriesID == missingSeriesID {+ draftSeriesID = nil+ draftPositionText = ""+ }+ }+ if case .creatorMissing(_, let missingCreatorID) = conflict {+ await loadCreatorOptions()+ removeCredit(for: missingCreatorID)+ }+ if case .roleMissing(_, let missingRoleID) = conflict {+ await reloadRoleOptions()+ for index in draftCredits.indices {+ draftCredits[index].shownRoleIDs.remove(missingRoleID)+ draftCredits[index].unresolvedRoles.removeAll { $0.id == missingRoleID }+ }+ }+ } else {+ errorMessage = "The Work changed before these edits could be saved. Nothing was saved."+ state = .error(message: errorMessage ?? "")+ }+ isSubmitting = false+ return+ case .recordRefused(let refusal):+ errorMessage = recordRefusalMessage(refusal)+ if case .torn = refusal { recordRefusalRoutesToCheckLibrary = true }+ if case .workTorn = refusal { recordRefusalRoutesToCheckLibrary = true }+ state = .error(message: errorMessage ?? "")+ isSubmitting = false+ return+ case .groupRefused:+ errorMessage = "A character group changed before these edits could be saved. Nothing was saved."+ state = .error(message: errorMessage ?? "")+ isSubmitting = false+ return+ case .linkRefused(let refusal):+ errorMessage = SeriesRefusalPresentation.sentence(for: refusal)+ state = .error(message: errorMessage ?? "")+ isSubmitting = false+ return+ case .urlRefused(let refusal):+ switch refusal {+ case .refreshed(let fresh):+ applyProjection(fresh, replaceDraft: false)+ workURLStatusMessage = "The Work changed while you were editing. Review the updated suggestion and try again."+ case .invalidated(let reason):+ workURLStatusMessage = reason+ case .committed:+ workURLStatusMessage = "The Work URL could not be saved with the other edits. Nothing was saved."+ }+ isSubmitting = false+ return+ case .committed(let receipt, _, _):+ rememberRecordCopyTransition(receipt, event: offerEvent, generation: offerGeneration)+ if let workURL { applyProjection(workURL, replaceDraft: true) }+ stagedRecordOperations = []+ stagedMembershipRemovals = []+ stagedCharacterGroups = [:]+ isSubmitting = false+ state = .ready+ isEditing = false+ cancelCoverFetch()+ onEditingChange?(self)+ if offerGeneration == recordCopySaveGeneration,+ offerEvent == recordCopySaveEventID {+ recordCopySaveEventID = nil+ let event = offerEvent+ let join = pendingRecordCopyJoin+ pendingRecordCopyJoin = nil+ if let event, let join {+ await recordCopyOffers.enqueue(eventID: event, transitions: [join])+ }+ }+ await onMutation()+ await load(preservingDrafts: false)+ return+ }+ } catch {+ errorMessage = error.localizedDescription+ state = .error(message: error.localizedDescription)+ }+ isSubmitting = false+ }+ /// Navigation/cancel retires intent without undoing a metadata save that /// already joined the series before another editor step refused. func discardRecordCopyOffers() {@@ -2631,6 +2907,7 @@ public final class WorkDetailModel { // the cover's reason. restoreLinkDraftsFromPresentation() stagedMembershipRemovals = []+ stagedCharacterGroups = [:] guard let work else { return } draftTitle = work.displayTitle draftAssignment = work.typeDisplay.assignment@@ -2658,6 +2935,24 @@ public final class WorkDetailModel { adoptRecordDrafts((presentation?.characters ?? []) + (presentation?.places ?? [])) } + private func commitGroupStep(_ operations: [GroupEditOperation]) async -> Bool {+ guard !operations.isEmpty else { return true }+ do {+ switch try await library.commitGroupEdits(workID: workID,+ operations: operations, currentChapterID: nil) {+ case .committed:+ stagedCharacterGroups = [:]+ return true+ case .refused:+ errorMessage = "A character group changed before Save. Your group edits are still here; cancel and reopen to reload."+ return false+ }+ } catch {+ errorMessage = error.localizedDescription+ return false+ }+ }+ // MARK: - The finished-reading rule (Decision 1, Reqs 3.1–3.5) /// What the "Mark as finished?" dialog is offering, or nil when none is up.@@ -2998,7 +3293,7 @@ public final class WorkDetailModel { switch staged { case .create(let id): guard let draft = recordDrafts[id] else { continue }- operations.append(.create(draft))+ operations.append(.createIdentified(id: id, draft: draft)) handled.insert(id) case .delete(let id): guard let basis = recordBases[id] else { continue }
diff --git a/Asterism/Asterism/Views/CharacterGroupEditorView.swift b/Asterism/Asterism/Views/CharacterGroupEditorView.swiftnew file mode 100644index 00000000..a82fd525--- /dev/null+++ b/Asterism/Asterism/Views/CharacterGroupEditorView.swift@@ -0,0 +1,223 @@+import AsterismCore+import ConstellationKit+import SwiftUI++struct CharacterGroupEditorView: View {+ @Bindable var model: CharacterGroupEditorModel+ let characters: [CharacterGroupMemberOption]+ let chapters: [WorkChapterRow]+ @Environment(\.dismiss) private var dismiss+ @State private var characterID: UUID?+ @State private var chapterID: UUID?+ @State private var action: GroupTransitionAction = .join++ var body: some View {+ NavigationStack {+ List {+ Section("Group") {+ TextField("Name", text: $model.name)+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityIdentifier("group-editor.name")+ TextField("Aliases (one per line)", text: $model.aliases, axis: .vertical)+ .lineLimit(1...4)+ .accessibilityIdentifier("group-editor.aliases")+ }+ Section("Membership history") {+ ForEach(model.transitions.filter { $0.action != .remove }, id: \.rootID) { transition in+ membershipTransitionRow(transition)+ }+ ForEach(model.conflictedTransitions) { conflict in+ conflictedTransitionRow(conflict)+ }+ VStack(alignment: .leading, spacing: 8) {+ Picker("Character", selection: $characterID) {+ Text("Choose character").tag(UUID?.none)+ ForEach(characters.filter { !$0.isTorn }) {+ Text($0.name)+ .tag(Optional($0.id))+ .accessibilityIdentifier("group-editor.character-option.\($0.id)")+ }+ }+ .labelsHidden()+ .accessibilityLabel("Character for membership change")+ .frame(maxWidth: .infinity)+ HStack(spacing: 10) {+ chapterMenu(selection: $chapterID,+ identifier: "group-editor.new-transition-chapter")+ actionControl(selection: $action,+ identifier: "group-editor.new-transition-action")+ .frame(maxWidth: .infinity)+ }+ }+ Button("Add transition") {+ if let characterID, let chapterID {+ model.addMember(characterID: characterID, chapterID: chapterID, action: action)+ }+ }+ .disabled(characterID == nil || chapterID == nil)+ .accessibilityIdentifier("group-editor.add-transition")+ }+ if let error = model.errorMessage {+ Section {+ Text(error).foregroundStyle(.red).accessibilityIdentifier("group-editor.error")+ }+ }+ if model.canDelete {+ Section {+ ConstellationDestructiveRow(title: "Delete group") {+ Task { if await model.save(deleting: true) { dismiss() } }+ }+ .disabled(model.isSaving)+ .accessibilityIdentifier("group-editor.delete")+ } footer: {+ Text("Deletes this group and its membership history when you save.")+ }+ }+ }+ .scrollContentBackground(.hidden)+ .macListChrome()+ .navigationTitle("Character group")+ .inlineNavigationTitle()+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button(role: .close) { dismiss() }+ .disabled(model.isSaving)+ .accessibilityLabel("Cancel")+ .accessibilityIdentifier("group-editor.cancel")+ }+ ToolbarItem(placement: .confirmationAction) {+ Button(role: .confirm) { Task { if await model.save() { dismiss() } } }+ .disabled(model.isSaving)+ .accessibilityLabel("Done")+ .accessibilityIdentifier("group-editor.save")+ }+ }+ }+ }++ private func chapterMenu(selection: Binding<UUID?>, identifier: String) -> some View {+ let selected = chapters.first { $0.id == selection.wrappedValue }+ return Menu {+ ForEach(chapters) { chapter in+ Button(chapter.displayTitle) { selection.wrappedValue = chapter.id }+ }+ } label: {+ HStack(spacing: 6) {+ Text(selected.map(compactChapterLabel) ?? "Choose chapter")+ .lineLimit(1)+ .truncationMode(.tail)+ Image(systemName: "chevron.up.chevron.down").font(.caption)+ }+ .frame(maxWidth: .infinity)+ }+ .accessibilityLabel("Chapter for membership change")+ .accessibilityValue(selected?.displayTitle ?? "Choose chapter")+ .accessibilityIdentifier(identifier)+ }++ private func memberName(for id: UUID) -> String {+ characters.first(where: { $0.id == id })?.name ?? "Unavailable character"+ }++ private func membershipTransitionRow(_ transition: GroupTransitionFact) -> some View {+ let name: String = memberName(for: transition.characterID)+ let chapterSelection = Binding<UUID?>(+ get: { transition.chapterID },+ set: { if let chapterID = $0 { model.revise(transition, chapterID: chapterID, action: transition.action) } }+ )+ let actionSelection = Binding<GroupTransitionAction>(+ get: { transition.action },+ set: { model.revise(transition, chapterID: transition.chapterID, action: $0) }+ )+ return VStack(alignment: .leading, spacing: 8) {+ HStack {+ Text(name).font(AsterismTypography.serifRowTitle)+ Spacer(minLength: 8)+ Button("Remove", role: .destructive) { model.remove(transition) }+ .accessibilityLabel("Remove membership change")+ }+ HStack(spacing: 10) {+ chapterMenu(selection: chapterSelection,+ identifier: "group-editor.transition-chapter.\(transition.rootID)")+ actionControl(selection: actionSelection,+ identifier: "group-editor.transition-action.\(transition.rootID)")+ }+ }+ .padding(.vertical, 4)+ }++ private func conflictedTransitionRow(_ conflict: GroupTransitionConflict) -> some View {+ let chapterSelection = Binding<UUID?>(+ get: { model.conflictChapter(conflict.rootID) },+ set: { model.chooseConflictChapter(conflict.rootID, chapterID: $0) })+ let actionSelection = Binding<GroupTransitionAction?>(+ get: { model.conflictAction(conflict.rootID) },+ set: { model.chooseConflictAction(conflict.rootID, action: $0) })+ let removing = model.conflictAction(conflict.rootID) == .remove+ return VStack(alignment: .leading, spacing: 8) {+ HStack {+ Text(memberName(for: conflict.characterID))+ .font(AsterismTypography.serifRowTitle)+ Spacer(minLength: 8)+ Button(removing ? "Undo remove" : "Remove", role: removing ? nil : .destructive) {+ model.toggleConflictRemoval(conflict.rootID)+ }+ .accessibilityIdentifier("group-editor.conflict-remove.\(conflict.rootID)")+ }+ if removing {+ Text("This membership change will be removed when you save the Work.")+ } else {+ Text("Choose a chapter and Join or Leave to resolve this membership change.")+ .font(.caption)+ HStack(spacing: 10) {+ chapterMenu(selection: chapterSelection,+ identifier: "group-editor.conflict-chapter.\(conflict.rootID)")+ ConstellationLiquidGlassSegmentedControl<GroupTransitionAction?>(+ values: [.join, .leave], selection: actionSelection,+ containerLabel: "Membership action",+ title: { $0 == .join ? "Join" : "Leave" },+ identifier: { "group-editor.conflict-action.\(conflict.rootID).\($0?.rawValue ?? "")" },+ controlIdentifier: "group-editor.conflict-action.\(conflict.rootID)")+ .frame(maxWidth: .infinity)+ }+ }+ }+ .padding(.vertical, 4)+ }++ private func actionControl(+ selection: Binding<GroupTransitionAction>, identifier: String+ ) -> some View {+ ConstellationLiquidGlassSegmentedControl(+ values: [.join, .leave],+ selection: selection,+ containerLabel: "Membership action",+ title: { $0 == .join ? "Join" : "Leave" },+ identifier: { "\(identifier).\($0.rawValue)" },+ controlIdentifier: identifier)+ }++ private func compactChapterLabel(_ chapter: WorkChapterRow) -> String {+ if let key = chapter.gutterChapterKey ?? chapter.chapterKey {+ return "Chapter \(key.label)"+ }+ if let position = chapter.sequencePosition {+ return "Chapter \(position.label)"+ }++ // A title prefix is used only when it uniquely identifies this option+ // among the Work's chapters; VoiceOver and the menu retain full titles.+ let title = chapter.displayTitle.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !title.isEmpty else { return "Chapter" }+ let others = chapters.filter { $0.id != chapter.id }.map(\.displayTitle)+ let uniquePrefixLength = (1...title.count).first { length in+ let prefix = String(title.prefix(length))+ return others.allSatisfy {+ $0.range(of: prefix, options: [.caseInsensitive, .anchored]) == nil+ }+ }+ guard let uniquePrefixLength else { return title }+ if uniquePrefixLength >= title.count { return title }+ return String(title.prefix(uniquePrefixLength)) + "…"+ }+}
diff --git a/Asterism/Asterism/Views/CharacterReviewView.swift b/Asterism/Asterism/Views/CharacterReviewView.swiftindex c972ea78..f726f03c 100644--- a/Asterism/Asterism/Views/CharacterReviewView.swift+++ b/Asterism/Asterism/Views/CharacterReviewView.swift@@ -27,7 +27,7 @@ struct CharacterReviewView: View { reviewContent } }- .navigationTitle("Suggested characters and places")+ .navigationTitle("Suggested characters, places and groups") .toolbar { // Every row commits on its own, so this button commits nothing — // it leaves the list, and undecided rows stay for a later visit@@ -85,6 +85,31 @@ struct CharacterReviewView: View { rowContent(row) } }+ ForEach(model.groupRows) { row in+ Section {+ Text(groupActionCaption(kind: row.kind,+ characterName: row.characterName))+ .font(.caption)+ .foregroundStyle(.secondary)+ if let quote = row.quote {+ Text(quote)+ .textSelection(.enabled)+ .accessibilityIdentifier("group-review-quote-\(row.id)")+ }+ ProposalSourceEvidenceView(evidence: [row.sourceEvidence], rowID: row.id)+ HStack(spacing: 12) {+ Button("Keep") { Task { await model.acceptGroup(row.id) } }+ .buttonStyle(.constellationPrimary)+ .accessibilityIdentifier("group-review-keep-\(row.id)")+ Button("Skip") { Task { await model.skipGroup(row.id) } }+ .buttonStyle(.constellationSecondary)+ .accessibilityIdentifier("group-review-skip-\(row.id)")+ }+ .disabled(model.isSubmitting)+ } header: {+ ConstellationSectionHeader(row.groupName, accent: .cyan)+ }+ } } .scrollDismissesKeyboard(.immediately) .accessibilityIdentifier("character-review-list")@@ -115,6 +140,11 @@ struct CharacterReviewView: View { .accessibilityIdentifier("character-review-keyboard-done") } + private func groupActionCaption(kind: GroundedGroupSuggestion.Kind,+ characterName: String?) -> String {+ GroupReviewActionCaption.text(kind: kind, characterName: characterName)+ }+ /// Req 2.1: every row says which collection it would join. The name is the /// header the sheet has always drawn; the kind is a caption under it, so a /// place row is not a character row with a different word in it.@@ -289,3 +319,14 @@ struct CharacterReviewView: View { set: { model.setTicked($0, factID: fact.id, in: row.id) }) } }++enum GroupReviewActionCaption {+ static func text(kind: GroundedGroupSuggestion.Kind, characterName: String?) -> String {+ let character = characterName ?? "Character"+ switch kind {+ case .create: return "Create this group"+ case .join: return "Add \(character) from this chapter"+ case .leave: return "\(character) remains in the group through this chapter; removal starts afterward."+ }+ }+}
diff --git a/Asterism/Asterism/Views/EntryDetailView.swift b/Asterism/Asterism/Views/EntryDetailView.swiftindex bf2dc4c6..76012293 100644--- a/Asterism/Asterism/Views/EntryDetailView.swift+++ b/Asterism/Asterism/Views/EntryDetailView.swift@@ -464,24 +464,33 @@ struct EntryDetailView: 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)+ HStack {+ 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())+ }+ .disabled(association.isRemoved)+ .accessibilityIdentifier("entry-association-\(association.pair.kind.rawValue)-\(association.pair.recordID.uuidString)")+ .accessibilityLabel("\(association.recordName), \(RecordKindPresentation.noun(association.pair.kind)), chapter link note")+ Button(association.isRemoved ? "Restore" : "Remove") {+ Task { await model.correctChapterAssociation(association) } }- .frame(maxWidth: .infinity, alignment: .leading)- .contentShape(Rectangle())+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityIdentifier("entry-association-\(association.isRemoved ? "restore" : "remove")-\(association.pair.kind.rawValue)-\(association.pair.recordID.uuidString)") }- .accessibilityIdentifier("entry-association-\(association.pair.kind.rawValue)-\(association.pair.recordID.uuidString)")- .accessibilityLabel("\(association.recordName), \(RecordKindPresentation.noun(association.pair.kind)), chapter link note")+ .buttonStyle(.borderless) } Button("Skipped character links") { skippedLinks = model.skippedCharacterLinksModel() } .accessibilityIdentifier("entry-skipped-character-links")
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex 7a9fb447..b51fa051 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -91,9 +91,11 @@ struct WorkDetailView: View { /// The review sheet, `@State`-owned so its snapshot survives a re-render /// (Req 2.7). @State private var reviewModel: CharacterReviewModel?+ @State private var groupEditor: CharacterGroupEditorModel? /// Which character's detail card is open under the cast pills; nil folds /// every quote away. @State private var expandedCharacterID: UUID?+ @State private var expandedGroupID: UUID? /// The same, for the Places section (`place-extraction` Req 4.1). Its own /// selection rather than one shared with the cast: the two sections sit one /// above the other, and opening a place would otherwise fold a character's@@ -245,6 +247,10 @@ struct WorkDetailView: View { .intentEditSession(active: model.isEditing || presentsSheet) .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { detailWidth = $0 } .screenSky(showsSky)+ .sheet(item: $groupEditor) { editor in+ CharacterGroupEditorView(model: editor, characters: model.groupCharacterOptions,+ chapters: model.chapterRows)+ } #if DEBUG .safeAreaInset(edge: .bottom) { if model.historyRefreshTestPublish != nil {@@ -359,6 +365,7 @@ struct WorkDetailView: View { editCreditsSection editSeriesSection editCharactersSection+ editGroupsSection editPlacesSection manageSection }@@ -523,6 +530,7 @@ struct WorkDetailView: View { seriesSection openLastNotedSection charactersSection+ groupsSection placesSection relatedWorksSection chapterSection@@ -574,6 +582,7 @@ struct WorkDetailView: View { wideMetadata(work) openLastNotedSection charactersSection+ groupsSection placesSection relatedWorksSection }.frame(width: 300)@@ -1375,21 +1384,22 @@ struct WorkDetailView: View { private var editStatusSection: some View { Section { VStack(alignment: .leading, spacing: 12) {- ConstellationSegmentedControl(+ ConstellationLiquidGlassSegmentedControl( values: WorkStatus.allCases, selection: Binding( get: { model.draftWorkStatus }, set: { model.setDraftWorkStatus($0) }), containerLabel: "Work status", title: WorkStatusPresentation.name,- identifier: WorkStatusPresentation.controlIdentifier)+ identifier: WorkStatusPresentation.controlIdentifier,+ controlIdentifier: "work-detail-work-status-control") .constellationCaptionedField("Work status") if model.draftWorkStatus == .hiatus { returnDateField } - ConstellationSegmentedControl(+ ConstellationLiquidGlassSegmentedControl( values: ReadingStatus.allCases, selection: Binding( get: { model.draftReadingStatus },@@ -1399,7 +1409,8 @@ struct WorkDetailView: View { set: { model.setDraftReadingStatus($0) }), containerLabel: "Reading status", title: ReadingStatusPresentation.name,- identifier: ReadingStatusPresentation.controlIdentifier)+ identifier: ReadingStatusPresentation.controlIdentifier,+ controlIdentifier: "work-detail-reading-status-control") .constellationCaptionedField("Reading status") // Req 2.3: present exactly while the draft reading status is@@ -1997,12 +2008,13 @@ struct WorkDetailView: View { /// `stats-period-navigation` Q28). The stacking, the surface, the 44 pt /// target and the `.isSelected` trait all live there now. private var sortControl: some View {- ConstellationSegmentedControl(+ ConstellationLiquidGlassSegmentedControl( values: WorkDetailModel.ChapterSortOrder.allCases, selection: $sortOrder, containerLabel: "Sort order", title: \.title,- identifier: \.controlIdentifier)+ identifier: \.controlIdentifier,+ controlIdentifier: "work-detail-sort-control") } /// Edit mode's structural actions (Decision 5), plus the two URL-identity@@ -2280,7 +2292,7 @@ struct WorkDetailView: View { // places in it would be the screen lying about its own // button. Label(- "\(Pluralisation.count(extraction.held(for: work.id).count, "suggestion", "suggestions")) from your notes",+ "\(Pluralisation.count(extraction.held(for: work.id).count + extraction.heldGroups(for: work.id).count, "suggestion", "suggestions")) from your notes", systemImage: "sparkles") .font(.callout) .foregroundStyle(AsterismColors.primaryText)@@ -2307,6 +2319,98 @@ struct WorkDetailView: View { /// Req 5.1/5.2's view-mode section, in the `chapterSection` idiom: absent /// when the work has no characters, and its facts already in Q88's display /// order — the repository's, not this view's.+ @ViewBuilder+ private var groupsSection: some View {+ if !model.characterGroups.isEmpty {+ Section {+ FlowLayout(spacing: 8) {+ ForEach(model.characterGroups, id: \.groupID) { group in+ let name = group.name ?? "Unresolved group"+ let isExpanded = expandedGroupID == group.groupID+ Button {+ withAnimation(.snappy) {+ expandedGroupID = isExpanded ? nil : group.groupID+ }+ } label: {+ HStack(spacing: 5) {+ Text(name)+ Image(systemName: "chevron.down")+ .font(.caption2)+ .rotationEffect(.degrees(isExpanded ? 180 : 0))+ .accessibilityHidden(true)+ }+ .constellationPill(isExpanded ? .selectedTypeTag : .typeTag)+ }+ .buttonStyle(.plain)+ .accessibilityIdentifier("work-detail.group.\(group.groupID)")+ .accessibilityLabel("\(name), group")+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .constellationListRow()+ if let group = model.characterGroups.first(where: { $0.groupID == expandedGroupID }) {+ groupDetailCard(group)+ }+ } header: { ConstellationSectionHeader("Groups", accent: .violet) }+ }+ }++ private func groupDetailCard(_ group: GroupSummary) -> some View {+ let members = model.characters.filter { group.members[$0.id] != nil }+ return VStack(alignment: .leading, spacing: 10) {+ FlowLayout(spacing: 8) {+ Text(group.name ?? "Unresolved group")+ .font(AsterismTypography.serifHeading)+ ForEach(group.aliases, id: \.self) { alias in+ Text(alias).constellationPill(.count)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ if members.isEmpty {+ Text("No members").foregroundStyle(AsterismColors.secondaryText)+ } else {+ ForEach(members) { character in+ Text(GroupMembershipText.membership(+ name: character.name, ranges: group.members[character.id] ?? []))+ .font(.subheadline)+ .foregroundStyle(AsterismColors.primaryText)+ .accessibilityIdentifier("work-detail.group-member.\(group.groupID).\(character.id)")+ }+ }+ }+ .padding(12)+ .constellationCard()+ .constellationListRow()+ }++ /// Group editing follows the compact captioned-card pattern used by the+ /// character and place collections. Creation is part of Work edit mode;+ /// reading mode keeps only the roster disclosure above.+ private var editGroupsSection: some View {+ Section {+ VStack(alignment: .leading, spacing: 12) {+ if !model.characterGroups.isEmpty {+ VStack(alignment: .leading, spacing: 6) {+ ForEach(model.characterGroups, id: \.groupID) { group in+ let memberCount = group.members.count+ ConstellationLineRow(+ name: group.name ?? "Unresolved group",+ detail: memberCount == 0 ? nil : Pluralisation.count(memberCount, "member", "members"),+ action: { groupEditor = model.groupEditor(group) })+ .accessibilityIdentifier("work-detail.group-edit.\(group.groupID)")+ }+ }+ }+ ConstellationFooterButton(title: "Add group") {+ groupEditor = model.groupEditor()+ }+ .disabled(model.isReadOnly)+ .accessibilityIdentifier("work-detail.add-group")+ }+ .constellationCaptionedCard("Character groups")+ }+ }+ @ViewBuilder private var charactersSection: some View { if !model.characters.isEmpty || offersManualPass {@@ -2503,6 +2607,11 @@ struct WorkDetailView: View { .frame(maxWidth: .infinity, alignment: .leading) } + if record.kind == .character {+ ForEach(GroupMembershipText.character(record.id, groups: model.characterGroups), id: \.self) {+ Text($0).font(.subheadline)+ }+ } RecordHistoryView(model: model, kind: record.kind, recordID: record.id, onSelectEntry: onSelectEntry) @@ -2805,6 +2914,7 @@ struct WorkDetailView: View { reviewModel = CharacterReviewModel( workID: workID, proposals: extraction.held(for: workID),+ groupProposals: extraction.heldGroups(for: workID), characters: model.characters, places: model.places, captureOrder: model.captureOrder,@@ -2838,7 +2948,19 @@ struct WorkDetailView: View { refresh: { await extraction.reconcile() return extraction.held(for: workID)- }, currentHeld: { extraction.held(for: workID) })+ }, currentHeld: { extraction.held(for: workID) },+ hasUndecidedGroupSource: { source, fingerprint in+ extraction.heldGroups(for: workID).contains {+ source.entryID == $0.chapterID && $0.sourceFingerprint == fingerprint+ }+ },+ onGroupDecision: { id, action in+ if action == .accept {+ return try await extraction.acceptGroup(id, workID: workID)+ }+ return try await extraction.skipGroup(id, workID: workID)+ },+ currentHeldGroups: { extraction.heldGroups(for: workID) }) } private func runManualPass(workID: UUID) async {
diff --git a/Asterism/Asterism/Views/WorksStatusSheet.swift b/Asterism/Asterism/Views/WorksStatusSheet.swiftindex b2aabc79..61282b94 100644--- a/Asterism/Asterism/Views/WorksStatusSheet.swift+++ b/Asterism/Asterism/Views/WorksStatusSheet.swift@@ -12,10 +12,12 @@ struct WorksStatusSheet: View { NavigationStack { Form { if model.isEditing {- ConstellationSegmentedControl(values: ReadingStatus.allCases,+ ConstellationLiquidGlassSegmentedControl(values: ReadingStatus.allCases, selection: Binding(get: { model.draftReadingStatus }, set: model.setDraftReadingStatus), containerLabel: "Reading status", title: ReadingStatusPresentation.name,- identifier: ReadingStatusPresentation.controlIdentifier)+ identifier: ReadingStatusPresentation.controlIdentifier,+ controlIdentifier: "works-status-sheet-reading-status-control")+ .constellationCaptionedField("Reading status") if let prompt = ReadingStatusPresentation.verdictPrompt(model.draftReadingStatus) { TextField(prompt, text: $model.draftVerdict, axis: .vertical) }
diff --git a/Asterism/AsterismShareExtension/CaptureView.swift b/Asterism/AsterismShareExtension/CaptureView.swiftindex cafd3c93..06541639 100644--- a/Asterism/AsterismShareExtension/CaptureView.swift+++ b/Asterism/AsterismShareExtension/CaptureView.swift@@ -301,6 +301,11 @@ struct CaptureView: View { // renders for a work without characters, for a projection that // names no existing work, or for a failed read — the list is empty // in all three cases.+ if !viewModel.workContext.groups.isEmpty {+ Text("Character groups").font(.caption)+ ShareCharacterChipsView(+ characters: viewModel.workContext.groups, identifierPrefix: "capture.groups")+ } if !viewModel.workContext.characters.isEmpty { ShareCharacterChipsView( characters: viewModel.workContext.characters,
diff --git a/Asterism/AsterismShareExtension/ReShareCaptureView.swift b/Asterism/AsterismShareExtension/ReShareCaptureView.swiftindex 8e62d677..ae7f4ef3 100644--- a/Asterism/AsterismShareExtension/ReShareCaptureView.swift+++ b/Asterism/AsterismShareExtension/ReShareCaptureView.swift@@ -130,6 +130,10 @@ struct ReShareCaptureView: View { // The work's cast (T-1916, T-2317). One chip per character; nothing // renders for a work without characters, which is also what a failed // read leaves behind — an empty list either way.+ if !state.workContext.groups.isEmpty {+ Text("Character groups").font(.caption)+ ShareCharacterChipsView(characters: state.workContext.groups, identifierPrefix: "reshare.groups")+ } if !state.workContext.characters.isEmpty { ShareCharacterChipsView( characters: state.workContext.characters,
diff --git a/Asterism/AsterismTests/CharacterExtractionCoordinatorTests.swift b/Asterism/AsterismTests/CharacterExtractionCoordinatorTests.swiftindex 51918b4e..ee7e2747 100644--- a/Asterism/AsterismTests/CharacterExtractionCoordinatorTests.swift+++ b/Asterism/AsterismTests/CharacterExtractionCoordinatorTests.swift@@ -92,6 +92,23 @@ struct CharacterExtractionCoordinatorTests { suppressions: [.character: suppressions, .place: placeSuppressions]) } + private nonisolated static func groupChapterCandidate(workID: UUID, chapterID: UUID,+ note: String = "Missha joins Team Loser.",+ knownGroupNames: [String] = [],+ characters: [MatchTarget] = [],+ characterSuppressions: SuppressionIndex = .empty) -> ExtractionCandidate {+ let fingerprint = CharacterCoverageFingerprint.of(note)+ return ExtractionCandidate(workID: workID, displayTitle: "Book",+ recency: Date(timeIntervalSince1970: 0), sources: [+ CharacterExtractionSource(ref: .entry(chapterID), text: note,+ fingerprint: fingerprint, coveredFingerprint: nil,+ isChapter: true, knownGroupNames: knownGroupNames)], records: [+ .character: characters+ ], acceptedFacts: [:], suppressions: [+ .character: characterSuppressions+ ], knownGroupNames: knownGroupNames)+ }+ /// One work whose two sources both name "Bay", so the pass can hold a /// dual-kind row from one response and a plain place row from the other — /// the shape Q56's cross-kind discard is about.@@ -404,6 +421,271 @@ struct CharacterExtractionCoordinatorTests { #expect(advance?.sources.first?.fingerprint == CharacterCoverageFingerprint.of(notes)) } + @Test("Grounded group-only output remains held and keeps its chapter uncovered")+ func groupSuggestionsStayPending() async {+ let workID = UUID(), chapterID = UUID()+ let stub = StubCharacterExtractionModelClient(result: ExtractionResult(+ groups: [.init(name: "Team Loser")],+ groupJoins: [.init(groupName: "Team Loser", characterName: "Missha",+ quote: "Missha joins Team Loser")]))+ let (coordinator, mock, _, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: chapterID)], stub: stub)+ await coordinator.runManualPass(workID: workID)+ #expect(coordinator.heldGroups(for: workID).count == 2)+ #expect(coordinator.hasProposals(for: workID))+ #expect(coordinator.manualOutcome(for: workID) == .proposals(2))+ #expect(mock.advancedCoverage.isEmpty)+ }++ @Test("Removing the last stale group proposal releases its retained context")+ func removedLastGroupProposalReleasesContext() async {+ let workID = UUID(), chapterID = UUID()+ let stub = StubCharacterExtractionModelClient(result: ExtractionResult(+ groups: [.init(name: "Team Loser")],+ groupJoins: [.init(groupName: "Team Loser", characterName: "Missha",+ quote: "Missha joins Team Loser")]))+ let (coordinator, mock, _, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: chapterID)], stub: stub)++ await coordinator.runManualPass(workID: workID)++ #expect(coordinator.heldGroups(for: workID).count == 2)+ #expect(coordinator.context(for: workID) != nil)+ #expect(mock.extractionCandidatesCallCount == 1)++ // The source disappears while both claims are pending. Reconciliation+ // must drop the final group bucket as well as its cached context.+ mock.extractionCandidatesResult = .success([])+ await coordinator.reconcile()++ #expect(coordinator.heldGroups(for: workID).isEmpty)+ #expect(coordinator.context(for: workID) == nil)+ #expect(mock.extractionCandidatesCallCount == 2)++ // An empty dictionary bucket must not keep a removed work tracked.+ await coordinator.reconcile()+ #expect(mock.extractionCandidatesCallCount == 2)+ }++ @Test("The last group decision covers its chapter only after sibling claims settle")+ func lastGroupDecisionCompletesSource() async throws {+ let workID = UUID(), chapterID = UUID()+ let stub = StubCharacterExtractionModelClient(result: ExtractionResult(+ groups: [.init(name: "Team Loser")],+ groupJoins: [.init(groupName: "Team Loser", characterName: "Missha",+ quote: "Missha joins Team Loser")]))+ let (coordinator, mock, _, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: chapterID)], stub: stub)+ await coordinator.runManualPass(workID: workID)+ let create = try #require(coordinator.heldGroups(for: workID).first { $0.kind == .create })+ let join = try #require(coordinator.heldGroups(for: workID).first { $0.kind == .join })+ _ = try await coordinator.acceptGroup(create.id, workID: workID)+ #expect(mock.advancedCoverage.isEmpty)+ #expect(coordinator.heldGroups(for: workID).map(\.id) == [join.id])+ _ = try await coordinator.skipGroup(join.id, workID: workID)+ #expect(mock.advancedCoverage.count == 1)+ #expect(mock.advancedCoverage.first?.sources.map(\.ref) == [.entry(chapterID)])+ #expect(coordinator.heldGroups(for: workID).isEmpty)+ }++ @Test("Automatic extraction honours a durable group Skip while a manual pass can reconsider")+ func skippedGroupAutomaticAndManual() async {+ let workID = UUID(), chapterID = UUID()+ let stub = StubCharacterExtractionModelClient(result: ExtractionResult(+ groupJoins: [.init(groupName: "Team Loser", characterName: "Missha",+ quote: "Missha joins Team Loser")]))+ let (coordinator, mock, _, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: chapterID)], stub: stub)+ mock.groupSuggestionSkipsResult = [.init(workID: workID, chapterID: chapterID,+ kind: .join, groupKey: "team loser", characterKey: "missha",+ evidenceKey: "Missha joins Team Loser")]+ await coordinator.activationSweep()+ #expect(coordinator.heldGroups(for: workID).isEmpty)+ #expect(mock.advancedCoverage.count == 1)+ await coordinator.runManualPass(workID: workID)+ #expect(coordinator.heldGroups(for: workID).count == 1)+ #expect(coordinator.manualOutcome(for: workID) == .proposals(1))+ }++ @Test("A join already effective in the saved chapter is not offered again")+ func effectiveJoinIsFiltered() async {+ let workID = UUID(), chapterID = UUID()+ let stub = StubCharacterExtractionModelClient(result: ExtractionResult(+ groupJoins: [.init(groupName: "Team Loser", characterName: "Missha",+ quote: "Missha joins Team Loser")]))+ let (coordinator, mock, _, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: chapterID)], stub: stub)+ mock.effectiveGroupJoins = ["\(chapterID.uuidString)/team loser/missha"]+ await coordinator.runManualPass(workID: workID)+ #expect(coordinator.heldGroups(for: workID).isEmpty)+ #expect(coordinator.manualOutcome(for: workID) == .noProposals)+ #expect(mock.advancedCoverage.count == 1)+ }++ @Test("An accepted inclusive leave is not proposed again during re-extraction")+ func acceptedLeaveIsFilteredAfterReextraction() async {+ let workID = UUID(), chapterID = UUID()+ let stub = StubCharacterExtractionModelClient(result: ExtractionResult(+ groupLeaves: [.init(groupName: "The Losers", characterName: "Ainar",+ quote: "Ainar leaves Team Loser")]))+ let (coordinator, mock, _, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: chapterID,+ note: "Ainar leaves Team Loser after the match.",+ knownGroupNames: ["Team Loser", "The Losers"] )], stub: stub)+ mock.effectiveGroupJoins = ["\(chapterID.uuidString)/the losers/ainar"]+ mock.applicableGroupLeaves = []++ await coordinator.runManualPass(workID: workID)++ #expect(coordinator.heldGroups(for: workID).isEmpty)+ #expect(coordinator.manualOutcome(for: workID) == .noProposals)+ }++ @Test("Leave Skip is durable for automatic extraction and reconsiderable manually")+ func skippedLeaveAutomaticAndManual() async {+ let workID = UUID(), chapterID = UUID()+ let note = "Ainar leaves Team Loser after the match."+ let stub = StubCharacterExtractionModelClient(result: ExtractionResult(+ groupLeaves: [.init(groupName: "Team Loser", characterName: "Ainar",+ quote: "Ainar leaves Team Loser")]))+ let (coordinator, mock, _, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: chapterID, note: note,+ knownGroupNames: ["Team Loser"], characters: [MatchTarget(id: UUID(),+ currentNameKey: "ainar", retainedKey: "ainar", aliasKeys: [], isTorn: false)])], stub: stub)+ let evidence = GroupSuggestionSkip(workID: workID, chapterID: chapterID,+ kind: .leave, groupKey: "team loser", characterKey: "ainar",+ evidenceKey: "Ainar leaves Team Loser")+ mock.groupSuggestionSkipsResult = [evidence]+ mock.effectiveGroupJoins = ["\(chapterID.uuidString)/team loser/ainar"]+ mock.applicableGroupLeaves = ["\(chapterID.uuidString)/team loser/ainar"]++ await coordinator.activationSweep()+ #expect(coordinator.heldGroups(for: workID).isEmpty)+ await coordinator.runManualPass(workID: workID)+ #expect(coordinator.heldGroups(for: workID).count == 1)+ #expect(coordinator.heldGroups(for: workID).first?.kind == .leave)+ }++ @Test("Known group aliases prevent false characters while a grounded leave stays reviewable")+ func existingGroupLeaveSurvivesCharacterSkip() async {+ let workID = UUID(), chapterID = UUID(), ainarID = UUID()+ let note = "Ainar leaves Team Loser after the match."+ let recorder = StubCharacterExtractionModelClient.Recorder()+ let stub = StubCharacterExtractionModelClient(result: ExtractionResult(+ characters: [+ .init(name: "Team Loser"), .init(name: "The Losers"), .init(name: "Ainar")+ ],+ groupLeaves: [.init(groupName: "Team Loser", characterName: "Ainar",+ quote: "Ainar leaves Team Loser")]), recorder: recorder)+ let ainar = MatchTarget(id: ainarID, currentNameKey: "ainar", retainedKey: "ainar",+ aliasKeys: [], isTorn: false)+ let (coordinator, mock, _, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: chapterID, note: note,+ knownGroupNames: ["Team Loser", "The Losers"], characters: [ainar],+ characterSuppressions: .init(candidateKeys: ["team loser", "the losers"], factIdentities: []))],+ stub: stub)+ mock.effectiveGroupJoins.insert("\(chapterID.uuidString)/team loser/ainar")+ mock.applicableGroupLeaves.insert("\(chapterID.uuidString)/team loser/ainar")++ await coordinator.runManualPass(workID: workID)++ #expect(coordinator.held(for: workID).isEmpty)+ let leave = coordinator.heldGroups(for: workID).first+ #expect(coordinator.heldGroups(for: workID).count == 1)+ #expect(leave?.kind == .leave)+ #expect(leave?.groupName == "Team Loser")+ #expect(leave?.characterName == "Ainar")+ #expect(leave?.quote == "Ainar leaves Team Loser")+ #expect(leave?.skipIdentity.kind == .leave)+ #expect(recorder.recordedSources.first?.knownGroupNames == ["Team Loser", "The Losers"])+ #expect(mock.advancedCoverage.isEmpty)+ }++ @Test("An existing group join survives an unrelated character Skip and yields a later alias-grounded leave")+ func existingGroupAinarJoinSkipThenLeave() async throws {+ let workID = UUID(), joinChapterID = UUID(), leaveChapterID = UUID(), ainarID = UUID()+ let ainar = MatchTarget(id: ainarID, currentNameKey: "ainar", retainedKey: "ainar",+ aliasKeys: [], isTorn: false)+ let recorder = StubCharacterExtractionModelClient.Recorder()+ let joinNote = "Ainar joins Team Loser after the trial, while Borin watches."+ let joinStub = StubCharacterExtractionModelClient(result: ExtractionResult(+ characters: [.init(name: "Team Loser"), .init(name: "The Losers"), .init(name: "Ainar"), .init(name: "Borin")],+ groups: [.init(name: "Team Loser")],+ groupJoins: [.init(groupName: "Team Loser", characterName: "Ainar",+ quote: "Ainar joins Team Loser")]), recorder: recorder)+ let (coordinator, mock, client, _) = makeSUT(candidates: [Self.groupChapterCandidate(+ workID: workID, chapterID: joinChapterID, note: joinNote,+ knownGroupNames: ["Team Loser", "The Losers"], characters: [ainar],+ characterSuppressions: .init(candidateKeys: ["team loser", "the losers"], factIdentities: []))],+ stub: joinStub)+ mock.groupSummariesResult = [GroupSummary(groupID: UUID(), name: "Team Loser", aliases: ["The Losers"])]+ mock.groupEditResult = .committed(groupIDs: [mock.groupSummariesResult[0].groupID])++ await coordinator.runManualPass(workID: workID)++ #expect(recorder.recordedSources.first?.knownGroupNames == ["Team Loser", "The Losers"])+ #expect(coordinator.held(for: workID).map(\.nameKey) == ["borin"])+ #expect(!coordinator.held(for: workID).contains { ["team loser", "the losers"].contains($0.nameKey) })+ let join = try #require(coordinator.heldGroups(for: workID).first { $0.kind == .join })+ #expect(coordinator.heldGroups(for: workID).allSatisfy { $0.kind != .create })++ // Skip the independent character proposal through the same review model+ // used by the sheet, then approve the group join through its review API.+ let review = CharacterReviewModel(workID: workID, proposals: coordinator.held(for: workID),+ groupProposals: coordinator.heldGroups(for: workID), characters: [], library: mock,+ extractionContext: { coordinator.context(for: workID) },+ onDecision: { key, kinds in coordinator.discard(key, for: workID, nameKeySuppressedKinds: kinds) },+ onReRoute: { key, target in coordinator.retarget(key, for: workID, to: target) },+ onReclassify: { key, kind, target in coordinator.reclassify(key, for: workID, to: kind, target: target) },+ refresh: { await coordinator.reconcile(); return coordinator.held(for: workID) },+ currentHeld: { coordinator.held(for: workID) },+ onGroupDecision: { id, action in+ action == .accept ? try await coordinator.acceptGroup(id, workID: workID)+ : try await coordinator.skipGroup(id, workID: workID)+ }, currentHeldGroups: { coordinator.heldGroups(for: workID) })+ let borin = try #require(coordinator.held(for: workID).first)+ await review.skip(borin.key.rowID)+ #expect(mock.committedDecisions.count == 1)+ await review.acceptGroup(join.id)+ #expect(mock.groupEditCalls.last?.operations.contains {+ if case .approveSuggestion(let approval) = $0 { return approval.action == .join }+ return false+ } == true)++ // The next saved chapter is read with the accepted roster. Its actual+ // model response uses the group alias, while the quote uses the name.+ let leaveNote = "After the trial, Ainar leaves The Losers for good."+ mock.extractionCandidatesResult = .success([Self.groupChapterCandidate(+ workID: workID, chapterID: leaveChapterID, note: leaveNote,+ knownGroupNames: ["Team Loser", "The Losers"], characters: [ainar],+ characterSuppressions: .init(candidateKeys: ["team loser", "the losers"], factIdentities: []))])+ let normalizedAliasKey = RecordNameKey.normalize("The Losers")+ let normalizedAinarKey = RecordNameKey.normalize("Ainar")+ mock.effectiveGroupJoins.insert("\(leaveChapterID.uuidString)/\(normalizedAliasKey)/\(normalizedAinarKey)")+ mock.applicableGroupLeaves.insert("\(leaveChapterID.uuidString)/\(normalizedAliasKey)/\(normalizedAinarKey)")+ client.inner = StubCharacterExtractionModelClient(result: ExtractionResult(+ characters: [.init(name: "Team Loser"), .init(name: "The Losers"), .init(name: "Ainar")],+ groupLeaves: [.init(groupName: "The Losers", characterName: "Ainar",+ quote: "Ainar leaves The Losers")]), recorder: recorder)++ await coordinator.runManualPass(workID: workID)++ #expect(recorder.recordedSources.count == 2)+ #expect(recorder.recordedSources.last?.knownGroupNames == ["Team Loser", "The Losers"])+ #expect(coordinator.held(for: workID).isEmpty)+ #expect(mock.groupSuggestionLeaveChecks == ["losers/ainar"])+ let leave = try #require(coordinator.heldGroups(for: workID).first { $0.kind == .leave })+ #expect(leave.groupName == "The Losers")+ #expect(leave.characterName == "Ainar")+ #expect(leave.quote == "Ainar leaves The Losers")+ let leaveOutcome = try await coordinator.acceptGroup(leave.id, workID: workID)+ #expect(leaveOutcome == .committed(groupIDs: [mock.groupSummariesResult[0].groupID]))+ #expect(mock.groupEditCalls.last?.operations.contains {+ if case .approveSuggestion(let approval) = $0 { return approval.action == .leave }+ return false+ } == true)+ }+ /// Req 1.4: coverage is one record per revision over **both** arrays, so /// "produced none" means neither kind survived grounding — not that the /// characters array was empty.
diff --git a/Asterism/AsterismTests/CharacterGroupEditorTests.swift b/Asterism/AsterismTests/CharacterGroupEditorTests.swiftnew file mode 100644index 00000000..ead82997--- /dev/null+++ b/Asterism/AsterismTests/CharacterGroupEditorTests.swift@@ -0,0 +1,149 @@+import AsterismCore+import Foundation+import Testing+@testable import Asterism++@Suite @MainActor struct CharacterGroupEditorTests {+ @Test func cancelNeverStages() async {+ var staged: CharacterGroupDraft?+ let model = CharacterGroupEditorModel(workID: UUID()) { staged = $0 }+ model.name = "Team Jake"+ #expect(staged == nil)+ }++ @Test func doneStagesCreateForEnclosingWorkSave() async {+ var staged: CharacterGroupDraft?+ let model = CharacterGroupEditorModel(workID: UUID()) { staged = $0 }+ #expect(!model.canDelete)+ model.name = "Team Jake"+ model.aliases = "The Jakes\nJake's team"+ #expect(await model.save())+ #expect(staged?.operations.contains(.create(groupID: model.groupID, name: "Team Jake")) == true)+ #expect(staged?.operations.count == 3)+ }++ @Test func nestedEditorStartsFromStagedValueButCanCancelIndependently() async throws {+ let workID = UUID()+ var staged: CharacterGroupDraft?+ let first = CharacterGroupEditorModel(workID: workID) { staged = $0 }+ first.name = "Team Jake"+ #expect(await first.save())+ let saved = try #require(staged)++ var nestedStage: CharacterGroupDraft?+ let nested = CharacterGroupEditorModel(workID: workID, draft: saved) { nestedStage = $0 }+ nested.aliases = "Only in nested draft"+ #expect(nestedStage == nil)+ #expect(saved.operations.count == 1)+ }++ @Test func repeatedNestedSavesDeriveOperationsFromOriginalBasis() async throws {+ let workID = UUID()+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", aliases: ["The Team"],+ factEventIDs: [UUID()])+ var staged: CharacterGroupDraft?+ let first = CharacterGroupEditorModel(workID: workID, group: group) { staged = $0 }+ first.name = "Jake's Team"+ #expect(await first.save())+ let second = CharacterGroupEditorModel(workID: workID, group: group, draft: try #require(staged)) {+ staged = $0+ }+ second.aliases = "The Team\nNight Crew"+ #expect(await second.save())+ let operations = try #require(staged).operations+ #expect(operations.filter {+ if case .fact(_, _, .setName) = $0 { return true }+ return false+ }.count == 1)+ #expect(operations.contains(.fact(groupID: group.groupID,+ expectedEventIDs: group.factEventIDs, operation: .addAlias("Night Crew"))))+ #expect(!operations.contains(.fact(groupID: group.groupID,+ expectedEventIDs: group.factEventIDs, operation: .removeAlias("The Team"))))+ }++ @Test func deletingExistingGroupStagesTombstoneOnly() async {+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", factEventIDs: [UUID()])+ var staged: CharacterGroupDraft?+ let model = CharacterGroupEditorModel(workID: UUID(), group: group) { staged = $0 }+ #expect(staged == nil)+ #expect(await model.save(deleting: true))+ #expect(staged?.operations == [+ .fact(groupID: group.groupID, expectedEventIDs: group.factEventIDs, operation: .delete)+ ])+ }++ @Test func editsAliasesAndTransitionHistoryFromOneSnapshot() async throws {+ let groupID = UUID(), characterID = UUID(), chapterID = UUID(), workID = UUID()+ let transitionID = UUID(), rootID = UUID()+ let old = GroupTransitionFact(id: transitionID, rootID: rootID, workID: workID,+ groupID: groupID, characterID: characterID, chapterID: chapterID, action: .join)+ let group = GroupSummary(groupID: groupID, name: "Team Jake", aliases: ["The Team"],+ factEventIDs: [UUID()], transitions: [old], transitionEventIDs: [rootID: [transitionID]])+ var staged: CharacterGroupDraft?+ let model = CharacterGroupEditorModel(workID: workID, group: group) { staged = $0 }+ model.aliases = "Team Jake\nNew Alias"+ let newChapter = UUID()+ model.revise(old, chapterID: newChapter, action: .leave)+ let addedCharacter = UUID(), addedChapter = UUID()+ model.addMember(characterID: addedCharacter, chapterID: addedChapter, action: .join)+ let added = try #require(model.transitions.first { $0.characterID == addedCharacter })+ model.remove(added)++ #expect(await model.save())+ let operations = try #require(staged).operations+ #expect(operations.contains(.fact(groupID: groupID, expectedEventIDs: group.factEventIDs,+ operation: .removeAlias("The Team"))))+ #expect(operations.contains(.fact(groupID: groupID, expectedEventIDs: group.factEventIDs,+ operation: .addAlias("New Alias"))))+ #expect(operations.contains(.reviseTransition(rootID: rootID,+ expectedEventIDs: [transitionID], chapterID: newChapter, action: .leave)))+ #expect(!operations.contains { if case .transition(_, _, characterID, _, _) = $0 { return characterID == addedCharacter }; return false })+ }++ @Test("Conflicted membership needs an explicit chapter and action but does not block alias edits")+ func explicitConflictedTransitionResolution() async throws {+ let workID = UUID(), groupID = UUID(), characterID = UUID(), rootID = UUID()+ let firstChapter = UUID(), secondChapter = UUID()+ let first = GroupTransitionFact(rootID: rootID, workID: workID,+ groupID: groupID, characterID: characterID, chapterID: firstChapter,+ action: .join)+ let second = GroupTransitionFact(rootID: rootID, workID: workID,+ groupID: groupID, characterID: characterID, chapterID: secondChapter,+ action: .leave)+ let basis = [first.id, second.id]+ let conflict = GroupTransitionConflict(rootID: rootID, groupID: groupID,+ characterID: characterID, heads: [first, second], expectedEventIDs: basis)+ let group = GroupSummary(groupID: groupID, name: "Team Jake", factEventIDs: [UUID()],+ conflictedTransitions: [conflict], transitionEventIDs: [rootID: basis])+ var staged: CharacterGroupDraft?+ let editor = CharacterGroupEditorModel(workID: workID, group: group) { staged = $0 }+ #expect(editor.conflictChapter(rootID) == nil)+ #expect(editor.conflictAction(rootID) == nil)+ editor.aliases = "Night Crew"+ #expect(await editor.save())+ #expect(staged?.operations.contains { if case .reviseTransition = $0 { return true }; return false } == false)++ let nested = CharacterGroupEditorModel(workID: workID, group: group,+ draft: try #require(staged)) { staged = $0 }+ nested.chooseConflictChapter(rootID, chapterID: secondChapter)+ #expect(!(await nested.save()))+ #expect(nested.errorMessage != nil)+ nested.chooseConflictAction(rootID, action: .join)+ #expect(nested.errorMessage == nil)+ #expect(await nested.save())+ #expect(staged?.operations.contains(.reviseTransition(rootID: rootID,+ expectedEventIDs: basis, chapterID: secondChapter, action: .join)) == true)+ #expect(staged?.previewTransitions.contains { $0.rootID == rootID &&+ $0.chapterID == secondChapter && $0.action == .join } == true)++ let remove = CharacterGroupEditorModel(workID: workID, group: group) { staged = $0 }+ remove.toggleConflictRemoval(rootID)+ #expect(await remove.save())+ #expect(staged?.operations.contains {+ if case .reviseTransition(let id, let expected, _, .remove) = $0 {+ return id == rootID && expected == basis+ }+ return false+ } == true)+ }+}
diff --git a/Asterism/AsterismTests/CharacterGroupReviewPresentationTests.swift b/Asterism/AsterismTests/CharacterGroupReviewPresentationTests.swiftnew file mode 100644index 00000000..e7f8f8df--- /dev/null+++ b/Asterism/AsterismTests/CharacterGroupReviewPresentationTests.swift@@ -0,0 +1,17 @@+import AsterismIntelligence+import Testing+@testable import Asterism++@Suite struct CharacterGroupReviewPresentationTests {+ @Test("A leave review states the character remains through the named chapter")+ func leaveCaptionUsesInclusiveBoundary() {+ #expect(GroupReviewActionCaption.text(kind: .leave, characterName: "Ainar") ==+ "Ainar remains in the group through this chapter; removal starts afterward.")+ }++ @Test("Join review keeps its existing chapter wording")+ func joinCaptionKeepsExistingWording() {+ #expect(GroupReviewActionCaption.text(kind: .join, characterName: "Ainar") ==+ "Add Ainar from this chapter")+ }+}
diff --git a/Asterism/AsterismTests/CharacterReviewModelTests.swift b/Asterism/AsterismTests/CharacterReviewModelTests.swiftindex a18c12ad..6d4722de 100644--- a/Asterism/AsterismTests/CharacterReviewModelTests.swift+++ b/Asterism/AsterismTests/CharacterReviewModelTests.swift@@ -103,6 +103,99 @@ struct CharacterReviewModelTests { return (model, mock) } + private nonisolated static func groupSuggestion(workID: UUID, chapterID: UUID) -> GroundedGroupSuggestion {+ let source = ExtractionSource(workID: workID, workTitle: "Story", source: .entry(chapterID),+ text: "Missha joins Team Loser.", fingerprint: "saved", isChapter: true)+ return GroupExtractionGrounding.ground(ExtractionResult(groupJoins: [+ .init(groupName: "Team Loser", characterName: "Missha", quote: "Missha joins Team Loser")+ ]), from: source)[0]+ }++ @Test("A group-only review accepts its proposal and retains a failed decision")+ func groupOnlyDecision() async {+ let work = UUID(), chapter = UUID()+ let proposal = Self.groupSuggestion(workID: work, chapterID: chapter)+ let library = MockLibraryProvider()+ var shouldCommit = false+ var decisions: [String] = []+ let model = CharacterReviewModel(workID: work, proposals: [], groupProposals: [proposal],+ characters: [], library: library, extractionContext: { nil },+ onDecision: { _, _ in }, onReRoute: { _, _ in }, onReclassify: { _, _, _ in },+ refresh: { [] }, onGroupDecision: { id, _ in+ decisions.append(id)+ return shouldCommit ? .committed(groupIDs: [UUID()]) : .refused(.stale)+ }, currentHeldGroups: { [proposal] })+ #expect(!model.isEmpty)+ await model.acceptGroup(proposal.id)+ #expect(model.groupRows.count == 1)+ #expect(model.disclosure != nil)+ shouldCommit = true+ await model.acceptGroup(proposal.id)+ #expect(model.isEmpty)+ #expect(decisions == [proposal.id, proposal.id])+ }++ @Test("Skipping a join leaves a separate group creation suggestion visible")+ func skippingJoinKeepsCreate() async {+ let work = UUID(), chapter = UUID()+ let join = Self.groupSuggestion(workID: work, chapterID: chapter)+ let source = ExtractionSource(workID: work, workTitle: "Story", source: .entry(chapter),+ text: "Missha joins Team Loser.", fingerprint: "saved", isChapter: true)+ let create = GroupExtractionGrounding.ground(ExtractionResult(groups: [+ .init(name: "Team Loser")]), from: source)[0]+ let library = MockLibraryProvider()+ let model = CharacterReviewModel(workID: work, proposals: [],+ groupProposals: [create, join], characters: [], library: library,+ extractionContext: { nil }, onDecision: { _, _ in }, onReRoute: { _, _ in },+ onReclassify: { _, _, _ in }, refresh: { [] },+ onGroupDecision: { _, _ in .committed(groupIDs: []) })+ await model.skipGroup(join.id)+ #expect(model.groupRows.map(\.id) == [create.id])+ }++ @Test("A stale group approval reconciles before presenting held group rows again")+ func staleGroupApprovalReconciles() async {+ let work = UUID(), chapter = UUID()+ let proposal = Self.groupSuggestion(workID: work, chapterID: chapter)+ let library = MockLibraryProvider()+ var held = [proposal]+ var refreshed = false+ let model = CharacterReviewModel(workID: work, proposals: [],+ groupProposals: [proposal], characters: [], library: library,+ extractionContext: { nil }, onDecision: { _, _ in }, onReRoute: { _, _ in },+ onReclassify: { _, _, _ in }, refresh: {+ refreshed = true+ held.removeAll()+ return []+ }, onGroupDecision: { _, _ in .refused(.stale) },+ currentHeldGroups: { held })+ await model.acceptGroup(proposal.id)+ #expect(refreshed)+ #expect(model.groupRows.isEmpty)+ }++ @Test("A held group in the same chapter withholds character decision coverage")+ func groupHoldWithholdsCharacterCoverage() async {+ let work = UUID(), chapter = UUID(), target = UUID()+ var character = Self.candidate(facts: [], target: .existing(target),+ revisions: [.entry(chapter): "saved"])+ character.mentions = [.init(entryID: chapter, noteFingerprint: "saved", spellingKeys: ["ada"])]+ character.citedMentionEligibility = [.entry(chapter): "eligibility"]+ let group = Self.groupSuggestion(workID: work, chapterID: chapter)+ let library = MockLibraryProvider()+ let model = CharacterReviewModel(workID: work, proposals: [character],+ groupProposals: [group], characters: [Self.character(id: target)], library: library,+ extractionContext: { nil }, onDecision: { _, _ in }, onReRoute: { _, _ in },+ onReclassify: { _, _, _ in }, refresh: { [] },+ hasUndecidedGroupSource: { source, fingerprint in+ source == .entry(chapter) && fingerprint == "saved"+ })+ guard let row = model.rows.first else { Issue.record("Expected character row"); return }+ await model.accept(row.id)+ #expect(library.committedDecisions.first?.completedSources.isEmpty == true)+ #expect(!model.isEmpty)+ }+ // MARK: - Fixtures for the refusal cases that cross the real seam @Test("An inline note draft is sent with Keep and guards the target note")
diff --git a/Asterism/AsterismTests/EntryDetailModelTests.swift b/Asterism/AsterismTests/EntryDetailModelTests.swiftindex bbf7863b..30f4a8d9 100644--- a/Asterism/AsterismTests/EntryDetailModelTests.swift+++ b/Asterism/AsterismTests/EntryDetailModelTests.swift@@ -131,6 +131,34 @@ struct EntryDetailModelTests { #expect(mock.entryTeachingDetailCallCount == 1) } + @Test("Ordinary chapter link correction preserves chapter drafts and refreshes associations")+ @MainActor func ordinaryChapterLinkCorrection() async {+ let entry = TestFixtures.makeEntry(note: "Draft stays put", rating: .up)+ let pair = AssociationPair(workID: UUID(), entryID: entry.id,+ kind: .character, recordID: UUID())+ let root = UUID()+ let association = ChapterAssociationSnapshot(pair: pair, recordName: "Alice", chapterTitle: "Chapter 1",+ evidence: [.init(key: "alice", spelling: "Alice")], activeAcceptanceIDs: [root],+ validationReceipt: nil, removalCorrectionIDs: [UUID()])+ let detail = EntryTeachingDetail(entry: entry, siteMode: .untaught, activePatternSummary: nil,+ historicalPatternSummaries: [], chapterSettlement: .unsettled(reason: "test"),+ assignmentSettlement: .unsettled(reason: "test"), availableActions: [],+ unresolvedCandidateTitle: nil, chapterAssociations: [association])+ let (model, mock, _) = makeSUT(entry: entry, detail: detail)+ mock.chapterAssociationsResult = .success([association])+ await model.load()+ #expect(model.chapterAssociations.first?.isRemoved == false)+ #expect(model.associationNoteEditor(for: pair) != nil,+ "A new active support remains on the normal note-editor route even while an older correction exists")+ model.draftNote = "unsaved chapter draft"+ await model.correctChapterAssociation(association)+ #expect(mock.chapterAssociationCorrections.count == 1)+ #expect(mock.chapterAssociationCorrections.first?.0 == pair)+ #expect(mock.chapterAssociationCorrections.first?.1 == false)+ #expect(model.draftNote == "unsaved chapter draft")+ #expect(model.chapterAssociations.first?.pair == pair)+ }+ /// `app-intents` Req 4.5: the entry screen has no edit mode, so an open /// intent asks this whether navigating away would lose an edit. @Test("hasUnsavedChanges follows the draft against the loaded snapshot")
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex 956ff320..ce157e2a 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -517,6 +517,44 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { /// these at once. var extractionCandidatesResult: Result<[ExtractionCandidate], Error> = .success([])+ var groupSuggestionSkipsResult: Set<GroupSuggestionSkip> = []+ var groupSummariesResult: [GroupSummary] = []+ var effectiveGroupJoins: Set<String> = []+ var applicableGroupLeaves: Set<String> = []+ var groupSuggestionLeaveChecks: [String] = []+ var groupEditResult: GroupEditOutcome = .committed(groupIDs: [])+ var groupEditCalls: [(workID: UUID, operations: [GroupEditOperation], chapterID: UUID?)] = []+ var workDetailEditResult: WorkDetailEditOutcome = .committed(+ receipt: MembershipWriteReceipt(outcome: .committed), recordIDs: [], groupIDs: [])+ var workDetailEditCalls: [WorkDetailEditTransaction] = []+ func commitWorkDetailEdit(_ request: WorkDetailEditTransaction) async throws -> WorkDetailEditOutcome {+ callLog.append("commitWorkDetailEdit")+ workDetailEditCalls.append(request)+ return workDetailEditResult+ }+ func groupSuggestionSkips(workID: UUID) async throws -> Set<GroupSuggestionSkip> {+ groupSuggestionSkipsResult+ }+ func characterGroups(workID: UUID) async throws -> [GroupSummary] { groupSummariesResult }+ func groupSuggestionMembershipIsEffective(workID: UUID, chapterID: UUID,+ groupName: String, characterName: String) async throws -> Bool {+ effectiveGroupJoins.contains("\(chapterID.uuidString)/\(RecordNameKey.normalize(groupName))/\(RecordNameKey.normalize(characterName))")+ }+ func groupSuggestionLeaveIsApplicable(workID: UUID, chapterID: UUID,+ groupName: String, characterName: String) async throws -> Bool {+ groupSuggestionLeaveChecks.append("\(RecordNameKey.normalize(groupName))/\(RecordNameKey.normalize(characterName))")+ return applicableGroupLeaves.contains("\(chapterID.uuidString)/\(RecordNameKey.normalize(groupName))/\(RecordNameKey.normalize(characterName))")+ }+ func commitGroupEdits(workID: UUID, operations: [GroupEditOperation],+ currentChapterID: UUID?) async throws -> GroupEditOutcome {+ groupEditCalls.append((workID, operations, currentChapterID))+ return groupEditResult+ }+ func skipGroupSuggestion(_ skip: GroupSuggestionSkip,+ sourceFingerprint: String) async throws -> GroupEditOutcome {+ groupSuggestionSkipsResult.insert(skip)+ return groupEditResult+ } var pendingMentionReviewHandler: (@Sendable ([AssociationPendingReviewRequest]) async throws -> [AssociationPendingReviewResult])? var advanceCoverageResult: Result<Int, Error> = .success(1) /// Awaited inside `commitDecision` before it returns, so a test@@ -730,6 +768,9 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { struct AssociationNoteRecovery: Equatable, Sendable { var basis: AssociationNoteBasis; var heads: [AssociationNoteValue]; var text: String } var chapterAssociationsResult: Result<[ChapterAssociationSnapshot], Error> = .success([]) var chapterAssociationsHold: SubmissionGate?+ var chapterAssociationCorrectionResult: Result<Bool, Error> = .success(true)+ private var storedChapterAssociationCorrections: [(AssociationPair, Bool)] = []+ var chapterAssociationCorrections: [(AssociationPair, Bool)] { recorderLock.withLock { storedChapterAssociationCorrections } } var associationNoteBasisResult: Result<AssociationNoteBasis?, Error> = .success(nil) var associationNoteBasisHold: SubmissionGate? var associationNoteWriteResult: Result<AssociationNoteWriteOutcome, Error> = .failure(MockError.notConfigured)@@ -752,6 +793,14 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { } await hold?.wait(); return try result.get() }+ func removeChapterAssociation(pair: AssociationPair) async throws -> Bool {+ recorderLock.withLock { storedChapterAssociationCorrections.append((pair, false)) }+ return try chapterAssociationCorrectionResult.get()+ }+ func restoreChapterAssociation(pair: AssociationPair) async throws -> Bool {+ recorderLock.withLock { storedChapterAssociationCorrections.append((pair, true)) }+ return try chapterAssociationCorrectionResult.get()+ } func associationNoteBasis(pair: AssociationPair) async throws -> AssociationNoteBasis? { let (result, hold) = recorderLock.withLock { storedAssociationNoteBasisReadCount += 1
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex 03590d92..e042b984 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 = BackupV20Exporter(repository: repository, stagingDirectory: stagingDirectory)+ let exporter = BackupV21Exporter(repository: repository, stagingDirectory: stagingDirectory) let exportedAt = Date(timeIntervalSince1970: 1_784_246_400) let result = try await exporter.export(- metadata: BackupV20Metadata(+ metadata: BackupV21Metadata( appBuild: "integration-1", exportedAt: exportedAt )@@ -166,8 +166,8 @@ struct IntegrationSafetyNetTests { defer { exporter.cleanup(result) } let encoded = try Data(contentsOf: result.fileURL)- let decoded = try BackupV20Codec.decode(encoded)- let source = try await repository.backupV20Snapshot()+ let decoded = try BackupV21Codec.decode(encoded)+ let source = try await repository.backupV21Snapshot() #expect(decoded.payload == source) #expect(decoded.payload.library.entries.count == 1)@@ -241,13 +241,13 @@ struct IntegrationSafetyNetTests { Issue.record("Expected Backup export for \(environment) \(capabilities.gate.rawValue)") continue }- // Settings writes 20/21 now: the archive has to carry+ // Settings writes 21/22 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 BackupV20Codec.decode(Data(contentsOf: backupURL))+ let document = try BackupV21Codec.decode(Data(contentsOf: backupURL)) #expect(document.capabilityGate == AsterismCapabilities.current.gate.rawValue) backup.shareDismissed() backup.handleShareOutcome(.cancelled)@@ -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 = BackupV20Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+ let exporter = BackupV21Exporter(repository: sourceRepo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV20Metadata(appBuild: "fill-test", exportedAt: Date())+ metadata: BackupV21Metadata(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.swiftindex 5cfddbb2..d1e8d0e4 100644--- a/Asterism/AsterismTests/NoteFirstCharacterRoutingTests.swift+++ b/Asterism/AsterismTests/NoteFirstCharacterRoutingTests.swift@@ -63,6 +63,25 @@ struct NoteFirstCharacterRoutingTests { return try ModelContext(container).fetchCount(FetchDescriptor<AssociationEvent>()) } }+ @Test("Modelled existing Jake cannot bypass saved group arbitration",+ arguments: [("Team Jake returns.", "Team Jake", false),+ ("Jake returns.", "Jake", false),+ ("Team Jake meets Jake.", "Team Jake", true)])+ func modelledGroupCollision(note: String, groupName: String,+ shouldLink: Bool) async throws {+ let fixture = try await Fixture(records: [.init(kind: .character, name: "Jake")],+ note: note)+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let groupID = UUID()+ guard case .committed = try await fixture.repository.commitGroupEdits(+ workID: fixture.workID, operations: [.create(groupID: groupID,+ name: groupName)]) else { throw FixtureError.refused }+ let owner = coordinator(fixture, result: .init(characters: [.init(name: "Jake")]))+ await owner.runManualPass(workID: fixture.workID)+ let links = try await fixture.repository.chapterAssociations(entryID: fixture.entryID)+ #expect(links.contains { !$0.activeAcceptanceIDs.isEmpty } == shouldLink)+ await fixture.repository.shutdown()+ } /// 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.
diff --git a/Asterism/AsterismTests/WorkDetailCharacterTests.swift b/Asterism/AsterismTests/WorkDetailCharacterTests.swiftindex 4626411c..7759b969 100644--- a/Asterism/AsterismTests/WorkDetailCharacterTests.swift+++ b/Asterism/AsterismTests/WorkDetailCharacterTests.swift@@ -205,13 +205,14 @@ struct WorkDetailCharacterTests { await model.load() model.beginEditing() - model.addCharacter(named: "Brede")+ let id = model.addCharacter(named: "Brede") await model.commitEditing() - guard case .create(let draft)? = mock.committedRecordEdits.first?.operations.first else {+ guard case .createIdentified(let createdID, let draft)? = mock.committedRecordEdits.first?.operations.first else { Issue.record("Expected a create operation") return }+ #expect(createdID == id) #expect(draft.name == "Brede") } @@ -529,10 +530,11 @@ struct WorkDetailRecordSessionTests { await model.commitEditing() - guard case .create(let draft)? = mock.committedRecordEdits.first?.operations.first else {+ guard case .createIdentified(let createdID, let draft)? = mock.committedRecordEdits.first?.operations.first else { Issue.record("Expected a create operation") return }+ #expect(createdID == id) #expect(draft.kind == .place) #expect(draft.name == "Kestrel Head") }@@ -681,10 +683,11 @@ struct WorkDetailRecordSessionTests { let operations = mock.committedRecordEdits.first?.operations ?? [] #expect(operations.count == 1)- guard case .create(let draft) = operations.first else {+ guard case .createIdentified(let createdID, let draft) = operations.first else { Issue.record("Expected a create operation") return }+ #expect(createdID == id) #expect(draft.kind == .place) #expect(draft.name == "Kestrel Head") }
diff --git a/Asterism/AsterismTests/WorkDetailModelTests.swift b/Asterism/AsterismTests/WorkDetailModelTests.swiftindex bda183a0..6fa2c5eb 100644--- a/Asterism/AsterismTests/WorkDetailModelTests.swift+++ b/Asterism/AsterismTests/WorkDetailModelTests.swift@@ -20,6 +20,349 @@ nonisolated func standInTypeID(_ name: String) -> UUID { @Suite("WorkDetailModel") struct WorkDetailModelTests {+ @Test("Group delete remains a draft when the enclosing Work edit is cancelled")+ @MainActor func groupDeleteCancel() async {+ let (model, mock, _) = makeSUT()+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", factEventIDs: [UUID()])+ await model.load(); model.beginEditing()+ let editor = model.groupEditor(group)+ #expect(await editor.save(deleting: true))+ #expect(mock.groupEditCalls.isEmpty)+ model.cancelEditing()+ #expect(mock.groupEditCalls.isEmpty)+ }++ @Test("Group delete is written only by the enclosing Work Save")+ @MainActor func groupDeleteSave() async {+ let (model, mock, _) = makeSUT()+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", factEventIDs: [UUID()])+ await model.load(); model.beginEditing()+ let editor = model.groupEditor(group)+ #expect(await editor.save(deleting: true))+ #expect(mock.workDetailEditCalls.isEmpty)+ await model.commitEditing()+ #expect(mock.workDetailEditCalls.count == 1)+ #expect(mock.workDetailEditCalls[0].groupOperations == [+ .fact(groupID: group.groupID, expectedEventIDs: group.factEventIDs, operation: .delete)+ ])+ }++ @Test("Cancelling a nested group edit preserves the earlier Work-session draft")+ @MainActor func nestedGroupEditCancel() async throws {+ let (model, mock, _) = makeSUT()+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", aliases: ["The Team"],+ factEventIDs: [UUID()])+ await model.load(); model.beginEditing()+ let first = model.groupEditor(group)+ first.name = "Jake's Team"+ #expect(await first.save())+ let nested = model.groupEditor(group)+ nested.aliases = "Nested-only alias"+ // Dismissing the nested sheet is its Cancel: no draft callback runs.+ #expect(mock.workDetailEditCalls.isEmpty)+ await model.commitEditing()+ let operations = try #require(mock.workDetailEditCalls.first?.groupOperations)+ #expect(operations.contains(.fact(groupID: group.groupID,+ expectedEventIDs: group.factEventIDs, operation: .setName("Jake's Team"))))+ #expect(!operations.contains(.fact(groupID: group.groupID,+ expectedEventIDs: group.factEventIDs, operation: .addAlias("Nested-only alias"))))+ }++ @Test("Group, metadata, and record drafts are accepted in one Work transaction")+ @MainActor func groupMetadataAndRecordSaveTogether() async throws {+ let (model, mock, _) = makeSUT()+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", factEventIDs: [UUID()])+ await model.load(); model.beginEditing()+ model.draftTitle = "Unsaved title"+ _ = model.addCharacter(named: "New character")+ let editor = model.groupEditor(group)+ editor.name = "New team name"+ #expect(await editor.save())+ await model.commitEditing()+ #expect(mock.workDetailEditCalls.count == 1)+ let transaction = try #require(mock.workDetailEditCalls.first)+ #expect(transaction.metadata?.draft.displayTitle == "Unsaved title")+ #expect(!transaction.recordOperations.isEmpty)+ #expect(transaction.groupOperations.contains(.fact(groupID: group.groupID,+ expectedEventIDs: group.factEventIDs, operation: .setName("New team name"))))+ #expect(mock.updateWorkCallCount == 0)+ #expect(mock.committedRecordEdits.isEmpty)+ #expect(!model.isEditing)+ }++ @Test("A staged character keeps its identity when joined in the same Work Save")+ @MainActor func stagedCharacterCanJoinGroupInSameSave() async throws {+ let chapterID = UUID()+ let work = TestFixtures.makeWork()+ let detail = TestFixtures.makeWorkDetail(work: work, chapterRows: [+ WorkChapterRow(id: chapterID, displayTitle: "Chapter 1", note: "", rating: nil,+ lastSharedAt: Date())+ ])+ let (model, mock, _) = makeSUT(work: work, detail: detail)+ await model.load(); model.beginEditing()+ let characterID = model.addCharacter(named: "New character")+ #expect(model.groupCharacterOptions.contains { $0.id == characterID && $0.name == "New character" })++ let editor = model.groupEditor()+ editor.name = "New team"+ editor.addMember(characterID: characterID, chapterID: chapterID, action: .join)+ #expect(await editor.save())+ await model.commitEditing()++ let transaction = try #require(mock.workDetailEditCalls.first)+ #expect(transaction.recordOperations.contains(.createIdentified(id: characterID,+ draft: RecordDraft(kind: .character, name: "New character"))))+ #expect(transaction.groupOperations.contains { operation in+ guard case .transition(_, _, let actualCharacterID, let actualChapterID, .join) = operation+ else { return false }+ guard actualChapterID == chapterID else { return false }+ return actualCharacterID == characterID+ })+ }++ @Test("Reopening a newly created group keeps its nil persisted baseline")+ @MainActor func reopeningCreatedGroupPreservesCreateOperation() async throws {+ let (model, mock, _) = makeSUT()+ await model.load(); model.beginEditing()+ let initial = model.groupEditor()+ initial.name = "The Night Crew"+ #expect(await initial.save())++ let staged = try #require(model.characterGroups.first)+ let reopened = model.groupEditor(staged)+ reopened.name = "Night Crew"+ #expect(await reopened.save())+ #expect(mock.groupEditCalls.isEmpty)+ await model.commitEditing()++ let transaction = try #require(mock.workDetailEditCalls.first)+ #expect(transaction.groupOperations.contains(.create(groupID: staged.groupID, name: "Night Crew")))+ #expect(!transaction.groupOperations.contains { operation in+ if case .fact(let groupID, _, .setName) = operation { return groupID == staged.groupID }+ return false+ })+ }++ @Test("Reopening an unsaved new group then cancelling both scopes discards it")+ @MainActor func cancelReopenedCreatedGroupDraft() async {+ let (model, mock, _) = makeSUT()+ await model.load(); model.beginEditing()+ let initial = model.groupEditor()+ initial.name = "The Night Crew"+ #expect(await initial.save())+ let staged = model.characterGroups.first+ let reopened = model.groupEditor(staged)+ reopened.name = "Cancelled rename"+ model.cancelEditing()+ #expect(mock.workDetailEditCalls.isEmpty)+ #expect(mock.groupEditCalls.isEmpty)+ }++ @Test("Staged transition corrections update roster preview and parent Cancel restores it")+ @MainActor func stagedTransitionProjectionTracksRevisionAndRemoval() async throws {+ let work = TestFixtures.makeWork()+ let chapterOne = WorkChapterRow(id: UUID(), displayTitle: "Chapter 1", note: "",+ rating: nil, lastSharedAt: Date())+ let chapterTwo = WorkChapterRow(id: UUID(), displayTitle: "Chapter 2", note: "",+ rating: nil, lastSharedAt: Date())+ let characterID = UUID(), groupID = UUID(), joinRoot = UUID(), leaveRoot = UUID()+ let join = GroupTransitionFact(id: joinRoot, rootID: joinRoot, workID: work.id, groupID: groupID,+ characterID: characterID, chapterID: chapterOne.id, action: .join)+ let leave = GroupTransitionFact(id: leaveRoot, rootID: leaveRoot, workID: work.id, groupID: groupID,+ characterID: characterID, chapterID: chapterTwo.id, action: .leave)+ let groups = [GroupSummary(groupID: groupID, name: "Team",+ members: [characterID: [MembershipRange(+ start: GroupChapter(id: chapterOne.id, label: chapterOne.displayTitle),+ end: GroupChapter(id: chapterTwo.id, label: chapterTwo.displayTitle))]],+ factEventIDs: [UUID()], transitions: [join, leave],+ transitionEventIDs: [joinRoot: [joinRoot], leaveRoot: [leaveRoot]])]+ let detail = TestFixtures.makeWorkDetail(work: work, chapterRows: [chapterOne, chapterTwo],+ characterGroups: groups)+ let (model, mock, _) = makeSUT(work: work, detail: detail)+ await model.load(); model.beginEditing()++ let first = model.groupEditor(groups[0])+ first.revise(leave, chapterID: chapterOne.id, action: .leave)+ #expect(await first.save())+ let revised = try #require(model.characterGroups.first?.members[characterID]?.first)+ #expect(revised.endLabel == "Chapter 1")++ let currentGroup = try #require(model.characterGroups.first)+ let second = model.groupEditor(currentGroup)+ let revisedLeave = try #require(second.transitions.first { $0.rootID == leaveRoot })+ second.remove(revisedLeave)+ #expect(await second.save())+ let open = try #require(model.characterGroups.first?.members[characterID]?.first)+ #expect(open.endChapterID == nil)++ model.cancelEditing()+ let restored = try #require(model.characterGroups.first?.members[characterID]?.first)+ #expect(restored.endLabel == "Chapter 2")+ }++ @Test("Revising an unsaved Join keeps its root for new and existing groups")+ @MainActor func reviseNewTransitionPreservesRootForBothGroupKinds() async throws {+ let work = TestFixtures.makeWork()+ let chapterOne = WorkChapterRow(id: UUID(), displayTitle: "Chapter 1", note: "",+ rating: nil, lastSharedAt: Date())+ let chapterTwo = WorkChapterRow(id: UUID(), displayTitle: "Chapter 2", note: "",+ rating: nil, lastSharedAt: Date())+ let detail = TestFixtures.makeWorkDetail(work: work, chapterRows: [chapterOne, chapterTwo])+ let existing = GroupSummary(groupID: UUID(), name: "Existing team", factEventIDs: [UUID()])+ let (model, mock, _) = makeSUT(work: work, detail: detail)+ mock.groupSummariesResult = [existing]+ await model.load(); model.beginEditing()+ let characterID = UUID()++ let newEditor = model.groupEditor()+ newEditor.name = "New team"+ newEditor.addMember(characterID: characterID, chapterID: chapterOne.id, action: .join)+ let newRoot = try #require(newEditor.transitions.first?.rootID)+ newEditor.revise(try #require(newEditor.transitions.first), chapterID: chapterTwo.id, action: .join)+ #expect(newEditor.transitions.first?.id == newRoot)+ #expect(await newEditor.save())++ let existingEditor = model.groupEditor(existing)+ existingEditor.addMember(characterID: characterID, chapterID: chapterOne.id, action: .join)+ let existingRoot = try #require(existingEditor.transitions.first?.rootID)+ existingEditor.revise(try #require(existingEditor.transitions.first),+ chapterID: chapterTwo.id, action: .join)+ #expect(existingEditor.transitions.first?.id == existingRoot)+ #expect(await existingEditor.save())++ #expect(model.characterGroups.first { $0.name == "New team" }?+ .members[characterID]?.first?.startChapterID == chapterTwo.id)+ #expect(model.characterGroups.first { $0.groupID == existing.groupID }?+ .members[characterID]?.first?.startChapterID == chapterTwo.id)+ #expect(mock.workDetailEditCalls.isEmpty)+ }++ @Test("Editing one group preserves an unrelated roster with a persisted revised head")+ @MainActor func editingGroupPreservesUnrelatedResolvedMembership() async throws {+ let work = TestFixtures.makeWork()+ let chapterOne = WorkChapterRow(id: UUID(), displayTitle: "Chapter 1", note: "",+ rating: nil, lastSharedAt: Date())+ let chapterTwo = WorkChapterRow(id: UUID(), displayTitle: "Chapter 2", note: "",+ rating: nil, lastSharedAt: Date())+ let memberID = UUID(), editedID = UUID(), unaffectedID = UUID()+ let joinRoot = UUID(), joinHead = UUID(), leaveRoot = UUID()+ let persistedJoinHead = GroupTransitionFact(id: joinHead, rootID: joinRoot,+ workID: work.id, groupID: unaffectedID, characterID: memberID,+ chapterID: chapterOne.id, parentHeadIDs: [joinRoot], action: .join)+ let leave = GroupTransitionFact(id: leaveRoot, rootID: leaveRoot,+ workID: work.id, groupID: unaffectedID, characterID: memberID,+ chapterID: chapterTwo.id, action: .leave)+ let edited = GroupSummary(groupID: editedID, name: "Edited", factEventIDs: [UUID()])+ let unaffected = GroupSummary(groupID: unaffectedID, name: "Unaffected",+ members: [memberID: [MembershipRange(+ start: GroupChapter(id: chapterOne.id, label: "Chapter 1"),+ end: GroupChapter(id: chapterTwo.id, label: "Chapter 2"))]],+ factEventIDs: [UUID()], transitions: [persistedJoinHead, leave],+ transitionEventIDs: [joinRoot: [joinRoot, joinHead], leaveRoot: [leaveRoot]])+ let detail = TestFixtures.makeWorkDetail(work: work, chapterRows: [chapterOne, chapterTwo],+ characterGroups: [edited, unaffected])+ let (model, _, _) = makeSUT(work: work, detail: detail)+ await model.load(); model.beginEditing()+ let editor = model.groupEditor(edited)+ editor.name = "Edited name"+ #expect(await editor.save())++ let range = try #require(model.characterGroups.first { $0.groupID == unaffectedID }?+ .members[memberID]?.first)+ #expect(range.startLabel == "Chapter 1")+ #expect(range.endLabel == "Chapter 2")+ }++ @Test("Unresolved group roots survive unrelated Work drafts until explicitly chosen")+ @MainActor func unresolvedGroupRootSurvivesUnrelatedWorkDraft() async throws {+ let work = TestFixtures.makeWork()+ let chapter = WorkChapterRow(id: UUID(), displayTitle: "Chapter 1", note: "",+ rating: nil, lastSharedAt: Date())+ let groupID = UUID(), rootID = UUID(), characterID = UUID(), joinRoot = UUID()+ let heads = [GroupTransitionFact(rootID: rootID, workID: work.id,+ groupID: groupID, characterID: characterID, chapterID: chapter.id,+ action: .join), GroupTransitionFact(rootID: rootID, workID: work.id,+ groupID: groupID, characterID: characterID, chapterID: chapter.id,+ action: .leave)]+ let basis = heads.map(\.id)+ let independentJoin = GroupTransitionFact(id: joinRoot, rootID: joinRoot,+ workID: work.id, groupID: groupID, characterID: characterID,+ chapterID: chapter.id, action: .join)+ let group = GroupSummary(groupID: groupID, name: "Team", factEventIDs: [UUID()],+ transitions: [independentJoin],+ conflictedTransitions: [.init(rootID: rootID, groupID: groupID,+ characterID: characterID, heads: heads, expectedEventIDs: basis)],+ transitionEventIDs: [rootID: basis, joinRoot: [joinRoot]])+ let detail = TestFixtures.makeWorkDetail(work: work, chapterRows: [chapter],+ characterGroups: [group])+ let (model, mock, _) = makeSUT(work: work, detail: detail)+ await model.load(); model.beginEditing()+ model.draftTitle = "A title change"+ let editor = model.groupEditor(group)+ editor.aliases = "Night Crew"+ #expect(await editor.save())+ #expect(model.characterGroups.first?.conflictedTransitions.map(\.rootID) == [rootID])+ #expect(model.characterGroups.first?.members[characterID] == nil,+ "A separate accepted join must not publish a member whose other root remains disputed")+ await model.commitEditing()+ #expect(mock.workDetailEditCalls.first?.groupOperations.contains {+ if case .reviseTransition = $0 { return true }+ return false+ } == false)+ #expect(mock.workDetailEditCalls.first?.metadata?.draft.displayTitle == "A title change")++ model.beginEditing()+ let reopened = model.groupEditor(try #require(model.characterGroups.first))+ reopened.chooseConflictChapter(rootID, chapterID: chapter.id)+ reopened.chooseConflictAction(rootID, action: .join)+ #expect(await reopened.save())+ #expect(model.characterGroups.first?.conflictedTransitions.isEmpty == true)+ #expect(model.characterGroups.first?.transitions.contains { $0.rootID == rootID } == true)+ model.cancelEditing()+ }++ @Test("A link refusal rolls back the grouped Work edit transaction")+ @MainActor func linkRefusalLeavesGroupDraftUncommitted() async throws {+ let (model, mock, _) = makeSUT()+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", factEventIDs: [UUID()])+ mock.workDetailEditResult = .linkRefused(.alreadyLinked(type: "sequel"))+ await model.load(); model.beginEditing()+ model.addLink(to: UUID(), type: "sequel")+ let editor = model.groupEditor(group)+ editor.name = "New team name"+ #expect(await editor.save())+ await model.commitEditing()+ #expect(mock.groupEditCalls.isEmpty)+ #expect(mock.workDetailEditCalls.count == 1)+ #expect(mock.workDetailEditCalls[0].linkOperations.count == 1)+ #expect(mock.workDetailEditCalls[0].groupOperations.contains(.fact(groupID: group.groupID,+ expectedEventIDs: group.factEventIDs, operation: .setName("New team name"))))+ #expect(!mock.callLog.contains("commitLinkEdits"))+ #expect(model.isEditing)+ #expect(model.errorMessage != nil)+ }++ @Test("A group refusal preserves the staged metadata and record edits")+ @MainActor func groupRefusalKeepsAllDrafts() async {+ let (model, mock, _) = makeSUT()+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", factEventIDs: [UUID()])+ mock.workDetailEditResult = .groupRefused(.stale)+ await model.load(); model.beginEditing()+ model.draftTitle = "Unsaved title"+ _ = model.addCharacter(named: "New character")+ let editor = model.groupEditor(group)+ editor.name = "New team name"+ #expect(await editor.save())+ await model.commitEditing()+ #expect(mock.workDetailEditCalls.count == 1)+ #expect(mock.workDetailEditCalls[0].metadata?.draft.displayTitle == "Unsaved title")+ #expect(!mock.workDetailEditCalls[0].recordOperations.isEmpty)+ #expect(mock.updateWorkCallCount == 0)+ #expect(mock.committedRecordEdits.isEmpty)+ #expect(model.isEditing)+ #expect(model.draftTitle == "Unsaved title")+ }+ @Test("The chapter default override is staged, cancelled, and sent only on metadata Save") @MainActor func chapterDefaultSaveAndCancel() async { let (model, mock, _) = makeSUT()
diff --git a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swiftindex 12e7303e..f79fa565 100644--- a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift+++ b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift@@ -365,10 +365,38 @@ final class AccessibilityJourneyUITests: XCTestCase { // its "New series" button and the position field between the type picker // and them — so at this size the capsule the walk now has to come back // to is well above the fold rather than still on screen.+ let finishedReadingSegment = app.buttons["work-detail-reading-status-finished"] scrollUntilTappableAndTap(- app.buttons["work-detail-reading-status-finished"], in: app,+ finishedReadingSegment, in: app, "The reading-status capsule is operable at largest Dynamic Type",- scroll: { $0.swipeDown() })+ scroll: { $0.swipeDown() },+ readyToTap: { segment in+ segment.frame.midY > self.app.navigationBars.firstMatch.frame.maxY+ && segment.frame.midY < self.app.tabBars.firstMatch.frame.minY+ },+ beforeTap: { segment in+ let navigationBottom = self.app.navigationBars.firstMatch.frame.maxY+ let tabBarTop = self.app.tabBars.firstMatch.frame.minY+ let segmentFrame = segment.frame+ XCTContext.runActivity(+ named: "Finished reading segment hit frame at largest Dynamic Type"+ ) { activity in+ let geometry = XCTAttachment(+ string: "segment=\(segmentFrame); "+ + "navigationBottom=\(navigationBottom); tabBarTop=\(tabBarTop)")+ geometry.name = "Finished reading segment frame"+ activity.add(geometry)+ }+ // A virtual segment can report itself hittable while its+ // accessibility frame is stale. Keep the touch inside the+ // visible editor viewport before sending the tap.+ XCTAssertGreaterThan(+ segmentFrame.midY, navigationBottom,+ "Req 10.2: Finished clears navigation bar (\(segmentFrame))")+ XCTAssertLessThan(+ segmentFrame.midY, tabBarTop,+ "Req 10.2: Finished clears tab bar (\(segmentFrame))")+ }) for identifier in [ "work-detail-finished-mark-work", "work-detail-finished-abandon", ] {
diff --git a/Asterism/AsterismUITests/AssociationNotesUITests.swift b/Asterism/AsterismUITests/AssociationNotesUITests.swiftindex 5aff2133..e314e11e 100644--- a/Asterism/AsterismUITests/AssociationNotesUITests.swift+++ b/Asterism/AsterismUITests/AssociationNotesUITests.swift@@ -733,6 +733,23 @@ final class AssociationNotesUITests: XCTestCase { retainFailure("Place history actual title and trailing date") } + func testOrdinaryChapterLinkRemoveRestoreKeepsTheNoteEditorRoute() {+ openChapter()+ let remove = app.buttons["entry-association-remove-character-\(characterID)"]+ XCTAssertTrue(remove.waitForExistence(timeout: 15))+ activate(remove)+ let restore = app.buttons["entry-association-restore-character-\(characterID)"]+ XCTAssertTrue(restore.waitForExistence(timeout: 15), "The removed link remains available for explicit restoration")+ XCTAssertFalse(app.buttons["entry-association-character-\(characterID)"].isEnabled,+ "Removal does not route a removed pair into its note editor")+ activate(restore)+ let restoredRemove = app.buttons["entry-association-remove-character-\(characterID)"]+ XCTAssertTrue(restoredRemove.waitForExistence(timeout: 15))+ let note = openNote()+ XCTAssertTrue(note.exists, "Restoration returns the ordinary primary note-editor route")+ XCTAssertEqual(note.value as? String, "Saved arrival note")+ }+ func testRecordHistoryWindowsCapturedBodiesAndExistingEditorRoute() { openHistoryFixture() let pill = app.buttons.matching(identifier: "work-detail-character").firstMatch
diff --git a/Asterism/AsterismUITests/CharacterGroupsUITests.swift b/Asterism/AsterismUITests/CharacterGroupsUITests.swiftnew file mode 100644index 00000000..839cc68c--- /dev/null+++ b/Asterism/AsterismUITests/CharacterGroupsUITests.swift@@ -0,0 +1,642 @@+import XCTest++#if !os(macOS)+/// The smallest rendered Work-detail journey for the named-group editor.+/// Model tests pin the edit transaction; this verifies its entry point and+/// that only Save publishes the draft back into the roster.+final class CharacterGroupsUITests: XCTestCase {+ let app = XCUIApplication()++ override func setUp() {+ continueAfterFailure = false+ XCUIDevice.shared.orientation = .portrait+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-characters"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "unavailable"+ app.launch()+ }++ override func tearDown() { terminateAndWaitForExit(app) }++ func testGroupEditorCancelAndSave() {+ waitFor(app.anyElement("recent-list"), "The seeded library opens", timeout: 60)+ openAllWorks(in: app)+ waitFor(app.anyElement("works-group-allWorks"), "The Works list opens")+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch,+ "The seeded Work is listed").tap()+ waitFor(app.anyElement("work-detail-pulse"), "Work detail opens")++ XCTAssertFalse(app.buttons["work-detail.add-group"].exists,+ "Group creation belongs to Work edit mode")+ XCTAssertFalse(app.buttons["Edit group"].exists,+ "The view-mode roster is read-only")+ attachSurface("group-view-mode")+ waitFor(app.buttons["work-detail-edit-button"], "Work detail offers edit mode").tap()+ let addGroup = app.buttons["work-detail.add-group"]+ scrollUntilPresent(addGroup, in: app, "Work edit mode includes the group card")+ app.swipeUp()+ attachSurface("group-work-edit-mode")+ scrollUntilTappableAndTap(addGroup, in: app, "Work edit mode offers group creation")+ let name = app.textFields["group-editor.name"]+ waitFor(name, "The group editor opens")+ attachSurface("group-editor")+ name.tap()+ XCTAssertFalse(app.buttons["Delete group"].exists,+ "An unsaved draft has no delete action")+ name.typeText("Discarded group")+ app.buttons["group-editor.cancel"].tap()+ waitFor(addGroup, "Cancel returns to Work detail")+ XCTAssertFalse(app.staticTexts["Discarded group"].exists,+ "A cancelled draft does not publish a group")++ addGroup.tap()+ waitFor(name, "The group editor can reopen").tap()+ name.typeText("Cancelled Work edit group")+ app.buttons["group-editor.save"].tap()+ waitFor(addGroup, "Done returns to the enclosing Work edit")+ let stagedGroupLine = app.descendants(matching: .any)+ .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group-edit."))+ XCTAssertTrue(stagedGroupLine.firstMatch.exists,+ "The group draft is visible inside the Work edit session")+ app.buttons["work-detail-edit-cancel-button"].tap()+ waitFor(app.buttons["work-detail-edit-button"], "Work Cancel discards the group draft")+ XCTAssertFalse(app.staticTexts["Cancelled Work edit group"].exists,+ "Cancelling the enclosing Work edit persists none of its group draft")++ waitFor(app.buttons["work-detail-edit-button"], "Work detail can start another edit").tap()+ scrollUntilTappableAndTap(addGroup, in: app, "The new Work edit can add a group")+ waitFor(name, "The group editor opens in the new edit").tap()+ name.typeText("The Night Crew")+ app.buttons["group-editor.save"].tap()+ let groupEditLine = app.descendants(matching: .any)+ .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group-edit.")).firstMatch+ scrollUntilPresent(groupEditLine, in: app,+ "Saving publishes the group in the edit card")+ XCTAssertTrue(app.staticTexts["The Night Crew"].exists)+ app.buttons["work-detail-save-button"].tap()+ waitFor(app.buttons["work-detail-edit-button"], "Saving the Work returns to view mode")+ scrollUntilPresent(app.staticTexts["The Night Crew"], in: app,+ "View mode shows the saved group roster")+ attachSurface("group-saved-view-mode")+ XCTAssertFalse(app.buttons["work-detail.add-group"].exists,+ "Group creation is absent from view mode")+ XCTAssertFalse(app.buttons["Edit group"].exists,+ "Saved roster remains read-only in view mode")+ }++ func testConflictedMembershipRequiresExplicitChoiceInLightAndDark() {+ for appearance in ["Light", "Dark"] {+ terminateAndWaitForExit(app)+ XCUIDevice.shared.appearance = appearance == "Dark" ? .dark : .light+ app.launchArguments = ["-AppleInterfaceStyle", appearance]+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-characters"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "unavailable"+ app.launchEnvironment["ASTERISM_UI_TEST_GROUP_CONFLICT"] = "1"+ app.launch()++ waitFor(app.anyElement("recent-list"), "The conflicted synthetic library opens", timeout: 60)+ openAllWorks(in: app)+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch,+ "The conflicted Work is listed").tap()+ waitFor(app.anyElement("work-detail-pulse"), "Work detail opens")+ app.buttons["work-detail-edit-button"].tap()+ let group = app.descendants(matching: .any).matching(NSPredicate(+ format: "identifier BEGINSWITH %@", "work-detail.group-edit.")).firstMatch+ scrollUntilTappableAndTap(group, in: app, "The unresolved group opens in the ordinary editor")++ let chapter = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@",+ "group-editor.conflict-chapter.")).firstMatch+ let join = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND identifier ENDSWITH %@",+ "group-editor.conflict-action.", ".join")).firstMatch+ let leave = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND identifier ENDSWITH %@",+ "group-editor.conflict-action.", ".leave")).firstMatch+ waitFor(chapter, "The conflict has a chapter choice")+ waitFor(join, "The conflict has an explicit Join choice")+ XCTAssertFalse(join.isSelected)+ XCTAssertFalse(leave.isSelected)+ XCTAssertEqual(chapter.value as? String, "Choose chapter")+ attachSurface("group-conflict-\(appearance.lowercased())-unresolved")++ join.tap()+ app.buttons["group-editor.save"].tap()+ waitFor(app.anyElement("group-editor.error"),+ "An incomplete resolution stays in the nested editor")+ XCTAssertTrue(app.buttons["group-editor.save"].exists)+ chapter.tap()+ waitFor(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Chapter 1")).firstMatch,+ "The saved chapter is selectable").tap()+ XCTAssertTrue(join.isSelected)+ XCTAssertFalse(leave.isSelected)+ XCTAssertFalse(app.anyElement("group-editor.error").exists,+ "Completing the explicit choice clears the stale partial-selection error")+ attachSurface("group-conflict-\(appearance.lowercased())-explicit-join")+ app.buttons["group-editor.save"].tap()+ waitFor(app.buttons["work-detail-save-button"],+ "The explicit choice is staged in the enclosing Work edit")+ app.buttons["work-detail-edit-cancel-button"].tap()+ waitFor(app.buttons["work-detail-edit-button"],+ "Work Cancel discards the explicit resolution")+ app.buttons["work-detail-edit-button"].tap()+ scrollUntilTappableAndTap(group, in: app,+ "The unresolved group remains editable after Work Cancel")+ waitFor(join, "The original conflict remains unresolved")+ XCTAssertFalse(join.isSelected)+ XCTAssertFalse(leave.isSelected)+ chapter.tap()+ waitFor(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Chapter 1")).firstMatch,+ "The chapter is still selectable after Work Cancel").tap()+ join.tap()+ app.buttons["group-editor.save"].tap()+ app.buttons["work-detail-save-button"].tap()+ waitFor(app.buttons["work-detail-edit-button"],+ "Work Save commits the explicit transition resolution")+ let savedGroup = app.descendants(matching: .any).matching(NSPredicate(+ format: "identifier BEGINSWITH %@", "work-detail.group.")).firstMatch+ scrollUntilPresent(savedGroup, in: app, "The resolved group remains published")+ savedGroup.tap()+ let membership = app.staticTexts.matching(NSPredicate(+ format: "label CONTAINS %@ AND label CONTAINS %@", "Brede", "–")).firstMatch+ waitFor(membership, "The saved Join publishes Brede's membership range")+ app.buttons["work-detail-edit-button"].tap()+ scrollUntilTappableAndTap(group, in: app,+ "The saved group reopens without an unresolved row")+ XCTAssertFalse(chapter.exists,+ "An accepted explicit successor removes the conflict editor row")+ XCTAssertTrue(app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@",+ "group-editor.transition-action.")).firstMatch.exists,+ "The resolved membership uses the ordinary editable history row")+ }+ }++ func testDeleteGroupStagesUntilEnclosingWorkSave() {+ waitFor(app.anyElement("recent-list"), "The seeded library opens", timeout: 60)+ openAllWorks(in: app)+ waitFor(app.anyElement("works-group-allWorks"), "The Works list opens")+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch,+ "The seeded Work is listed").tap()+ waitFor(app.anyElement("work-detail-pulse"), "Work detail opens")++ waitFor(app.buttons["work-detail-edit-button"], "Work detail offers edit mode").tap()+ let addGroup = app.buttons["work-detail.add-group"]+ scrollUntilTappableAndTap(addGroup, in: app, "Work edit mode can create a group")+ let groupName = app.textFields["group-editor.name"]+ waitFor(groupName, "The group editor opens").tap()+ groupName.typeText("Delete Only On Save")+ app.buttons["group-editor.save"].tap()+ let groupEditLine = app.descendants(matching: .any)+ .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group-edit."))+ .firstMatch+ scrollUntilPresent(groupEditLine, in: app, "Work edit shows the group before it is saved")+ let viewGroupIdentifier = groupEditLine.identifier.replacingOccurrences(+ of: "work-detail.group-edit.", with: "work-detail.group.")+ let viewGroup = app.descendants(matching: .any)+ .matching(identifier: viewGroupIdentifier).firstMatch+ app.buttons["work-detail-save-button"].tap()+ waitFor(app.buttons["work-detail-edit-button"], "The group has been saved")++ waitFor(app.buttons["work-detail-edit-button"], "The saved Work can be edited").tap()+ scrollUntilTappableAndTap(groupEditLine, in: app, "The saved group can be deleted")+ XCTAssertEqual(app.buttons["group-editor.cancel"].label, "Cancel",+ "The native close role keeps the spoken Cancel label")+ XCTAssertEqual(app.buttons["group-editor.save"].label, "Done",+ "The native confirm role keeps the spoken Done label")+ let delete = app.buttons["group-editor.delete"]+ waitFor(delete, "The editor offers direct staged deletion")+ XCTAssertEqual(delete.label, "Delete group",+ "The destructive row has a clear accessible label")+ attachSurface("group-editor-native-toolbar-and-delete-row")+ delete.tap()+ XCTAssertTrue(app.buttons["group-editor.save"].waitForNonExistence(timeout: 10),+ "Delete stages the removal and dismisses the nested editor without a prompt")+ XCTAssertFalse(app.alerts["Delete this group and its membership history?"].exists,+ "Deleting a group has no confirmation dialog")++ app.buttons["work-detail-edit-cancel-button"].tap()+ waitFor(app.buttons["work-detail-edit-button"], "Work Cancel returns to view mode")+ scrollUntilPresent(viewGroup, in: app, "Cancelling the Work edit restores the saved group")++ waitFor(app.buttons["work-detail-edit-button"], "The saved group can be edited again").tap()+ scrollUntilTappableAndTap(groupEditLine, in: app, "The saved group can be deleted again")+ waitFor(app.buttons["group-editor.delete"], "The editor offers direct staged deletion").tap()+ XCTAssertTrue(app.buttons["group-editor.save"].waitForNonExistence(timeout: 10),+ "The second delete also stages and dismisses immediately")+ app.buttons["work-detail-save-button"].tap()+ waitFor(app.buttons["work-detail-edit-button"], "Work Save accepts the deletion")+ XCTAssertTrue(viewGroup.waitForNonExistence(timeout: 10),+ "The saved Work no longer publishes the deleted group")+ }++ func testGlassSortAndMembershipControlsInLightAndDark() {+ for appearance in ["Dark", "Light"] {+ terminateAndWaitForExit(app)+ XCUIDevice.shared.appearance = appearance == "Dark" ? .dark : .light+ app.launchArguments = ["-AppleInterfaceStyle", appearance]+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-characters"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "unavailable"+ app.launch()++ waitFor(app.anyElement("recent-list"), "The \(appearance) synthetic library opens", timeout: 60)+ openAllWorks(in: app)+ waitFor(app.anyElement("works-group-allWorks"), "All works opens in \(appearance)")+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch,+ "The seeded Work is listed in \(appearance)").tap()+ waitFor(app.anyElement("work-detail-pulse"), "Work detail opens in \(appearance)")++ let newest = app.buttons["work-detail-sort-newest"]+ let chapter = app.buttons["work-detail-sort-chapter"]+ let sortControl = app.descendants(matching: .any)+ .matching(identifier: "work-detail-sort-control").firstMatch+ scrollUntilPresent(newest, in: app, "The chapter sort control draws in \(appearance)")+ XCTAssertTrue(sortControl.exists, "The sort control has one accessible container")+ XCTAssertEqual(sortControl.label, "Sort order")+ XCTAssertTrue(newest.isSelected, "Newest starts selected in \(appearance)")+ XCTAssertFalse(chapter.isSelected, "Chapter starts unselected in \(appearance)")+ XCTAssertGreaterThanOrEqual(newest.frame.height, 44,+ "Newest keeps a 44 pt target in \(appearance)")+ attachSurface("group-controls-sort-\(appearance.lowercased())-newest-selected")+ chapter.tap()+ XCTAssertTrue(chapter.isSelected, "Chapter becomes selected in (appearance)")+ XCTAssertFalse(newest.isSelected, "Selecting Chapter clears Newest in (appearance)")+ attachSurface("group-controls-sort-\(appearance.lowercased())-chapter-selected")++ waitFor(app.buttons["work-detail-edit-button"], "The Work editor opens in \(appearance)").tap()+ let workStatus = app.buttons["work-detail-work-status-ongoing"]+ let readingStatus = app.buttons["work-detail-reading-status-reading"]+ scrollUntilPresent(workStatus, in: app,+ "The Work and Reading status selectors use the shared segmented style in \(appearance)")+ XCTAssertTrue(workStatus.isSelected, "Ongoing is selected in \(appearance)")+ XCTAssertTrue(readingStatus.isSelected, "Reading is selected in \(appearance)")+ XCTAssertGreaterThanOrEqual(workStatus.frame.height, 44,+ "Work status retains a 44 pt target in \(appearance)")+ XCTAssertGreaterThanOrEqual(readingStatus.frame.height, 44,+ "Reading status retains a 44 pt target in \(appearance)")+ scrollUntilTappableAndTap(readingStatus, in: app,+ "The Reading selector scrolls fully into view in \(appearance)")+ XCTAssertTrue(readingStatus.isSelected,+ "Tapping the already-selected Reading option leaves the status unchanged")+ attachSurface("group-controls-work-and-reading-status-\(appearance.lowercased())")++ let addGroup = app.buttons["work-detail.add-group"]+ scrollUntilTappableAndTap(addGroup, in: app,+ "Work edit mode can add a group in \(appearance)")+ let name = app.textFields["group-editor.name"]+ waitFor(name, "The group editor opens in \(appearance)").tap()+ name.typeText("Glass Controls \(appearance)")+ XCTAssertEqual(app.buttons["group-editor.cancel"].label, "Cancel")+ XCTAssertEqual(app.buttons["group-editor.save"].label, "Done")+ attachSurface("group-editor-toolbar-\(appearance.lowercased())")+ app.buttons["group-editor.save"].tap()+ let groupEditLine = app.descendants(matching: .any)+ .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group-edit."))+ .firstMatch+ scrollUntilTappableAndTap(groupEditLine, in: app,+ "The group can be edited in \(appearance)")++ let join = app.buttons["group-editor.new-transition-action.join"]+ let leave = app.buttons["group-editor.new-transition-action.leave"]+ let actionControl = app.descendants(matching: .any)+ .matching(identifier: "group-editor.new-transition-action").firstMatch+ XCTAssertTrue(join.waitForExistence(timeout: 15), "Join is available in \(appearance)")+ XCTAssertTrue(leave.exists, "Leave is available in \(appearance)")+ XCTAssertTrue(actionControl.exists,+ "Join and Leave remain under one accessible container in \(appearance)")+ XCTAssertEqual(actionControl.label, "Membership action")+ XCTAssertTrue(join.isSelected, "Join is selected in \(appearance)")+ XCTAssertFalse(leave.isSelected, "Leave is unselected in \(appearance)")+ XCTAssertGreaterThanOrEqual(join.frame.height, 44,+ "Join keeps a 44 pt target in \(appearance)")+ attachSurface("group-controls-membership-\(appearance.lowercased())-join-selected")+ leave.tap()+ XCTAssertTrue(leave.isSelected, "Leave becomes selected in \(appearance)")+ XCTAssertFalse(join.isSelected, "Selecting Leave clears Join in \(appearance)")+ attachSurface("group-controls-membership-\(appearance.lowercased())-leave-selected")+ app.buttons["group-editor.cancel"].tap()+ app.buttons["work-detail-edit-cancel-button"].tap()+ }+ XCUIDevice.shared.appearance = .light+ }++ func testWorksStatusSheetUsesTheSharedGlassReadingSelectorInLightAndDark() {+ for appearance in ["Dark", "Light"] {+ terminateAndWaitForExit(app)+ XCUIDevice.shared.appearance = appearance == "Dark" ? .dark : .light+ app.launchArguments = ["-AppleInterfaceStyle", appearance]+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-characters"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "unavailable"+ app.launch()++ waitFor(app.anyElement("recent-list"), "The synthetic library opens in \(appearance)", timeout: 60)+ openAllWorks(in: app)+ waitFor(app.anyElement("works-group-allWorks"), "All works opens in \(appearance)")+ let row = app.elements(withIdentifierPrefix: "work-row-").firstMatch+ waitFor(row, "The seeded Work is listed in \(appearance)").press(forDuration: 1)+ let changeStatus = app.buttons["Change status…"]+ waitFor(changeStatus, "The Work menu offers status editing in \(appearance)").tap()++ let reading = app.buttons["work-detail-reading-status-reading"]+ waitFor(reading, "The status sheet opens with its shared glass reading selector in \(appearance)")+ XCTAssertTrue(app.staticTexts["Reading status"].exists,+ "The five status choices have a visible, accessible purpose label in \(appearance)")+ XCTAssertTrue(reading.isSelected, "Reading is selected in \(appearance)")+ XCTAssertGreaterThanOrEqual(reading.frame.height, 44,+ "The status sheet keeps a 44 pt target in \(appearance)")+ attachSurface("group-controls-status-sheet-\(appearance.lowercased())-reading-selected")+ }+ XCUIDevice.shared.appearance = .light+ }++ func testManualJoinPublishesReciprocalChapterRangeAndAccessibleActions() {+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-characters"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "unavailable"+ app.launchEnvironment["ASTERISM_UI_TEST_LEGACY_FACTS"] = "1"+ app.launch()++ waitFor(app.anyElement("recent-list"), "The synthetic library opens", timeout: 60)+ openAllWorks(in: app)+ waitFor(app.anyElement("works-group-allWorks"), "The Works list opens")+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch,+ "The seeded Work is listed").tap()+ waitFor(app.anyElement("work-detail-pulse"), "Work detail opens")++ let character = app.buttons.matching(+ NSPredicate(format: "label == %@", "Brede, character")).firstMatch+ waitFor(character, "The seeded character is available")+ character.tap()+ waitFor(app.buttons["work-detail-edit-button"], "Work detail offers edit mode").tap()+ let addGroup = app.buttons["work-detail.add-group"]+ scrollUntilTappableAndTap(addGroup, in: app, "Work edit mode can create a group")+ let name = app.textFields["group-editor.name"]+ waitFor(name, "The group editor opens").tap()+ name.typeText("The Night Crew")+ app.buttons["group-editor.save"].tap()++ let groupEditLine = app.descendants(matching: .any)+ .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group-edit.")).firstMatch+ scrollUntilTappableAndTap(groupEditLine, in: app, "The group appears in the edit card")+ let joinAction = app.buttons["group-editor.new-transition-action.join"]+ let leaveAction = app.buttons["group-editor.new-transition-action.leave"]+ XCTAssertTrue(joinAction.waitForExistence(timeout: 15),+ "The transition editor uses the accessible Join/Leave capsule")+ XCTAssertTrue(leaveAction.exists)+ let actionControl = app.descendants(matching: .any)+ .matching(identifier: "group-editor.new-transition-action").firstMatch+ XCTAssertEqual(actionControl.label, "Membership action")+ XCTAssertTrue(joinAction.isSelected, "Join is selected for a new membership")+ XCTAssertFalse(leaveAction.isSelected, "Leave is unselected for a new membership")+ attachSurface("group-transition-editor-join-selected")+ leaveAction.tap()+ XCTAssertTrue(leaveAction.isSelected, "Leave can be selected")+ XCTAssertFalse(joinAction.isSelected, "Selecting Leave clears Join")+ attachSurface("group-transition-editor-leave-selected")+ joinAction.tap()+ XCTAssertTrue(joinAction.isSelected, "Join can be restored")+ attachSurface("group-transition-editor")+ let characterPicker = app.buttons.matching(+ NSPredicate(format: "label CONTAINS %@", "Character for membership change")).firstMatch+ waitFor(characterPicker, "The editor offers a character picker").tap()+ let existingCharacterOption = app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label == %@",+ "group-editor.character-option.", "Brede")).firstMatch+ waitFor(existingCharacterOption, "The existing character is selectable").tap()+ let chapterPicker = app.buttons.matching(+ NSPredicate(format: "label CONTAINS %@", "Chapter for membership change")).firstMatch+ waitFor(chapterPicker, "The editor offers a chapter picker").tap()+ waitFor(app.buttons.matching(+ NSPredicate(format: "label CONTAINS %@", "Chapter 1")).firstMatch,+ "The saved chapter is selectable").tap()+ XCTAssertEqual(chapterPicker.value as? String, "Chapter 1 - The Lamp Room",+ "The compact row label preserves the complete chapter title for accessibility")+ waitFor(app.buttons["group-editor.add-transition"], "A join can be added")+ .tap()+ app.buttons["group-editor.save"].tap()+ app.buttons["work-detail-save-button"].tap()++ let characterMembership = app.staticTexts.matching(+ NSPredicate(format: "label CONTAINS %@ AND label CONTAINS %@", "The Night Crew", "–"))+ .firstMatch+ XCTAssertTrue(characterMembership.waitForExistence(timeout: 15),+ "The character card refreshes with the reciprocal group and range")+ attachSurface("group-membership-character")+ XCTAssertTrue(app.buttons["work-detail-character"].exists,+ "The character entry point has a stable accessible identity")++ // Work detail is a lazy List: the roster section sits below the open+ // character card and is absent from the accessibility tree until we+ // scroll it into view.+ let group = app.descendants(matching: .any)+ .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group.")).firstMatch+ for _ in 0..<8 where !group.exists {+ app.swipeUp()+ _ = group.waitForExistence(timeout: 2)+ }+ if !group.exists {+ let error = app.anyElement("group-editor.error")+ let save = app.buttons["group-editor.save"]+ let relevantHierarchy = app.debugDescription+ .split(whereSeparator: \.isNewline)+ .filter { line in+ ["Character groups", "The Night Crew", "work-detail.group.", "Brede"]+ .contains { line.localizedCaseInsensitiveContains($0) }+ }+ .joined(separator: "\n")+ XCTFail("The saved group disclosure did not enter the accessibility tree after scrolling; editorError=\(error.exists ? error.label : "<none>"), editorStillOpen=\(save.exists), matchingHierarchy=\(relevantHierarchy)")+ return+ }+ let groupMembership = app.staticTexts.matching(+ NSPredicate(format: "label CONTAINS %@ AND label CONTAINS %@", "Brede", "–"))+ .firstMatch+ if !groupMembership.exists { group.tap() }+ XCTAssertTrue(groupMembership.waitForExistence(timeout: 15),+ "The group disclosure shows the member and its open-ended chapter range")+ attachSurface("group-membership-roster")++ waitFor(app.buttons["work-detail-edit-button"],+ "The saved Work can reopen its edit session").tap()+ scrollUntilTappableAndTap(groupEditLine, in: app,+ "The saved group can reopen its membership editor")+ let existingTransitionAction = app.buttons.matching(+ NSPredicate(format: "identifier BEGINSWITH %@", "group-editor.transition-action.")).firstMatch+ XCTAssertTrue(existingTransitionAction.waitForExistence(timeout: 15),+ "A saved membership keeps its accessible Join/Leave control beside its chapter")+ attachSurface("group-transition-existing-membership")+ app.buttons["group-editor.cancel"].tap()+ app.buttons["work-detail-edit-cancel-button"].tap()+ }++ func testGroundedGroupAndJoinApprovalsPublishRoster() {+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-characters"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "named-groups"+ app.launchEnvironment["ASTERISM_UI_TEST_GROUP_JOURNEY"] = "1"+ app.launchEnvironment["ASTERISM_UI_TEST_LEGACY_FACTS"] = "1"+ app.launch()++ waitFor(app.anyElement("recent-list"), "The synthetic library opens", timeout: 60)+ openAllWorks(in: app)+ waitFor(app.anyElement("works-group-allWorks"), "Works lists the seeded library")+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch,+ "The seeded Work is listed").tap()+ waitFor(app.anyElement("work-detail-pulse"), "Work detail opens")+ waitFor(app.anyElement("work-detail-character-proposals"),+ "Grounded group proposals are raised", timeout: 60)+ waitFor(app.buttons["work-detail-review-characters-button"],+ "The proposal indicator opens review").tap()+ waitFor(app.anyElement("character-review-banner"), "Review opens")++ let createRow = app.staticTexts["Create this group"]+ let joinRow = app.staticTexts["Add Brede from this chapter"]+ waitFor(createRow, "Review presents the grounded group creation")+ waitFor(joinRow, "Review presents the exact-note member join")+ let keepButtons = app.buttons.matching(+ NSPredicate(format: "identifier BEGINSWITH %@", "group-review-keep-"))+ XCTAssertEqual(keepButtons.count, 2, "Creation and join each require explicit approval")+ keepButtons.firstMatch.tap()++ waitFor(joinRow, "Approving creation leaves the join for a separate decision")+ XCTAssertEqual(keepButtons.count, 1)+ keepButtons.firstMatch.tap()+ waitFor(app.buttons["character-review-done"],+ "Review can be closed after both approvals").tap()+ waitUntilGone(app.anyElement("character-review-banner"),+ "Closing review refreshes the Work detail", timeout: 20)+ let group = app.descendants(matching: .any)+ .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group.")).firstMatch+ for _ in 0..<8 where !group.exists {+ app.swipeUp()+ _ = group.waitForExistence(timeout: 2)+ }+ if !group.exists {+ let relevantHierarchy = app.debugDescription+ .split(whereSeparator: \.isNewline)+ .filter { line in+ ["work-detail", "The Night Crew", "Character groups", "Brede", "recent-list", "works-group"]+ .contains { line.localizedCaseInsensitiveContains($0) }+ }+ .joined(separator: "\n")+ XCTFail("Approved group disclosure is still absent after scrolling; matchingHierarchy=\(relevantHierarchy)")+ return+ }+ let member = app.staticTexts.matching(+ NSPredicate(format: "label CONTAINS %@ AND label CONTAINS %@", "Brede", "–"))+ .firstMatch+ if !member.exists { group.tap() }+ XCTAssertTrue(member.waitForExistence(timeout: 15),+ "The approved join appears with its open-ended chapter range")+ }++ func testLeaveReviewCaptionIncludesItsChapter() {+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-characters"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "named-groups-leave"+ app.launchEnvironment["ASTERISM_UI_TEST_GROUP_LEAVE_JOURNEY"] = "1"+ app.launchEnvironment["ASTERISM_UI_TEST_LEGACY_FACTS"] = "1"+ app.launch()++ waitFor(app.anyElement("recent-list"), "The synthetic group library opens", timeout: 60)+ openAllWorks(in: app)+ waitFor(app.anyElement("works-group-allWorks"), "Works lists the seeded library")+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch,+ "The seeded Work is listed").tap()+ waitFor(app.anyElement("work-detail-pulse"), "Work detail opens")+ waitFor(app.anyElement("work-detail-character-proposals"),+ "The grounded leave proposal is raised", timeout: 60)+ waitFor(app.buttons["work-detail-review-characters-button"],+ "The proposal indicator opens review").tap()+ waitFor(app.anyElement("character-review-banner"), "Review opens")++ let caption = app.staticTexts[+ "Brede remains in the group through this chapter; removal starts afterward."]+ waitFor(caption, "The leave caption explicitly includes its named chapter")+ XCTAssertTrue(app.staticTexts["Brede leaves The Night Crew"].exists,+ "The exact saved chapter quote remains visible beside the caption")+ attachSurface("group-review-inclusive-leave-caption")+ app.buttons["character-review-done"].tap()+ }++ private func attachSurface(_ name: String) {+ let attachment = XCTAttachment(screenshot: app.screenshot())+ attachment.name = name+ attachment.lifetime = .keepAlways+ add(attachment)+ }+}+#endif++#if os(macOS)+/// Native Mac entry/save/cancel journey. The iOS helper extensions are not+/// available to the macOS UI test target, so this test keeps its queries local.+final class CharacterGroupsMacUITests: XCTestCase {+ private let app = XCUIApplication()++ override func setUp() {+ continueAfterFailure = false+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-characters"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "unavailable"+ app.launch()+ }++ override func tearDown() { terminateAndWaitForExit(app) }++ private func element(_ identifier: String) -> XCUIElement {+ app.descendants(matching: .any).matching(identifier: identifier).firstMatch+ }++ private func require(_ element: XCUIElement, _ message: String, timeout: TimeInterval = 30) {+ XCTAssertTrue(element.waitForExistence(timeout: timeout), message)+ }++ func testGroupEditorCancelAndSaveOnMac() {+ require(element("recent-list"), "The synthetic library opens", timeout: 60)+ let allWorks = app.buttons["sidebar-library-allWorks"]+ require(allWorks, "The native sidebar offers all works")+ allWorks.tap()+ require(element("works-group-allWorks"), "All works opens")+ let work = app.buttons.matching(+ NSPredicate(format: "identifier BEGINSWITH %@", "work-row-")).firstMatch+ require(work, "The seeded Work is listed")+ work.tap()+ require(element("work-detail-pulse"), "Work detail opens")++ XCTAssertFalse(app.buttons["work-detail.add-group"].exists,+ "Group creation belongs to Work edit mode")+ XCTAssertFalse(app.buttons["Edit group"].exists,+ "View-mode groups are read-only")+ app.buttons["work-detail-edit-button"].tap()+ let addGroup = app.buttons["work-detail.add-group"]+ require(addGroup, "Work detail offers group creation")+ addGroup.tap()+ let name = app.textFields["group-editor.name"]+ require(name, "The group editor opens")+ name.tap()+ XCTAssertFalse(app.buttons["Delete group"].exists,+ "An unsaved draft has no delete action")+ name.typeText("Discarded group")+ app.buttons["group-editor.cancel"].tap()+ require(addGroup, "Cancel returns to Work detail")+ XCTAssertFalse(app.staticTexts["Discarded group"].exists,+ "A cancelled draft does not publish a group")++ addGroup.tap()+ require(name, "The editor can reopen")+ name.tap()+ name.typeText("The Night Crew")+ app.buttons["group-editor.save"].tap()+ let groupLine = app.buttons.matching(+ NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group-edit.")).firstMatch+ require(groupLine, "Saving publishes the group in edit mode")+ app.buttons["work-detail-save-button"].tap()+ XCTAssertFalse(app.buttons["work-detail.add-group"].exists,+ "Group creation is absent from view mode")+ }+}+#endif
diff --git a/Asterism/AsterismUITests/UIJourneySupport.swift b/Asterism/AsterismUITests/UIJourneySupport.swiftindex ae05fd9e..4f3916fc 100644--- a/Asterism/AsterismUITests/UIJourneySupport.swift+++ b/Asterism/AsterismUITests/UIJourneySupport.swift@@ -406,11 +406,14 @@ extension XCTestCase { func scrollUntilTappableAndTap( _ element: XCUIElement, in app: XCUIApplication, _ message: String, attempts: Int = 8, scroll: (XCUIApplication) -> Void = { $0.swipeUp() },+ readyToTap: ((XCUIElement) -> Bool)? = nil,+ beforeTap: ((XCUIElement) -> Void)? = nil, file: StaticString = #filePath, line: UInt = #line ) { _ = element.waitForExistence(timeout: 15) for _ in 0..<attempts {- if element.exists, element.isHittable {+ if element.exists, element.isHittable, readyToTap?(element) ?? true {+ beforeTap?(element) element.tap() return }
diff --git a/Asterism/AsterismUITests/WorkDetailStatusUITests.swift b/Asterism/AsterismUITests/WorkDetailStatusUITests.swiftindex c6c78100..8cdc5a70 100644--- a/Asterism/AsterismUITests/WorkDetailStatusUITests.swift+++ b/Asterism/AsterismUITests/WorkDetailStatusUITests.swift@@ -88,7 +88,7 @@ final class WorkDetailStatusUITests: XCTestCase { /// help: it stops as soon as the row is hittable. This is the nudge /// `docs/agent-notes/testing.md` prescribes for exactly that shape. private func openWork(_ title: String) {- waitFor(app.collectionViews["recent-list"], "The library opens", timeout: 60)+ waitFor(app.anyElement("recent-list"), "The library opens", timeout: 60) openAllWorks(in: app) waitFor(app.anyElement("works-group-allWorks"), "Works lists the seeded library") let target = row(titled: title)
diff --git a/Asterism/SharedUI/ShareCharacterChipsView.swift b/Asterism/SharedUI/ShareCharacterChipsView.swiftindex 391491da..533879b4 100644--- a/Asterism/SharedUI/ShareCharacterChipsView.swift+++ b/Asterism/SharedUI/ShareCharacterChipsView.swift@@ -286,13 +286,14 @@ struct ShareCharacterChipsView: View { } .frame(maxWidth: .infinity, alignment: .leading) - if character.note.isEmpty && character.aliases.isEmpty {+ if character.note.isEmpty && character.aliases.isEmpty && character.memberships.isEmpty { // Q5: every chip opens a card, so a character with nothing // behind it says so rather than coming up blank. Text(ShareCharacterChips.emptyDetailText) .font(.subheadline) .foregroundStyle(AsterismColors.secondaryText) }+ ForEach(character.memberships, id: \.self) { Text($0).font(.subheadline) } if !character.note.isEmpty { // The note arrives trimmed from the read and keeps its own line // breaks; nothing is clamped, as the work page shows it.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationEndpoints.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationEndpoints.swiftindex 7a937556..aa7eaf8d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AssociationEndpoints.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationEndpoints.swift@@ -33,15 +33,32 @@ struct AssociationEndpointInventory { var targetOwnerIDs: [AssociationRecordAddress: Set<UUID>] var liveWorkIDs: Set<UUID> var endpointFetchCount: Int+ var groupSupportsByPair: [AssociationPair: [AssociationGroupSupport]] func current(_ pair: AssociationPair) -> AssociationCurrentPair? {+ current(pair, groupSupports: groupSupportsByPair[pair, default: []])+ }+ /// The caller supplies supports produced by the shared complete-name+ /// resolver and a coherent chapter roster. Recheck the saved source and+ /// endpoint identities here before granting a V22 group receipt.+ func current(_ pair: AssociationPair,+ groupSupports: [AssociationGroupSupport]) -> 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 }+ let eligibleGroups: [AssociationGroupSupport] = pair.kind == .character+ ? groupSupports.filter { support in+ support.version == 22 && !support.transitionEventIDs.isEmpty &&+ RecordNameKey.normalize(support.spellingKey) == support.spellingKey &&+ RecordMentionGrounding.completeNameEvidence(names: [support.spelling],+ in: source.note).contains { $0.key == support.spellingKey &&+ $0.spelling == support.spelling }+ } : []+ guard !evidence.isEmpty || !eligibleGroups.isEmpty else { return nil } return .init(pair: pair, sourceFingerprint: source.fingerprint,- matchingFingerprint: target.fingerprint, evidence: evidence)+ matchingFingerprint: target.fingerprint, evidence: evidence,+ groupSupports: eligibleGroups) } static func read(context: ModelContext, pairs: Set<AssociationPair>, entryIDs explicitEntries: Set<UUID> = [],@@ -87,9 +104,12 @@ struct AssociationEndpointInventory { fetches += 1 liveWorks = Set(try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { workIDs.contains($0.id) })).map(\.id)) }+ let groupSupports = try GroupSupportInventory.supports(pairs: pairs,+ sources: sources, context: context) return .init(sources: sources, targets: targets, sourceStates: sourceStates, targetStates: targetStates, sourceOwnerIDs: sourceOwners, targetOwnerIDs: targetOwners,- liveWorkIDs: liveWorks, endpointFetchCount: fetches)+ liveWorkIDs: liveWorks, endpointFetchCount: fetches,+ groupSupportsByPair: groupSupports) } static func eligible(_ row: Entry) -> Bool { guard row.mergedIntoEntryID == nil else { return false }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationImportPreparation.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationImportPreparation.swiftindex 15d86dd0..9e1d24bb 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AssociationImportPreparation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationImportPreparation.swift@@ -22,13 +22,18 @@ struct AssociationImportPreparation { // 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)+ // Keep the local before-authority above, then make imported group proof+ // visible to the projected endpoint/receipt check. Staging it only in+ // the final record merge invents an invalidation barrier for an otherwise+ // coherent incoming group acceptance and detaches its authored note.+ try GroupImportPreparation.insertMissing(payload, context: context) 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 projection = try project(payload, onto: actual, pairs: pairs, 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@@ -201,6 +206,7 @@ struct AssociationImportPreparation { /// 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,+ pairs: Set<AssociationPair>, context: ModelContext) throws -> (endpoints: AssociationEndpointInventory, uncertainScopes: Set<AssociationScope>, arrivalScopes: Set<AssociationScope>) { var result = original var uncertainScopes: Set<AssociationScope> = [], arrivalScopes: Set<AssociationScope> = []@@ -311,6 +317,60 @@ struct AssociationImportPreparation { } try apply(payload.characters, type: CharacterRecord.self) try apply(payload.places, type: Place.self)+ let prospectiveSpines = try projectedChapterSpines(payload,+ endpoints: result, pairs: pairs, context: context)+ result.groupSupportsByPair = try GroupSupportInventory.supports(pairs: pairs,+ sources: result.sources, context: context, chapterSpines: prospectiveSpines,+ projectedTargets: result.targets) return (result, uncertainScopes, arrivalScopes) }++ /// An archive may carry a join chapter that the destination has not+ /// received yet. Build the projected spine from the same winning imported+ /// Entry fields as `project`, while retaining untouched local chapters.+ /// This is read-only; the importer still writes the rows in its usual order.+ private static func projectedChapterSpines(_ payload: BackupImportPayload,+ endpoints: AssociationEndpointInventory, pairs: Set<AssociationPair>,+ context: ModelContext) throws -> [UUID: [GroupChapter]] {+ let workIDs = Array(Set(pairs.map(\.workID)))+ guard !workIDs.isEmpty, !payload.chapterEntries.isEmpty else { return [:] }+ let works = try context.fetch(FetchDescriptor<Work>(+ predicate: #Predicate { workIDs.contains($0.id) }))+ let groups = LibraryRepository.workGroups(works,+ types: try LibraryRepository.workTypeDirectory(context: context))+ var spines: [UUID: [GroupChapter]] = [:]+ for (workID, group) in groups where !group.isTorn {+ var rows = try GroupSupportInventory.chapterRows(work: group, context: context)+ var imported: [WorkChapterRow] = []+ for record in payload.chapterEntries.values where record.workID == workID {+ guard let projected = endpoints.sources[record.id],+ projected.workID == workID,+ projected.fingerprint == AssociationEndpointInventory.sourceFingerprint(+ id: record.id, workID: workID, eligible: record.mergedIntoEntryID == nil,+ note: record.note) else { continue }+ let target = record.authoredTargetData.flatMap {+ try? AuthoredEntryTarget.decode($0)+ }+ guard record.mergedIntoEntryID == nil,+ target == nil || target?.kind == .chapter else { continue }+ let title = target?.title ?? record.chapterTitle ?? record.chapterSequence+ ?? record.captureTitle+ imported.append(WorkChapterRow(id: record.id, displayTitle: title,+ note: record.note, rating: record.rating,+ lastSharedAt: record.lastSharedAt,+ chapterKey: ChapterKeyDerivation.key(+ chapterSequence: record.chapterSequence,+ chapterTitle: record.chapterTitle),+ sequencePosition: ChapterKeyDerivation.position(+ chapterSequence: record.chapterSequence),+ showsTitle: target?.kind != .note || target?.title != nil,+ authoredTarget: target))+ }+ let replaced = Set(imported.map(\.id))+ rows.removeAll { replaced.contains($0.id) }+ spines[workID] = WorkChapterRow.inChapterOrder(rows + imported)+ .map { GroupChapter(id: $0.id, label: $0.displayTitle) }+ }+ return spines+ } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationLedger.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationLedger.swiftindex 69d82aa2..1fb7742e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AssociationLedger.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationLedger.swift@@ -42,10 +42,12 @@ public struct AssociationCurrentPair: Sendable, Equatable { public var sourceFingerprint: String public var matchingFingerprint: String public var evidence: [AssociationEvidence]+ public var groupSupports: [AssociationGroupSupport] public init(pair: AssociationPair, sourceFingerprint: String, matchingFingerprint: String,- evidence: [AssociationEvidence]) {+ evidence: [AssociationEvidence], groupSupports: [AssociationGroupSupport] = []) { self.pair = pair; self.sourceFingerprint = sourceFingerprint self.matchingFingerprint = matchingFingerprint; self.evidence = evidence+ self.groupSupports = groupSupports } } @@ -86,15 +88,46 @@ public struct AssociationRebind: Sendable, Equatable, Codable { } } +/// V22 roots name the source of their support. Nil on a legacy V21 root keeps+/// its historical direct payload and validation bytes unchanged.+public enum AssociationSupport: Sendable, Equatable, Codable {+ case direct(spellingKey: String)+ case group(groupID: UUID, spellingKey: String, transitionEventIDs: [UUID])+ public var spellingKey: String {+ switch self {+ case .direct(let key), .group(_, let key, _): return key+ }+ }+}++/// A complete group proof, supplied by the saved-note resolver and the+/// effective chapter roster. The ledger never mixes its fields with another+/// receipt, and the V21 direct receipt remains a separate domain.+public struct AssociationGroupSupport: Sendable, Equatable, Hashable, Codable {+ public let version: Int+ public let groupID: UUID+ public let spellingKey: String+ public let spelling: String+ public let transitionEventIDs: [UUID]+ public init(groupID: UUID, spellingKey: String, spelling: String,+ transitionEventIDs: [UUID]) {+ version = 22; self.groupID = groupID; self.spellingKey = spellingKey+ self.spelling = spelling+ self.transitionEventIDs = AssociationDigest.ordered(transitionEventIDs)+ }+}+ public struct AssociationAcceptance: Sendable, Equatable, Codable { public var pair: AssociationPair public var spellingKeys: [String] public var reconsideredRejectionIDs: [UUID] public var rebind: AssociationRebind?+ public var support: AssociationSupport? public init(pair: AssociationPair, spellingKeys: [String], reconsideredRejectionIDs: [UUID] = [],- rebind: AssociationRebind? = nil) {+ rebind: AssociationRebind? = nil, support: AssociationSupport? = nil) { self.pair = pair; self.spellingKeys = Array(Set(spellingKeys)).sorted()- self.reconsideredRejectionIDs = AssociationDigest.ordered(reconsideredRejectionIDs); self.rebind = rebind+ self.reconsideredRejectionIDs = AssociationDigest.ordered(reconsideredRejectionIDs)+ self.rebind = rebind; self.support = support } } @@ -106,6 +139,39 @@ public struct AssociationRejection: Sendable, Equatable, Codable { } } +/// Identity of the evidence source whose support was explicitly removed.+/// Group transition IDs are intentionally omitted: changing a roster does not+/// revive an unchanged group/name pair.+public enum AssociationPairSupportKey: Sendable, Hashable, Codable {+ case direct(spellingKey: String)+ case group(groupID: UUID, spellingKey: String)+}++public struct AssociationPairCorrection: Sendable, Equatable, Codable {+ public var pair: AssociationPair+ public var supports: [AssociationPairSupportKey]+ public init(pair: AssociationPair, supports: [AssociationPairSupportKey]) {+ self.pair = pair+ self.supports = Array(Set(supports)).sorted { lhs, rhs in+ func token(_ key: AssociationPairSupportKey) -> [String] {+ switch key {+ case .direct(let spelling): ["direct", "", spelling]+ case .group(let groupID, let spelling): ["group", groupID.uuidString, spelling]+ }+ }+ return token(lhs).lexicographicallyPrecedes(token(rhs))+ }+ }+}++public struct AssociationPairCorrectionAcknowledgement: Sendable, Equatable, Codable {+ public var pair: AssociationPair+ public var correctionIDs: [UUID]+ public init(pair: AssociationPair, correctionIDs: [UUID]) {+ self.pair = pair; self.correctionIDs = AssociationDigest.ordered(correctionIDs)+ }+}+ public struct AssociationRetirement: Sendable, Equatable, Codable { public var pair: AssociationPair public var acceptanceIDs: [UUID]@@ -123,6 +189,26 @@ public struct AssociationCoverage: Sendable, Equatable, Codable { } } +/// Evidence identity for a reader's Skip of a model-suggested group change.+/// It deliberately omits the whole-note fingerprint: an unrelated sentence+/// must not revive the same skipped name or join quote on the next sweep.+public enum GroupSuggestionKind: String, Sendable, Equatable, Codable { case create, join, leave }++public struct GroupSuggestionSkip: Sendable, Equatable, Hashable, Codable {+ public let workID: UUID+ public let chapterID: UUID+ public let kind: GroupSuggestionKind+ public let groupKey: String+ public let characterKey: String?+ public let evidenceKey: String+ public init(workID: UUID, chapterID: UUID, kind: GroupSuggestionKind,+ groupKey: String, characterKey: String? = nil, evidenceKey: String) {+ self.workID = workID; self.chapterID = chapterID; self.kind = kind+ self.groupKey = groupKey; self.characterKey = characterKey+ self.evidenceKey = evidenceKey+ }+}+ public enum AssociationEventPayload: Sendable, Equatable, Codable { case accept(AssociationAcceptance) case reject(AssociationRejection)@@ -131,21 +217,29 @@ public enum AssociationEventPayload: Sendable, Equatable, Codable { case coverage(AssociationCoverage) case pendingReview(AssociationPendingReview) case reviewAcknowledgement(AssociationReviewAcknowledgement)+ case groupSuggestionSkip(GroupSuggestionSkip)+ case pairCorrection(AssociationPairCorrection)+ case pairCorrectionAcknowledgement(AssociationPairCorrectionAcknowledgement) public var workID: UUID { switch self { case .accept(let value): value.pair.workID case .reject(let value): value.pair.workID+ case .pairCorrection(let value): value.pair.workID+ case .pairCorrectionAcknowledgement(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+ case .groupSuggestionSkip(let value): value.workID } } public var pair: AssociationPair? { switch self { case .accept(let value): value.pair case .reject(let value): value.pair+ case .pairCorrection(let value): value.pair+ case .pairCorrectionAcknowledgement(let value): value.pair case .retire(let value): value.pair default: nil }@@ -161,6 +255,17 @@ public struct AssociationValidationReceipt: Sendable, Equatable, Hashable, Codab public var recordBarrierDigest: String public var decisionDigest: String public var evidence: [AssociationEvidence]+ public var groupSupport: AssociationGroupSupport?+ public init(pair: AssociationPair, sourceFingerprint: String, matchingFingerprint: String,+ sourceBarrierDigest: String, recordBarrierDigest: String, decisionDigest: String,+ evidence: [AssociationEvidence], groupSupport: AssociationGroupSupport? = nil) {+ self.pair = pair; self.sourceFingerprint = sourceFingerprint+ self.matchingFingerprint = matchingFingerprint+ self.sourceBarrierDigest = sourceBarrierDigest+ self.recordBarrierDigest = recordBarrierDigest+ self.decisionDigest = decisionDigest; self.evidence = evidence+ self.groupSupport = groupSupport+ } } public struct AssociationLedgerEvent: Sendable, Equatable, Codable {@@ -209,11 +314,14 @@ public struct AssociationLedgerInventory: Sendable { private var acceptances: [UUID: AssociationAcceptance] = [:] private var rootsByPair: [AssociationPair: Set<UUID>] = [:] private var rejectionsByPair: [AssociationPair: [(UUID, AssociationRejection)]] = [:]+ private var pairCorrectionsByPair: [AssociationPair: [(UUID, AssociationPairCorrection)]] = [:]+ private var pairCorrectionAcknowledgements: [UUID: Set<UUID>] = [:] 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]] = [:]+ public private(set) var groupSuggestionSkips: Set<GroupSuggestionSkip> = [] private var barrierDigests: [AssociationScope: String] = [:] private var decisionsByEntry: [UUID: Set<UUID>] = [:] private var consumed: Set<UUID> = []@@ -237,6 +345,11 @@ public struct AssociationLedgerInventory: Sendable { guard !visiting.contains(id), let core = acceptances[id], !core.spellingKeys.isEmpty, core.spellingKeys.allSatisfy({ !$0.isEmpty && RecordNameKey.normalize($0) == $0 }) else { return false }+ if let support = core.support {+ guard core.spellingKeys == [support.spellingKey] else { return false }+ if case .group(_, _, let transitionIDs) = support,+ transitionIDs.isEmpty { return false }+ } var next = visiting; next.insert(id) for rejectionID in core.reconsideredRejectionIDs { guard let event = events[rejectionID], case .reject(let rejection) = event.payload,@@ -306,6 +419,25 @@ public struct AssociationLedgerInventory: Sendable { } rejectionsByPair[rejection.pair, default: []].append((id, rejection)) decisionsByEntry[rejection.pair.entryID, default: []].insert(id)+ case .pairCorrection(let correction):+ guard !correction.supports.isEmpty, correction.supports.allSatisfy({ key in+ switch key {+ case .direct(let spelling): !spelling.isEmpty && RecordNameKey.normalize(spelling) == spelling+ case .group(_, let spelling): !spelling.isEmpty && RecordNameKey.normalize(spelling) == spelling+ }+ }) else { invalidIDs.insert(id); continue }+ pairCorrectionsByPair[correction.pair, default: []].append((id, correction))+ decisionsByEntry[correction.pair.entryID, default: []].insert(id)+ case .pairCorrectionAcknowledgement(let acknowledgement):+ guard !acknowledgement.correctionIDs.isEmpty,+ acknowledgement.correctionIDs.allSatisfy({ correctionID in+ guard let event = events[correctionID], case .pairCorrection(let correction) = event.payload else { return false }+ return correction.pair == acknowledgement.pair+ }) else { invalidIDs.insert(id); continue }+ for correctionID in acknowledgement.correctionIDs {+ pairCorrectionAcknowledgements[correctionID, default: []].insert(id)+ }+ decisionsByEntry[acknowledgement.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@@ -322,6 +454,14 @@ public struct AssociationLedgerInventory: Sendable { if case .entry = scope {} else { barriersByWork[scope.workID, default: []].insert(id) } case .coverage(let coverage): coverageByEntry[coverage.entryID, default: []].append(coverage)+ case .groupSuggestionSkip(let skip):+ guard skip.groupKey == RecordNameKey.normalize(skip.groupKey),+ !skip.groupKey.isEmpty, !skip.evidenceKey.isEmpty,+ (skip.kind == .create && skip.characterKey == nil ||+ (skip.kind == .join || skip.kind == .leave) && skip.characterKey.map {+ !$0.isEmpty && $0 == RecordNameKey.normalize($0)+ } == true) else { invalidIDs.insert(id); continue }+ groupSuggestionSkips.insert(skip) default: break } }@@ -339,11 +479,27 @@ public struct AssociationLedgerInventory: Sendable { public func acceptance(_ id: UUID) -> AssociationAcceptance? { invalidIDs.contains(id) ? nil : acceptances[id] }+ /// Historical group reconciliation must see roots whose support just+ /// disappeared; `activeAcceptanceIDs` correctly hides those from readers.+ func unretiredAcceptanceIDs(for pair: AssociationPair) -> Set<UUID> {+ rootsByPair[pair, default: []].subtracting(invalidIDs)+ .subtracting(retired).subtracting(consumed)+ } 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 isPairSupportSuppressed(pair: AssociationPair, support: AssociationPairSupportKey) -> Bool {+ pairCorrectionsByPair[pair, default: []].contains { id, correction in+ correction.supports.contains(support) && (pairCorrectionAcknowledgements[id]?.isEmpty ?? true)+ }+ }+ public func pairCorrectionIDs(pair: AssociationPair) -> [UUID] {+ AssociationDigest.ordered(pairCorrectionsByPair[pair, default: []].compactMap { id, _ in+ pairCorrectionAcknowledgements[id]?.isEmpty == false ? nil : id+ })+ } 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@@ -373,18 +529,80 @@ public struct AssociationLedgerInventory: Sendable { decisionDigest: AssociationDigest.of("association/decisions/v1", AssociationDigest.pairToken(current.pair) + AssociationDigest.ordered(decisions).map(\.uuidString)), evidence: evidence) }+ public func receipt(for current: AssociationCurrentPair,+ groupSupport: AssociationGroupSupport) -> AssociationValidationReceipt {+ var value = receipt(for: current)+ value.evidence = isSuppressed(pair: current.pair, spellingKey: groupSupport.spellingKey)+ ? [] : [.init(key: groupSupport.spellingKey, spelling: groupSupport.spelling)]+ value.groupSupport = groupSupport+ let relevant = rejectionIDs(pair: current.pair,+ spellingKeys: [groupSupport.spellingKey])+ let decisions = relevant + relevant.flatMap { rejectionID in+ Array(acknowledgements[rejectionID]?[groupSupport.spellingKey] ?? [])+ }+ value.decisionDigest = AssociationDigest.of("association/group-decisions/v22",+ AssociationDigest.pairToken(current.pair) + [groupSupport.groupID.uuidString,+ groupSupport.spellingKey]+ + groupSupport.transitionEventIDs.map(\.uuidString)+ + AssociationDigest.ordered(decisions).map(\.uuidString))+ return value+ } 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> {+ activeAcceptanceIDs(for: current, groupSupports: current.groupSupports)+ }+ private func directActiveAcceptanceIDs(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)+ isDirectRoot($0, evidence: expected.evidence) &&+ !invalidIDs.contains($0) && !retired.contains($0) && !consumed.contains($0)+ && !supportIsRemoved($0, pair: current.pair) && receipts[$0, default: []].contains(expected) } }+ private func supportIsRemoved(_ id: UUID, pair: AssociationPair) -> Bool {+ switch acceptances[id]?.support {+ case .some(.direct(let key)):+ return isPairSupportSuppressed(pair: pair, support: .direct(spellingKey: key))+ case .some(.group(let groupID, let key, _)):+ return isPairSupportSuppressed(pair: pair, support: .group(groupID: groupID, spellingKey: key))+ case nil:+ guard let keys = acceptances[id]?.spellingKeys, !keys.isEmpty else { return false }+ return keys.allSatisfy { isPairSupportSuppressed(pair: pair, support: .direct(spellingKey: $0)) }+ }+ }+ private func isDirectRoot(_ id: UUID, evidence: [AssociationEvidence]) -> Bool {+ switch acceptances[id]?.support {+ case nil: return true // V21's unchanged whole direct receipt path.+ case .some(.direct(let key)): return evidence.contains { $0.key == key }+ case .some(.group): return false+ }+ }+ public func activeAcceptanceIDs(for current: AssociationCurrentPair,+ groupSupports: [AssociationGroupSupport]) -> Set<UUID> {+ var active = directActiveAcceptanceIDs(for: current)+ for support in groupSupports where support.version == 22 &&+ !support.spellingKey.isEmpty &&+ RecordNameKey.normalize(support.spellingKey) == support.spellingKey &&+ !support.spelling.isEmpty && !support.transitionEventIDs.isEmpty {+ let expected = receipt(for: current, groupSupport: support)+ guard !expected.evidence.isEmpty else { continue }+ for id in rootsByPair[current.pair, default: []] where+ !invalidIDs.contains(id) && !retired.contains(id) && !consumed.contains(id) {+ guard case .group(let groupID, let key, let transitionIDs) = acceptances[id]?.support,+ groupID == support.groupID, key == support.spellingKey,+ !isPairSupportSuppressed(pair: current.pair, support: .group(groupID: groupID, spellingKey: key)),+ AssociationDigest.ordered(transitionIDs) == support.transitionEventIDs,+ receipts[id, default: []].contains(expected) else { continue }+ active.insert(id)+ }+ }+ return active+ } public var spellingDecisions: [AssociationPair: [String: AssociationSpellingDecision]] { var result: [AssociationPair: [String: AssociationSpellingDecision]] = [:] for (pair, rejections) in rejectionsByPair {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swiftindex f73d58cf..c7301285 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swift@@ -1,10 +1,10 @@ import Foundation import SwiftData -public typealias AssociationEvent = AsterismSchemaV21.AssociationEvent-public typealias PairNoteVersion = AsterismSchemaV21.PairNoteVersion+public typealias AssociationEvent = AsterismSchemaV22.AssociationEvent+public typealias PairNoteVersion = AsterismSchemaV22.PairNoteVersion -extension AsterismSchemaV21 {+extension AsterismSchemaV22 { @Model public final class AssociationEvent { #Index<AssociationEvent>([\.id], [\.workID], [\.entryID], [\.recordID]) public var id: UUID = UUID()@@ -28,6 +28,7 @@ extension AsterismSchemaV21 { case .coverage(let coverage): entryID = coverage.entryID case .pendingReview(let marker): entryID = marker.entryID case .reviewAcknowledgement(let acknowledgement): entryID = acknowledgement.entryID+ case .groupSuggestionSkip(let skip): entryID = skip.chapterID default: break } eventData = try JSONBlob.encode(event.payload)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationMutation.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationMutation.swiftindex 7f58d651..066ea177 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AssociationMutation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationMutation.swift@@ -105,10 +105,11 @@ struct AssociationMutation { let oldIDs = active[path.source] else { continue } let current = after.current(final) let historicalKeys = Array(Set(oldIDs.compactMap { storage.ledger.acceptance($0) }.flatMap(\.spellingKeys)))+ let currentKeys = current?.evidence.map(\.key) ?? [] 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,+ spellingKeys: currentKeys.isEmpty ? historicalKeys : currentKeys, rebind: .init(operation: operation, predecessorIDs: predecessors)))) stages.append(event); events.append(event); predecessors = [event.id] }@@ -146,25 +147,48 @@ struct AssociationMutation { 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+ let directReceipt = ledger.receipt(for: current)+ let beforeCurrent = endpoints.current(pair)+ let directMentionLost = lostSupportedMention(from: pair, to: pair,+ after: after, ledger: ledger)+ var unsupported: Set<UUID> = []+ for id in ids {+ let support = storage.ledger.acceptance(id)?.support+ let receipt: AssociationValidationReceipt+ let beforeReceipt: AssociationValidationReceipt?+ switch support {+ case .some(.group(let groupID, let key, let transitionIDs)):+ guard let group = current.groupSupports.first(where: {+ $0.groupID == groupID && $0.spellingKey == key &&+ $0.transitionEventIDs == AssociationDigest.ordered(transitionIDs)+ }) else { unsupported.insert(id); continue }+ receipt = ledger.receipt(for: current, groupSupport: group)+ beforeReceipt = beforeCurrent?.groupSupports.first(where: {+ $0.groupID == groupID && $0.spellingKey == key &&+ $0.transitionEventIDs == AssociationDigest.ordered(transitionIDs)+ }).map { storage.ledger.receipt(for: beforeCurrent!, groupSupport: $0) }+ case .some(.direct(let key)):+ guard !directMentionLost,+ directReceipt.evidence.contains(where: { $0.key == key }) else {+ unsupported.insert(id); continue }+ receipt = directReceipt+ beforeReceipt = beforeCurrent.map { storage.ledger.receipt(for: $0) }+ case nil:+ guard !directMentionLost else { unsupported.insert(id); continue }+ receipt = directReceipt+ beforeReceipt = beforeCurrent.map { storage.ledger.receipt(for: $0) }+ }+ guard !receipt.evidence.isEmpty else { unsupported.insert(id); continue }+ guard receipt != beforeReceipt else { continue }+ let bytes = try JSONBlob.encode(receipt)+ for row in rowsByID[id, default: []]+ where row.validationData != bytes && row.ledgerValue?.validation == beforeReceipt {+ row.validationData = bytes } }+ try retire(pair: pair, ids: unsupported, context: context, timestamp: timestamp) } else if definitelyRemoved(pair, after: after, changedEntries: changedEntries, changedRecords: changedRecords) { try retire(pair: pair, ids: ids, context: context, timestamp: timestamp) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationRawRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationRawRecords.swiftindex aa5301d9..81fcba93 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AssociationRawRecords.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationRawRecords.swift@@ -71,6 +71,7 @@ public struct AssociationRawEvent: Sendable, Equatable, Codable { case .coverage(let coverage): expectedEntry = coverage.entryID case .pendingReview(let marker): expectedEntry = marker.entryID case .reviewAcknowledgement(let acknowledgement): expectedEntry = acknowledgement.entryID+ case .groupSuggestionSkip(let skip): expectedEntry = skip.chapterID default: break } guard workID == payload.workID, entryID == expectedEntry,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationSnapshots.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationSnapshots.swiftindex df7a52af..e57a6cf5 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AssociationSnapshots.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationSnapshots.swift@@ -86,12 +86,15 @@ public struct ChapterAssociationSnapshot: Sendable, Equatable, Identifiable { public var validationReceipt: AssociationValidationReceipt? public var noteHeads: [AssociationNoteValue] public var rawNotes: [AssociationRawNote]+ public var removalCorrectionIDs: [UUID]+ public var isRemoved: Bool { activeAcceptanceIDs.isEmpty && !removalCorrectionIDs.isEmpty } public init(pair: AssociationPair, recordName: String, chapterTitle: String, evidence: [AssociationEvidence], activeAcceptanceIDs: Set<UUID>, validationReceipt: AssociationValidationReceipt?, noteHeads: [AssociationNoteValue] = [],- rawNotes: [AssociationRawNote] = []) {+ rawNotes: [AssociationRawNote] = [], removalCorrectionIDs: [UUID] = []) { self.pair = pair; self.recordName = recordName; self.chapterTitle = chapterTitle self.evidence = evidence; self.activeAcceptanceIDs = activeAcceptanceIDs self.validationReceipt = validationReceipt; self.noteHeads = noteHeads; self.rawNotes = rawNotes+ self.removalCorrectionIDs = removalCorrectionIDs } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationStorage.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationStorage.swiftindex 2d45bcfc..44827811 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AssociationStorage.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationStorage.swift@@ -92,6 +92,7 @@ struct AssociationStorageInventory { requiredEvents.formUnion(core.rebind?.predecessorIDs ?? []) case .retire(let retirement): requiredEvents.formUnion(retirement.acceptanceIDs) case .reviewAcknowledgement(let acknowledgement): requiredEvents.formUnion(acknowledgement.references.map(\.markerID))+ case .pairCorrectionAcknowledgement(let acknowledgement): requiredEvents.formUnion(acknowledgement.correctionIDs) default: break } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21AssociationModels.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21AssociationModels.swiftnew file mode 100644index 00000000..321dc0b1--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21AssociationModels.swift@@ -0,0 +1,59 @@+import Foundation+import SwiftData++/// Frozen V21 association storage shape.+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+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21Models.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21Models.swiftnew file mode 100644index 00000000..6208619d--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21Models.swift@@ -0,0 +1,290 @@+import Foundation+import SwiftData++/// Frozen V21 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 AsterismSchemaV21 {++@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() {}+}+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV22.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV22.swiftnew file mode 100644index 00000000..5246dd64--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV22.swift@@ -0,0 +1,110 @@+import Foundation+import SwiftData++/// Live V22 adds named character groups and their authored event history.+public enum AsterismSchemaV22: VersionedSchema {+ public static let versionIdentifier = Schema.Version(22, 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, CharacterGroup.self,+ GroupFactEvent.self, GroupTransition.self]+ }+}++public enum AsterismV22MigrationPlan: SchemaMigrationPlan {+ public static var schemas: [any VersionedSchema.Type] {+ [AsterismSchemaV16.self, AsterismSchemaV17.self, AsterismSchemaV18.self,+ AsterismSchemaV19.self, AsterismSchemaV20.self, AsterismSchemaV21.self,+ AsterismSchemaV22.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),+ .lightweight(fromVersion: AsterismSchemaV21.self, toVersion: AsterismSchemaV22.self)]+ }+}++extension AsterismSchemaV22 {+ @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; createdAt = timestamp; modifiedAt = timestamp+ self.evidenceData = evidenceData+ }+ }++ @Model public final class CharacterGroup {+ #Index<CharacterGroup>([\.id], [\.workID])+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public init(id: UUID = UUID(), workID: UUID) {+ self.id = id; self.workID = workID+ }+ }++ @Model public final class GroupFactEvent {+ #Index<GroupFactEvent>([\.id], [\.workID], [\.groupID])+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var groupID: UUID = UUID()+ public var payloadData: Data = Data()+ public var parentHeadIDsData: Data = Data()+ public var recordedAt: Date = Date(timeIntervalSince1970: 0)+ public init(id: UUID = UUID(), workID: UUID, groupID: UUID,+ payloadData: Data, parentHeadIDsData: Data, recordedAt: Date) {+ self.id = id; self.workID = workID; self.groupID = groupID+ self.payloadData = payloadData; self.parentHeadIDsData = parentHeadIDsData+ self.recordedAt = recordedAt+ }+ }++ @Model public final class GroupTransition {+ #Index<GroupTransition>([\.id], [\.workID], [\.groupID], [\.characterID], [\.entryID])+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var groupID: UUID = UUID()+ public var characterID: UUID = UUID()+ public var entryID: UUID = UUID()+ public var payloadData: Data = Data()+ public var parentHeadIDsData: Data = Data()+ public var recordedAt: Date = Date(timeIntervalSince1970: 0)+ public init(id: UUID = UUID(), workID: UUID, groupID: UUID,+ characterID: UUID, entryID: UUID, payloadData: Data,+ parentHeadIDsData: Data, recordedAt: Date) {+ self.id = id; self.workID = workID; self.groupID = groupID+ self.characterID = characterID; self.entryID = entryID+ self.payloadData = payloadData; self.parentHeadIDsData = parentHeadIDsData+ self.recordedAt = recordedAt+ }+ }+}++public typealias NamedCharacterGroup = AsterismSchemaV22.CharacterGroup+public typealias GroupFactEvent = AsterismSchemaV22.GroupFactEvent+public typealias GroupTransition = AsterismSchemaV22.GroupTransition
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swiftindex 0ea7a301..4dc9f4d4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift@@ -16,6 +16,9 @@ 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 groups: [GroupRawIdentity]+ public let groupFacts: [GroupRawFact]+ public let groupTransitions: [GroupRawTransition] public let associationEvents: [AssociationRawEvent] public let pairNoteVersions: [AssociationRawNote] public let chapterEntries: [UUID: BackupV19Entry]@@ -62,8 +65,13 @@ public struct BackupImportPayload: Sendable, Equatable { chapterEntries: [UUID: BackupV19Entry] = [:], workCaptureDefaults: [UUID: ChapterCaptureDefault] = [:], entrySources: [BackupV19EntrySource] = [],- associationEvents: [AssociationRawEvent] = [], pairNoteVersions: [AssociationRawNote] = []+ associationEvents: [AssociationRawEvent] = [], pairNoteVersions: [AssociationRawNote] = [],+ groups: [GroupRawIdentity] = [], groupFacts: [GroupRawFact] = [],+ groupTransitions: [GroupRawTransition] = [] ) {+ self.groups = groups+ self.groupFacts = groupFacts+ self.groupTransitions = groupTransitions self.associationEvents = associationEvents self.pairNoteVersions = pairNoteVersions self.chapterEntries = chapterEntries@@ -131,6 +139,25 @@ public struct BackupImportPayload: Sendable, Equatable { self.init(payload.library, associationEvents: payload.associationEvents, pairNoteVersions: payload.pairNoteVersions) }+ public init(_ payload: BackupV21Payload) {+ self.init(entries: payload.library.entries.map(\.predecessorRecord),+ works: payload.library.works.map(\.predecessorRecord),+ sites: payload.library.sites, titlePatterns: payload.library.titlePatterns,+ urlRules: payload.library.urlRules, workTypes: payload.library.workTypes,+ memberships: payload.library.memberships, distinctPairs: payload.library.distinctPairs,+ characters: payload.library.characters, suppressions: payload.library.suppressions,+ places: payload.library.places, placeSuppressions: payload.library.placeSuppressions,+ series: payload.library.series, links: payload.library.links,+ creators: payload.library.creators, creatorRoles: payload.library.creatorRoles,+ credits: payload.library.credits, noEpisodeActions: payload.library.noEpisodeActions,+ chapterEntries: Dictionary(uniqueKeysWithValues: payload.library.entries.map { ($0.id, $0) }),+ workCaptureDefaults: Dictionary(uniqueKeysWithValues: payload.library.works.map { ($0.id, $0.chapterCaptureDefault) }),+ entrySources: payload.library.entrySources,+ associationEvents: payload.predecessor.associationEvents,+ pairNoteVersions: payload.predecessor.pairNoteVersions,+ groups: payload.groups, groupFacts: payload.groupFacts,+ groupTransitions: payload.groupTransitions)+ } /// Whether any record carries a character-extraction coverage fingerprint. /// The 6/7 payload had a coverage array to test for emptiness; every@@ -289,7 +316,7 @@ public enum BackupImporter { /// constants, so the accepted pair moves with the generation rather than /// being restated here. private static let supportedVersions = (- format: BackupV20Document.formatVersion, schema: BackupV20Document.schemaVersion+ format: BackupV21Document.formatVersion, schema: BackupV21Document.schemaVersion ) // MARK: - Plan Dispatch (Req 5.1, 5.2, Decision 2)@@ -302,7 +329,7 @@ public enum BackupImporter { let (formatVersion, schemaVersion) = try detectVersions(data) logger.debug("Detected format=\(formatVersion) schema=\(schemaVersion)") - guard (formatVersion, schemaVersion) == supportedVersions || (formatVersion, schemaVersion) == (19, 20) || (formatVersion, schemaVersion) == (18, 19) else {+ guard (formatVersion, schemaVersion) == supportedVersions || (formatVersion, schemaVersion) == (20, 21) || (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.@@ -320,8 +347,8 @@ public enum BackupImporter { } private static func planFromArchive(_ data: Data) throws -> BackupImportPlan {- let compatible: CompatibleBackupV20Document- do { compatible = try BackupV20Codec.decodeCompatible(data) }+ let compatible: CompatibleBackupV21Document+ do { compatible = try BackupV21Codec.decodeCompatible(data) } catch { throw BackupImportError.decodingFailed(reason: String(describing: error)) } let payload: BackupImportPayload let metadata: BackupImportMetadata@@ -348,6 +375,12 @@ public enum BackupImporter { schemaVersion: document.databaseSchemaVersion, appBuild: document.appBuild, exportedAt: document.exportedAt, capabilityGate: document.capabilityGate, entryCount: document.entryCount, workCount: document.workCount)+ case .oldest(let document):+ 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/BackupV21Codec.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV21Codec.swiftnew file mode 100644index 00000000..1b1c0732--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV21Codec.swift@@ -0,0 +1,161 @@+import Foundation++/// Current archive codec; released predecessor codecs remain frozen.+public enum BackupV21Codec {+ /// Pinned literally. 21/22 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 = "V21"++ // 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 `BackupV21Document.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: BackupV21Payload,+ 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: BackupV21Document.formatVersion,+ capabilityGate: Self.gate,+ checksum: checksum,+ databaseSchemaVersion: BackupV21Document.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++ /// Exact21/22 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 -> BackupV21Document {+ do {+ let rootKeys = try DuplicateJSONKeyValidator.validate(data)+ try BackupArchiveShapeValidator.validate(rootKeys: rootKeys)++ let document = try BackupCanonicalJSON.decoder()+ .decode(BackupV21Document.self, from: data)++ guard document.backupFormatVersion == BackupV21Document.formatVersion else {+ throw BackupCodecError.invalidFormatVersion(document.backupFormatVersion)+ }+ guard document.databaseSchemaVersion == BackupV21Document.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 CompatibleBackupV21Document: Sendable {+ case current(BackupV21Document)+ case predecessor(BackupV20Document)+ case legacy(BackupV19Document)+ case oldest(BackupV18Document)+ public var payload: BackupV21Payload {+ switch self {+ case .current(let document): document.payload+ case .predecessor(let document): .init(predecessor: document.payload)+ case .legacy(let document): .init(predecessor: .init(library: document.payload))+ case .oldest(let document): .init(predecessor: .init(library: .init(predecessor: document.payload)))+ }+ }+}++extension BackupV21Codec {+ public static func decodeCompatible(_ data: Data) throws -> CompatibleBackupV21Document {+ 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 (21, 22): return .current(try decode(data))+ case (20, 21): return .predecessor(try BackupV20Codec.decode(data))+ case (19, 20): return .legacy(try BackupV19Codec.decode(data))+ case (18, 19): return .oldest(try BackupV18Codec.decode(data))+ default: throw BackupCodecError.invalidFormatVersion(versions.backupFormatVersion)+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV21Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV21Exporter.swiftnew file mode 100644index 00000000..55e349ba--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV21Exporter.swift@@ -0,0 +1,110 @@+import Foundation+import SwiftData++public protocol BackupV21SnapshotProviding: Sendable {+ func backupV21Snapshot() async throws -> BackupV21Payload+}++extension LibraryRepository: BackupV21SnapshotProviding {+ public func backupV21Snapshot() async throws -> BackupV21Payload {+ let outcome: Result<BackupV21Payload, 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]) }+ let groups = try context.fetch(FetchDescriptor<NamedCharacterGroup>())+ .map(GroupRawIdentity.init).sorted { [$0.id.uuidString, $0.workID.uuidString]+ .lexicographicallyPrecedes([$1.id.uuidString, $1.workID.uuidString]) }+ let facts = try context.fetch(FetchDescriptor<GroupFactEvent>())+ .map(GroupRawFact.init).sorted { [$0.id.uuidString, $0.groupID.uuidString,+ $0.payloadData.base64EncodedString()].lexicographicallyPrecedes(+ [$1.id.uuidString, $1.groupID.uuidString, $1.payloadData.base64EncodedString()]) }+ let transitions = try context.fetch(FetchDescriptor<GroupTransition>())+ .map(GroupRawTransition.init).sorted { [$0.id.uuidString, $0.groupID.uuidString,+ $0.payloadData.base64EncodedString()].lexicographicallyPrecedes(+ [$1.id.uuidString, $1.groupID.uuidString, $1.payloadData.base64EncodedString()]) }+ return .success(.init(predecessor: .init(library: base,+ associationEvents: events, pairNoteVersions: notes), groups: groups,+ groupFacts: facts, groupTransitions: transitions))+ } catch let error as BackupV18ExportError { return .failure(error) }+ }+ return try outcome.get()+ }+}++public final class BackupV21Exporter: Sendable {+ private let repository: any BackupV21SnapshotProviding+ private let stagingDirectory: URL++ public init(+ repository: any BackupV21SnapshotProviding,+ stagingDirectory: URL+ ) {+ self.repository = repository+ self.stagingDirectory = stagingDirectory+ }++ public func export(metadata: BackupV21Metadata) async throws -> BackupExportResult {+ let payload: BackupV21Payload+ do {+ payload = try await repository.backupV21Snapshot()+ } catch let error as BackupV18ExportError {+ throw error+ } catch {+ throw BackupV18ExportError.snapshotFailed(reason: String(describing: error))+ }++ let encoded: Data+ do {+ encoded = try BackupV21Codec.encode(payload: payload, metadata: metadata)+ } catch {+ throw BackupV18ExportError.encodingFailed(reason: String(describing: error))+ }++ do {+ let decoded = try BackupV21Codec.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\(BackupV21Document.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)+ }+}+
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV21Types.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV21Types.swiftnew file mode 100644index 00000000..5b72ec94--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV21Types.swift@@ -0,0 +1,72 @@+import Foundation++// Archive21/schema22 adds raw group identity and causal event arrays while+// retaining released library and association record shapes.++public struct BackupV21Document: Codable, Equatable, Sendable {+ public static let formatVersion = 21+ public static let schemaVersion = 22++ 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: BackupV21Payload++ public init(+ appBuild: String,+ exportedAt: Date,+ capabilityGate: String,+ entryCount: Int,+ workCount: Int,+ checksum: String,+ payload: BackupV21Payload+ ) {+ 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 BackupV21Metadata = BackupV19Metadata++/// Composition in memory keeps every released predecessor shape unchanged.+/// The new raw arrays share the existing flat payload object on the wire.+public struct BackupV21Payload: Codable, Equatable, Sendable {+ public var predecessor: BackupV20Payload+ public var groups: [GroupRawIdentity]+ public var groupFacts: [GroupRawFact]+ public var groupTransitions: [GroupRawTransition]+ public var library: BackupV19Payload { predecessor.library }+ public init(predecessor: BackupV20Payload, groups: [GroupRawIdentity] = [],+ groupFacts: [GroupRawFact] = [], groupTransitions: [GroupRawTransition] = []) {+ self.predecessor = predecessor; self.groups = groups+ self.groupFacts = groupFacts; self.groupTransitions = groupTransitions+ }+ private enum CodingKeys: String, CodingKey { case groups, groupFacts, groupTransitions }+ public init(from decoder: any Decoder) throws {+ predecessor = try BackupV20Payload(from: decoder)+ let container = try decoder.container(keyedBy: CodingKeys.self)+ groups = try container.decode([GroupRawIdentity].self, forKey: .groups)+ groupFacts = try container.decode([GroupRawFact].self, forKey: .groupFacts)+ groupTransitions = try container.decode([GroupRawTransition].self, forKey: .groupTransitions)+ }+ public func encode(to encoder: any Encoder) throws {+ try predecessor.encode(to: encoder)+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(groups, forKey: .groups)+ try container.encode(groupFacts, forKey: .groupFacts)+ try container.encode(groupTransitions, forKey: .groupTransitions)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CharacterExtractionTypes.swift b/Packages/AsterismCore/Sources/AsterismCore/CharacterExtractionTypes.swiftindex 1bb78e72..c011b762 100644--- a/Packages/AsterismCore/Sources/AsterismCore/CharacterExtractionTypes.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/CharacterExtractionTypes.swift@@ -38,10 +38,12 @@ public struct CharacterExtractionSource: Sendable, Equatable { public let capturedAt: Date? public let isChapter: Bool public let stableOrder: Int+ public let knownGroupNames: [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) {+ displayTitle: String = "", capturedAt: Date? = nil, isChapter: Bool = false,+ stableOrder: Int = 0, knownGroupNames: [String] = []) { self.ref = ref self.text = text self.fingerprint = fingerprint@@ -50,6 +52,7 @@ public struct CharacterExtractionSource: Sendable, Equatable { self.coveredMentionEligibilityDigest = coveredMentionEligibilityDigest self.displayTitle = displayTitle; self.capturedAt = capturedAt self.isChapter = isChapter; self.stableOrder = stableOrder+ self.knownGroupNames = Array(Set(knownGroupNames)).sorted() } /// Coverage is per revision: editing the note *is* the invalidation.@@ -133,6 +136,9 @@ public struct ExtractionCandidate: Sendable, Equatable { public let acceptedFacts: [RecordKind: Set<RecordFactIdentity>] public let suppressions: [RecordKind: SuppressionIndex] public let mentionIndex: AssociationMentionIndex+ /// Normalized names and aliases of groups in this Work, from the same+ /// coherent candidate read as records and notes.+ public let knownGroupNames: [String] public init( workID: UUID,@@ -142,7 +148,8 @@ public struct ExtractionCandidate: Sendable, Equatable { records: [RecordKind: [MatchTarget]], acceptedFacts: [RecordKind: Set<RecordFactIdentity>], suppressions: [RecordKind: SuppressionIndex],- mentionIndex: AssociationMentionIndex = .empty+ mentionIndex: AssociationMentionIndex = .empty,+ knownGroupNames: [String] = [] ) { self.workID = workID self.displayTitle = displayTitle@@ -152,6 +159,7 @@ public struct ExtractionCandidate: Sendable, Equatable { self.acceptedFacts = acceptedFacts self.suppressions = suppressions self.mentionIndex = mentionIndex+ self.knownGroupNames = Array(Set(knownGroupNames)).sorted() } public func records(of kind: RecordKind) -> [MatchTarget] { records[kind] ?? [] }@@ -164,6 +172,10 @@ public struct ExtractionCandidate: Sendable, Equatable { suppressions[kind] ?? .empty } + public var knownGroupNameKeys: Set<String> {+ Set(knownGroupNames.map(RecordNameKey.normalize).filter { !$0.isEmpty })+ }+ public var uncoveredSources: [CharacterExtractionSource] { sources.filter { !$0.isCovered } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupConflictJourneyFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupConflictJourneyFixture.swiftnew file mode 100644index 00000000..3e5cbd31--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupConflictJourneyFixture.swift@@ -0,0 +1,33 @@+#if DEBUG+import Foundation+import SwiftData++extension LibraryRepository {+ /// A simulator-only concurrent delivery fixture for the ordinary group+ /// editor journey. It leaves the root intact and inserts two coherent+ /// sibling heads, which public single-device commands cannot produce.+ public func seedConflictedGroupTransitionForUITest(workID: UUID,+ rootID: UUID) async throws {+ try await withLockedContext(mode: .exclusive,+ operation: "seeding a group transition conflict for UI tests") { context in+ let rows = try context.fetch(FetchDescriptor<GroupTransition>(+ predicate: #Predicate { $0.id == rootID }))+ guard rows.count == 1, let root = rows.first?.transitionValue,+ root.workID == workID, root.rootID == rootID,+ root.action == .join else {+ throw LibraryRepositoryError.invalidInput(+ operation: "seeding a group transition conflict for UI tests",+ reason: "the expected join root is unavailable")+ }+ for action in [GroupTransitionAction.join, .leave] {+ context.insert(try GroupTransition(fact: .init(rootID: rootID,+ workID: workID, groupID: root.groupID,+ characterID: root.characterID, chapterID: root.chapterID,+ parentHeadIDs: [rootID], action: action),+ recordedAt: Date()))+ }+ try context.save()+ }+ }+}+#endif
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupImportPreparation.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupImportPreparation.swiftnew file mode 100644index 00000000..ec3521bf--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupImportPreparation.swift@@ -0,0 +1,24 @@+import SwiftData++/// Imports exact immutable physical variants. The roster fold, not the import+/// parser, judges coherence after Works, characters and chapters have arrived.+enum GroupImportPreparation {+ static func insertMissing(_ payload: BackupImportPayload,+ context: ModelContext) throws {+ var existingGroups = Set(try context.fetch(FetchDescriptor<NamedCharacterGroup>())+ .map(GroupRawIdentity.init))+ var existingFacts = Set(try context.fetch(FetchDescriptor<GroupFactEvent>())+ .map(GroupRawFact.init))+ var existingTransitions = Set(try context.fetch(FetchDescriptor<GroupTransition>())+ .map(GroupRawTransition.init))+ for raw in payload.groups where existingGroups.insert(raw).inserted {+ context.insert(NamedCharacterGroup(raw: raw))+ }+ for raw in payload.groupFacts where existingFacts.insert(raw).inserted {+ context.insert(GroupFactEvent(raw: raw))+ }+ for raw in payload.groupTransitions where existingTransitions.insert(raw).inserted {+ context.insert(GroupTransition(raw: raw))+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupRawRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupRawRecords.swiftnew file mode 100644index 00000000..a7f89477--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupRawRecords.swift@@ -0,0 +1,64 @@+import Foundation++/// Archive values keep whole physical variants, including malformed event+/// payloads. A later coherent copy can resolve a torn imported ID; decoding an+/// archive must never silently discard one of the reader's authored variants.+public struct GroupRawIdentity: Codable, Hashable, Sendable {+ public let id: UUID+ public let workID: UUID+ public init(_ row: NamedCharacterGroup) {+ id = row.id; workID = row.workID+ }+}++public struct GroupRawFact: Codable, Hashable, Sendable {+ public let id: UUID+ public let workID: UUID+ public let groupID: UUID+ public let payloadData: Data+ public let parentHeadIDsData: Data+ public let recordedAtBits: UInt64+ public init(_ row: GroupFactEvent) {+ id = row.id; workID = row.workID; groupID = row.groupID+ payloadData = row.payloadData; parentHeadIDsData = row.parentHeadIDsData+ recordedAtBits = row.recordedAt.timeIntervalSinceReferenceDate.bitPattern+ }+}++public struct GroupRawTransition: Codable, Hashable, Sendable {+ public let id: UUID+ public let workID: UUID+ public let groupID: UUID+ public let characterID: UUID+ public let entryID: UUID+ public let payloadData: Data+ public let parentHeadIDsData: Data+ public let recordedAtBits: UInt64+ public init(_ row: GroupTransition) {+ id = row.id; workID = row.workID; groupID = row.groupID+ characterID = row.characterID; entryID = row.entryID+ payloadData = row.payloadData; parentHeadIDsData = row.parentHeadIDsData+ recordedAtBits = row.recordedAt.timeIntervalSinceReferenceDate.bitPattern+ }+}++extension NamedCharacterGroup {+ convenience init(raw: GroupRawIdentity) { self.init(id: raw.id, workID: raw.workID) }+}++extension GroupFactEvent {+ convenience init(raw: GroupRawFact) {+ self.init(id: raw.id, workID: raw.workID, groupID: raw.groupID,+ payloadData: raw.payloadData, parentHeadIDsData: raw.parentHeadIDsData,+ recordedAt: Date(timeIntervalSinceReferenceDate: Double(bitPattern: raw.recordedAtBits)))+ }+}++extension GroupTransition {+ convenience init(raw: GroupRawTransition) {+ self.init(id: raw.id, workID: raw.workID, groupID: raw.groupID,+ characterID: raw.characterID, entryID: raw.entryID,+ payloadData: raw.payloadData, parentHeadIDsData: raw.parentHeadIDsData,+ recordedAt: Date(timeIntervalSinceReferenceDate: Double(bitPattern: raw.recordedAtBits)))+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupRecordMutation.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupRecordMutation.swiftnew file mode 100644index 00000000..ef8fd92a--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupRecordMutation.swift@@ -0,0 +1,37 @@+import Foundation+import SwiftData++/// Record delete/combine keeps immutable transition ancestry. Physically torn+/// roots remain withheld; coherent concurrent heads move together or retain+/// their explicit resolution choice on the surviving character.+enum GroupRecordMutation {+ static func advance(workID: UUID, from characterID: UUID,+ to survivorID: UUID?, context: ModelContext,+ recordedAt: Date, groupID: UUID? = nil) throws {+ let copies = try GroupSupportInventory.transitionRows(workID: workID, context: context)+ guard !copies.isEmpty else { return }+ for (rootID, state) in GroupTransitionRebind.states(rows: copies) {+ guard case .live(let heads) = state, let first = heads.first,+ heads.allSatisfy({ $0.workID == workID &&+ $0.groupID == first.groupID && $0.characterID == characterID }),+ groupID == nil || first.groupID == groupID else { continue }+ if survivorID == nil || GroupTransitionRebind.sameValue(heads) {+ let successor = GroupTransitionFact(rootID: rootID, workID: workID,+ groupID: first.groupID, characterID: survivorID ?? characterID,+ chapterID: first.chapterID, parentHeadIDs: heads.map(\.id),+ action: survivorID == nil ? .remove : first.action)+ context.insert(try GroupTransition(fact: successor,+ recordedAt: recordedAt))+ } else if let survivorID {+ for head in heads {+ let successor = GroupTransitionFact(rootID: rootID, workID: workID,+ groupID: head.groupID, characterID: survivorID,+ chapterID: head.chapterID, parentHeadIDs: [head.id],+ action: head.action)+ context.insert(try GroupTransition(fact: successor,+ recordedAt: recordedAt))+ }+ }+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupReferenceResolver.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupReferenceResolver.swiftnew file mode 100644index 00000000..4f3fb36a--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupReferenceResolver.swift@@ -0,0 +1,130 @@+import Foundation++public enum GroupMentionKind: String, Sendable, Codable {+ case character, place, group+}++public struct GroupNameClaim: Sendable, Equatable {+ public let kind: GroupMentionKind+ public let id: UUID+ public let spelling: String+ public init(kind: GroupMentionKind, id: UUID, spelling: String) {+ self.kind = kind; self.id = id; self.spelling = spelling+ }+}++public struct GroupResolvedMention: Sendable, Equatable {+ public let kind: GroupMentionKind+ public let id: UUID+ public let spellingKey: String+ public let spelling: String+ public let utf16Offset: Int+ public let utf16Length: Int+}++public struct GroupReferenceSupport: Sendable, Equatable {+ public let groupID: UUID+ public let spellingKey: String+ public let spelling: String+ public let members: Set<UUID>+ public let transitionEventIDsByMember: [UUID: [UUID]]+}++public struct GroupReferenceResolution: Sendable {+ public let mentions: [GroupResolvedMention]+ public let characterIDs: Set<UUID>+ public let groupSupports: [GroupReferenceSupport]+ public func associationSupports(for characterID: UUID) -> [AssociationGroupSupport] {+ groupSupports.compactMap { support in+ guard support.members.contains(characterID),+ let transitionIDs = support.transitionEventIDsByMember[characterID],+ !transitionIDs.isEmpty else { return nil }+ return AssociationGroupSupport(groupID: support.groupID,+ spellingKey: support.spellingKey, spelling: support.spelling,+ transitionEventIDs: transitionIDs)+ }+ }+}++/// A single matcher for every name kind; a group spelling cannot silently be+/// treated as a character spelling when the two overlap in saved prose.+public enum GroupReferenceResolver {+ private struct Candidate: Equatable {+ let claim: GroupNameClaim+ let range: Range<String.Index>+ let offset: Int+ let length: Int+ let sourceSpelling: String+ var identity: String { "\(claim.kind.rawValue)/\(claim.id.uuidString)" }+ func overlaps(_ other: Candidate) -> Bool {+ range.lowerBound < other.range.upperBound && other.range.lowerBound < range.upperBound+ }+ }++ public static func resolve(note: String, chapterID: UUID?, claims: [GroupNameClaim],+ roster: GroupProjection) -> GroupReferenceResolution {+ let liveGroupIDs = Set(roster.groups.map(\.groupID))+ var spans: [Candidate] = []+ for claim in claims where claim.kind != .group || liveGroupIDs.contains(claim.id) {+ for range in RecordMentionGrounding.completeNameSpans(name: claim.spelling, in: note) {+ let sourceSpelling = String(note[range])+ spans.append(Candidate(claim: claim, range: range,+ offset: note.utf16.distance(from: note.startIndex, to: range.lowerBound),+ length: note.utf16.distance(from: range.lowerBound, to: range.upperBound),+ sourceSpelling: sourceSpelling))+ }+ }+ let distinct = Dictionary(grouping: spans, by: {+ "\($0.identity)/\($0.offset)/\($0.length)/\($0.sourceSpelling)"+ }).values.compactMap(\.first)+ let ordered = distinct.sorted {+ if $0.length != $1.length { return $0.length > $1.length }+ if $0.offset != $1.offset { return $0.offset < $1.offset }+ return $0.identity < $1.identity+ }+ var chosen: [Candidate] = []+ var disputedSpans: [Candidate] = []+ for candidate in ordered {+ if chosen.contains(where: { $0.overlaps(candidate) }) ||+ disputedSpans.contains(where: { $0.overlaps(candidate) }) { continue }+ // An equally complete claim of a different identity (including a+ // different kind) is unresolved; neither gets an inferred link.+ if ordered.contains(where: {+ $0.identity != candidate.identity && $0.length == candidate.length &&+ $0.overlaps(candidate)+ }) {+ disputedSpans.append(candidate)+ continue+ }+ chosen.append(candidate)+ }+ chosen.sort { $0.offset < $1.offset }+ let mentions = chosen.map {+ GroupResolvedMention(kind: $0.claim.kind, id: $0.claim.id,+ spellingKey: RecordNameKey.normalize($0.claim.spelling),+ spelling: $0.sourceSpelling, utf16Offset: $0.offset,+ utf16Length: $0.length)+ }+ var characterIDs = Set(mentions.filter { $0.kind == .character }.map(\.id))+ let supports = mentions.filter { $0.kind == .group }.map { mention in+ // Generic Work notes have no chapter anchor: their group spelling+ // still arbitrates spans, but cannot imply any chapter membership.+ let members = chapterID.map { roster.members(groupID: mention.id,+ chapterID: $0) } ?? []+ characterIDs.formUnion(members)+ let transitionIDs: [UUID: [UUID]]+ if let chapterID {+ transitionIDs = Dictionary(uniqueKeysWithValues: members.map {+ ($0, roster.transitionEventIDs(groupID: mention.id,+ characterID: $0, chapterID: chapterID))+ })+ } else { transitionIDs = [:] }+ return GroupReferenceSupport(groupID: mention.id,+ spellingKey: mention.spellingKey, spelling: mention.spelling,+ members: members,+ transitionEventIDsByMember: transitionIDs)+ }+ return GroupReferenceResolution(mentions: mentions, characterIDs: characterIDs,+ groupSupports: supports)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupRoster.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupRoster.swiftnew file mode 100644index 00000000..634df54a--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupRoster.swift@@ -0,0 +1,442 @@+import Foundation++/// A chapter in the Work's already established presentation order. The roster+/// does not infer order from UUIDs, timestamps, titles, or physical row order.+public struct GroupChapter: Sendable, Equatable {+ public let id: UUID+ public let label: String+ public init(id: UUID, label: String) { self.id = id; self.label = label }+}++public enum GroupFactOperation: Codable, Equatable, Sendable {+ case create(name: String)+ case setName(String)+ case addAlias(String)+ case removeAlias(String)+ case delete+}++public struct GroupFact: Codable, Equatable, Sendable {+ public let id: UUID+ public let groupID: UUID+ public let workID: UUID+ public let parentHeadIDs: [UUID]+ public let operation: GroupFactOperation+ public init(id: UUID = UUID(), groupID: UUID, workID: UUID,+ parentHeadIDs: [UUID] = [], operation: GroupFactOperation) {+ self.id = id; self.groupID = groupID; self.workID = workID+ self.parentHeadIDs = parentHeadIDs; self.operation = operation+ }+}++public enum GroupTransitionAction: String, Codable, Sendable, Hashable {+ case join, leave, remove+}++/// A correction names the same root as the original and observes its current+/// heads. The old event remains untouched for late CloudKit delivery.+public struct GroupTransitionFact: Codable, Equatable, Sendable {+ public let id: UUID+ public let rootID: UUID+ public let workID: UUID+ public let groupID: UUID+ public let characterID: UUID+ public let chapterID: UUID+ public let parentHeadIDs: [UUID]+ public let action: GroupTransitionAction+ public init(id: UUID = UUID(), rootID: UUID, workID: UUID, groupID: UUID,+ characterID: UUID, chapterID: UUID, parentHeadIDs: [UUID] = [],+ action: GroupTransitionAction) {+ self.id = id; self.rootID = rootID; self.workID = workID+ self.groupID = groupID; self.characterID = characterID; self.chapterID = chapterID+ self.parentHeadIDs = parentHeadIDs; self.action = action+ }+}++public struct MembershipRange: Equatable, Sendable {+ public let startChapterID: UUID+ public let endChapterID: UUID?+ public let startLabel: String+ public let endLabel: String?+ public init(start: GroupChapter, end: GroupChapter?) {+ startChapterID = start.id; endChapterID = end?.id+ startLabel = start.label; endLabel = end?.label+ }+}++public struct GroupSummary: Equatable, Sendable {+ public let groupID: UUID+ public let name: String?+ public let aliases: [String]+ public let members: [UUID: [MembershipRange]]+ public let factEventIDs: [UUID]+ public let transitions: [GroupTransitionFact]+ /// Compatible concurrent heads remain withheld from the roster until the+ /// reader chooses one replacement chapter and action against this basis.+ public let conflictedTransitions: [GroupTransitionConflict]+ public let transitionEventIDs: [UUID: [UUID]]+ public init(groupID: UUID, name: String?, aliases: [String] = [],+ members: [UUID: [MembershipRange]] = [:], factEventIDs: [UUID] = [],+ transitions: [GroupTransitionFact] = [],+ conflictedTransitions: [GroupTransitionConflict] = [],+ transitionEventIDs: [UUID: [UUID]] = [:]) {+ self.groupID = groupID; self.name = name; self.aliases = aliases+ self.members = members; self.factEventIDs = factEventIDs; self.transitions = transitions+ self.conflictedTransitions = conflictedTransitions+ self.transitionEventIDs = transitionEventIDs+ }+}++public struct GroupTransitionConflict: Equatable, Sendable, Identifiable {+ public var id: UUID { rootID }+ public let rootID: UUID+ public let groupID: UUID+ public let characterID: UUID+ public let heads: [GroupTransitionFact]+ /// All current-Work event IDs, including observed ancestors, form the+ /// existing compare-and-swap basis for an explicit resolution event.+ public let expectedEventIDs: [UUID]+ public init(rootID: UUID, groupID: UUID, characterID: UUID,+ heads: [GroupTransitionFact], expectedEventIDs: [UUID]) {+ self.rootID = rootID; self.groupID = groupID+ self.characterID = characterID; self.heads = heads+ self.expectedEventIDs = expectedEventIDs+ }+}++public struct CharacterGroupMembership: Equatable, Sendable {+ public let groupID: UUID+ public let groupName: String?+ public let ranges: [MembershipRange]+}++private struct GroupMemberAddress: Hashable {+ let workID: UUID+ let groupID: UUID+ let characterID: UUID+ init(_ event: GroupTransitionFact) {+ workID = event.workID; groupID = event.groupID+ characterID = event.characterID+ }+}++public struct GroupProjection: Sendable {+ public let groups: [GroupSummary]+ private let chapterIndices: [UUID: Int]+ let transitionIDs: [UUID: [UUID: [UUID]]]+ let unresolvedSpellings: [UUID: Set<String>]+ let disputedMembers: [UUID: Set<UUID>]++ init(groups: [GroupSummary], chapters: [GroupChapter],+ transitionIDs: [UUID: [UUID: [UUID]]] = [:],+ unresolvedSpellings: [UUID: Set<String>] = [:],+ disputedMembers: [UUID: Set<UUID>] = [:]) {+ self.groups = groups+ chapterIndices = GroupRoster.chapterIndices(chapters)+ self.transitionIDs = transitionIDs+ self.unresolvedSpellings = unresolvedSpellings+ self.disputedMembers = disputedMembers+ }++ public func ranges(groupID: UUID, characterID: UUID) -> [MembershipRange] {+ groups.first { $0.groupID == groupID }?.members[characterID] ?? []+ }++ public func members(groupID: UUID, chapterID: UUID) -> Set<UUID> {+ guard let index = chapterIndices[chapterID],+ let group = groups.first(where: { $0.groupID == groupID }) else { return [] }+ return Set(group.members.compactMap { characterID, ranges in+ contains(ranges, at: index) ? characterID : nil+ })+ }++ private func contains(_ ranges: [MembershipRange], at index: Int) -> Bool {+ ranges.contains { range in+ guard let start = chapterIndices[range.startChapterID], start <= index else { return false }+ return range.endChapterID.flatMap { chapterIndices[$0] }.map { $0 >= index } ?? true+ }+ }++ /// True when a character had an accepted membership interval that ended+ /// before this chapter. Repeated explicit leaves may extend that boundary.+ public func hasMembershipBefore(groupID: UUID, characterID: UUID,+ chapterID: UUID) -> Bool {+ guard let index = chapterIndices[chapterID],+ let ranges = groups.first(where: { $0.groupID == groupID })?.members[characterID]+ else { return false }+ return ranges.contains { range in+ guard let start = chapterIndices[range.startChapterID], start < index,+ let end = range.endChapterID.flatMap({ chapterIndices[$0] }) else { return false }+ return end < index+ }+ }++ public func groupsForCharacter(_ characterID: UUID) -> [CharacterGroupMembership] {+ groups.compactMap { group in+ guard let ranges = group.members[characterID], !ranges.isEmpty else { return nil }+ return CharacterGroupMembership(groupID: group.groupID, groupName: group.name, ranges: ranges)+ }+ }++ public func transitionEventIDs(groupID: UUID, characterID: UUID,+ chapterID: UUID) -> [UUID] {+ guard let index = chapterIndices[chapterID],+ let ranges = groups.first(where: { $0.groupID == groupID })?.members[characterID],+ contains(ranges, at: index) else { return [] }+ return transitionIDs[groupID]?[characterID] ?? []+ }+}++public enum GroupRoster {+ public static func project(workID: UUID, chapters: [GroupChapter], facts: [GroupFact],+ transitions: [GroupTransitionFact]) -> GroupProjection {+ let chapterIndices = chapterIndices(chapters)+ // Keep historical parents from a merged Work available when validating+ // immutable successor events in this Work.+ let validFacts = uniqueFacts(facts)+ let factByID = Dictionary(uniqueKeysWithValues: validFacts.map { ($0.id, $0) })+ let validTransitions = uniqueTransitions(transitions)+ let transitionByID = Dictionary(uniqueKeysWithValues: validTransitions.map { ($0.id, $0) })+ var acceptedTransitions: [GroupTransitionFact] = []+ var conflictedTransitions: [GroupTransitionConflict] = []+ var disputedMembers: Set<GroupMemberAddress> = []+ // Resolve each root over every destination before projecting one Work.+ // Filtering by destination first turns two incompatible successors into+ // two falsely unique heads. A remove tombstones its root permanently.+ for (rootID, chain) in Dictionary(grouping: validTransitions, by: \.rootID) {+ guard let root = transitionByID[rootID], root.rootID == root.id else { continue }+ let completeChain = chain.filter { complete($0.id, in: transitionByID,+ parents: { $0.parentHeadIDs }) &&+ ($0.id == rootID || hasAncestor($0.id, ancestor: rootID,+ in: transitionByID, parents: { $0.parentHeadIDs })) }+ if completeChain.contains(where: { $0.action == .remove }) { continue }+ let liveHeads = heads(completeChain, all: completeChain,+ parents: { $0.parentHeadIDs })+ guard let value = liveHeads.min(by: { $0.id.uuidString < $1.id.uuidString }) else {+ continue+ }+ guard liveHeads.allSatisfy({+ $0.workID == value.workID && $0.groupID == value.groupID &&+ $0.characterID == value.characterID && $0.chapterID == value.chapterID &&+ $0.action == value.action+ }) else {+ disputedMembers.formUnion(completeChain.map(GroupMemberAddress.init))+ let current = chain.filter { $0.workID == workID }+ if let first = liveHeads.first, !current.isEmpty,+ liveHeads.allSatisfy({ $0.workID == workID &&+ $0.groupID == first.groupID && $0.characterID == first.characterID }),+ current.allSatisfy({ complete($0.id, in: transitionByID,+ parents: { $0.parentHeadIDs }) &&+ ($0.id == rootID || hasAncestor($0.id, ancestor: rootID,+ in: transitionByID, parents: { $0.parentHeadIDs })) }) {+ conflictedTransitions.append(.init(rootID: rootID,+ groupID: first.groupID, characterID: first.characterID,+ heads: liveHeads.sorted { $0.id.uuidString < $1.id.uuidString },+ expectedEventIDs: current.map(\.id).sorted {+ $0.uuidString < $1.uuidString+ }))+ }+ continue+ }+ acceptedTransitions.append(value)+ }++ let groupIDs = Set(validFacts.compactMap { fact -> UUID? in+ if fact.workID == workID, case .create = fact.operation { return fact.groupID }+ return nil+ })+ var transitionIDs: [UUID: [UUID: [UUID]]] = [:]+ var unresolvedSpellings: [UUID: Set<String>] = [:]+ let summaries = groupIDs.sorted { $0.uuidString < $1.uuidString }.compactMap { groupID -> GroupSummary? in+ let events = validFacts.filter { $0.groupID == groupID && $0.workID == workID &&+ complete($0.id, in: factByID,+ parents: { $0.parentHeadIDs }) }+ guard events.contains(where: { if case .create = $0.operation { return true }; return false }),+ !events.contains(where: { if case .delete = $0.operation { return true }; return false })+ else { return nil }++ let names = events.filter {+ switch $0.operation {+ case .create, .setName: return true+ default: return false+ }+ }+ let nameHeads = heads(names, all: events, parents: { $0.parentHeadIDs })+ let nameValues = Set(nameHeads.compactMap { event -> String? in+ switch event.operation { case .create(let name), .setName(let name): name; default: nil }+ })+ if nameValues.count > 1 {+ unresolvedSpellings[groupID, default: []].formUnion(+ nameValues.map(RecordNameKey.normalize))+ }+ let name = nameValues.count == 1 ? nameValues.first : nil+ let aliasesByKey = Dictionary(grouping: events.compactMap { event -> (String, GroupFact)? in+ switch event.operation {+ case .addAlias(let alias), .removeAlias(let alias):+ return (alias.folding(options: [.caseInsensitive, .diacriticInsensitive],+ locale: Locale(identifier: "en_US_POSIX")), event)+ default: return nil+ }+ }, by: { $0.0 })+ let aliases = aliasesByKey.values.compactMap { values -> String? in+ let relevant = values.map(\.1)+ let remaining = heads(relevant, all: events, parents: { $0.parentHeadIDs })+ if remaining.contains(where: { if case .addAlias = $0.operation { return true }; return false }) &&+ remaining.contains(where: { if case .removeAlias = $0.operation { return true }; return false }) {+ unresolvedSpellings[groupID, default: []].insert(+ RecordNameKey.normalize(values[0].0))+ }+ guard !remaining.isEmpty, remaining.allSatisfy({+ if case .addAlias = $0.operation { return true }; return false+ }) else { return nil }+ return remaining.compactMap { event -> String? in+ if case .addAlias(let value) = event.operation { return value }+ return nil+ }.sorted().first+ }.sorted()++ var memberRanges: [UUID: [MembershipRange]] = [:]+ let accepted = acceptedTransitions.filter {+ $0.groupID == groupID && $0.workID == workID+ }+ for (characterID, claims) in Dictionary(grouping: accepted, by: \.characterID) {+ if disputedMembers.contains(.init(claims[0])) { continue }+ // An accepted leave with an unavailable chapter cannot be+ // discarded: that would make an earlier join open ended and+ // invent later membership until the chapter hydrates.+ guard claims.allSatisfy({ chapterIndices[$0.chapterID] != nil }) else {+ disputedMembers.formUnion(claims.map(GroupMemberAddress.init))+ continue+ }+ let ordered = claims.sorted {+ let left = chapterIndices[$0.chapterID]!, right = chapterIndices[$1.chapterID]!+ if left != right { return left < right }+ if $0.action != $1.action { return $0.action == .join }+ return $0.id.uuidString < $1.id.uuidString+ }+ var intervals: [(start: Int, end: Int?)] = []+ for claim in ordered {+ let index = chapterIndices[claim.chapterID]!+ switch claim.action {+ case .join:+ if intervals.last?.end != nil || intervals.isEmpty {+ intervals.append((index, nil))+ }+ case .leave:+ if !intervals.isEmpty {+ intervals[intervals.count - 1].end = index+ }+ case .remove: break+ }+ }+ memberRanges[characterID] = intervals.map { interval in+ MembershipRange(start: chapters[interval.start],+ end: interval.end.map { chapters[$0] })+ }+ if !intervals.isEmpty {+ transitionIDs[groupID, default: [:]][characterID] = claims.map(\.id)+ .sorted { $0.uuidString < $1.uuidString }+ }+ }+ return GroupSummary(groupID: groupID, name: name, aliases: aliases, members: memberRanges,+ factEventIDs: validFacts.filter { $0.groupID == groupID }.map(\.id),+ transitions: acceptedTransitions.filter { $0.groupID == groupID },+ conflictedTransitions: conflictedTransitions.filter { $0.groupID == groupID }+ .sorted { $0.rootID.uuidString < $1.rootID.uuidString },+ transitionEventIDs: Dictionary(grouping: validTransitions.filter { $0.groupID == groupID }, by: \.rootID).mapValues { $0.map(\.id) })+ }+ let publishedIDs = Set(summaries.map(\.groupID))+ let disputedByGroup = Dictionary(grouping: disputedMembers.filter {+ $0.workID == workID && publishedIDs.contains($0.groupID)+ }, by: \.groupID).mapValues { Set($0.map(\.characterID)) }+ return GroupProjection(groups: summaries, chapters: chapters,+ transitionIDs: transitionIDs,+ unresolvedSpellings: unresolvedSpellings,+ disputedMembers: disputedByGroup)+ }++ private static func uniqueFacts(_ facts: [GroupFact]) -> [GroupFact] {+ Dictionary(grouping: facts, by: \.id).values.compactMap { copies in+ copies.allSatisfy { $0 == copies[0] } ? copies[0] : nil+ }+ }+ static func chapterIndices(_ chapters: [GroupChapter]) -> [UUID: Int] {+ var indices: [UUID: Int] = [:]+ var ambiguous: Set<UUID> = []+ for (index, chapter) in chapters.enumerated() {+ if indices.updateValue(index, forKey: chapter.id) != nil {+ ambiguous.insert(chapter.id)+ }+ }+ for id in ambiguous { indices.removeValue(forKey: id) }+ return indices+ }+ private static func uniqueTransitions(_ transitions: [GroupTransitionFact]) -> [GroupTransitionFact] {+ Dictionary(grouping: transitions, by: \.id).values.compactMap { copies in+ copies.allSatisfy { $0 == copies[0] } ? copies[0] : nil+ }+ }+ static func complete<Value>(_ id: UUID, in values: [UUID: Value],+ parents: (Value) -> [UUID]) -> Bool {+ var visiting: Set<UUID> = []+ var visited: Set<UUID> = []+ func visit(_ key: UUID) -> Bool {+ guard let value = values[key] else { return false }+ if visited.contains(key) { return true }+ guard visiting.insert(key).inserted else { return false }+ for parent in parents(value) where !visit(parent) { return false }+ visiting.remove(key); visited.insert(key)+ return true+ }+ return visit(id)+ }+ static func hasAncestor<Value>(_ id: UUID, ancestor: UUID,+ in values: [UUID: Value],+ parents: (Value) -> [UUID]) -> Bool {+ var visited: Set<UUID> = []+ func search(_ key: UUID) -> Bool {+ guard visited.insert(key).inserted, let value = values[key] else { return false }+ if parents(value).contains(ancestor) { return true }+ return parents(value).contains(where: search)+ }+ return search(id)+ }+ private static func heads<Value: Identifiable>(_ subset: [Value], all: [Value],+ parents: (Value) -> [UUID]) -> [Value]+ where Value.ID == UUID {+ let byID = Dictionary(uniqueKeysWithValues: all.map { ($0.id, $0) })+ func descends(_ child: UUID, from ancestor: UUID, seen: inout Set<UUID>) -> Bool {+ guard seen.insert(child).inserted, let value = byID[child] else { return false }+ if parents(value).contains(ancestor) { return true }+ return parents(value).contains { descends($0, from: ancestor, seen: &seen) }+ }+ return subset.filter { candidate in+ !subset.contains { other in+ var seen: Set<UUID> = []+ return other.id != candidate.id && descends(other.id, from: candidate.id, seen: &seen)+ }+ }+ }+}++extension GroupFact: Identifiable {}+extension GroupTransitionFact: Identifiable {}++/// Shared visual and spoken range disclosure for both app and extension.+public enum GroupMembershipText {+ public static func range(_ range: MembershipRange) -> String {+ "\(range.startLabel)–\(range.endLabel ?? "")"+ }+ public static func ranges(_ ranges: [MembershipRange]) -> String {+ ranges.map(range).joined(separator: ", ")+ }+ public static func membership(name: String, ranges values: [MembershipRange]) -> String {+ "\(name) (\(ranges(values)))"+ }+ public static func character(_ id: UUID, groups: [GroupSummary]) -> [String] {+ groups.compactMap { group in+ guard let ranges = group.members[id], !ranges.isEmpty else { return nil }+ return membership(name: group.name ?? "Unresolved group", ranges: ranges)+ }.sorted()+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupRosterStorage.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupRosterStorage.swiftnew file mode 100644index 00000000..9adbc87b--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupRosterStorage.swift@@ -0,0 +1,131 @@+import Foundation++extension GroupFactEvent {+ public convenience init(fact: GroupFact, recordedAt: Date) throws {+ self.init(id: fact.id, workID: fact.workID, groupID: fact.groupID,+ payloadData: try JSONBlob.encode(fact.operation),+ parentHeadIDsData: try JSONBlob.encode(fact.parentHeadIDs.sorted {+ $0.uuidString < $1.uuidString+ }), recordedAt: recordedAt)+ }++ public var factValue: GroupFact? {+ guard let operation = try? JSONBlob.decode(GroupFactOperation.self, from: payloadData),+ let parents = try? JSONBlob.decode([UUID].self, from: parentHeadIDsData) else {+ return nil+ }+ return GroupFact(id: id, groupID: groupID, workID: workID,+ parentHeadIDs: parents, operation: operation)+ }+}++extension GroupTransition {+ public convenience init(fact: GroupTransitionFact, recordedAt: Date) throws {+ self.init(id: fact.id, workID: fact.workID, groupID: fact.groupID,+ characterID: fact.characterID, entryID: fact.chapterID,+ payloadData: try JSONBlob.encode(GroupTransitionStoragePayload(+ rootID: fact.rootID, action: fact.action)),+ parentHeadIDsData: try JSONBlob.encode(fact.parentHeadIDs.sorted {+ $0.uuidString < $1.uuidString+ }), recordedAt: recordedAt)+ }++ public var transitionValue: GroupTransitionFact? {+ guard let payload = try? JSONBlob.decode(GroupTransitionStoragePayload.self, from: payloadData),+ let parents = try? JSONBlob.decode([UUID].self, from: parentHeadIDsData) else {+ return nil+ }+ return GroupTransitionFact(id: id, rootID: payload.rootID, workID: workID,+ groupID: groupID, characterID: characterID,+ chapterID: entryID, parentHeadIDs: parents,+ action: payload.action)+ }+}++private struct GroupTransitionStoragePayload: Codable {+ let rootID: UUID+ let action: GroupTransitionAction+}++extension GroupRoster {+ /// Preserve disputed physical rows but withhold their claims. A corrupt twin+ /// must not allow a valid copy with the same authored ID to take effect.+ public static func project(workID: UUID, chapters: [GroupChapter],+ groupRows: [NamedCharacterGroup],+ factRows: [GroupFactEvent],+ transitionRows: [GroupTransition]) -> GroupProjection {+ let groups = Dictionary(grouping: groupRows, by: \.id).compactMap { id, rows -> UUID? in+ rows.allSatisfy { $0.workID == workID } ? id : nil+ }+ let groupIDs = Set(groups)+ let facts = Dictionary(grouping: factRows, by: \.id).values.compactMap { rows -> GroupFact? in+ guard let first = rows.first,+ rows.allSatisfy({ $0.workID == first.workID && $0.groupID == first.groupID &&+ $0.payloadData == first.payloadData &&+ $0.parentHeadIDsData == first.parentHeadIDsData &&+ $0.recordedAt == first.recordedAt }) else { return nil }+ return first.factValue+ }+ var quarantinedMembers: [UUID: Set<UUID>] = [:]+ var disputedRoots: Set<UUID> = []+ var disputedIDs: Set<UUID> = []+ let transitions = Dictionary(grouping: transitionRows, by: \.id).values.compactMap {+ rows -> GroupTransitionFact? in+ guard let first = rows.first else { return nil }+ let coherent =+ rows.allSatisfy({ $0.workID == first.workID && $0.groupID == first.groupID &&+ $0.characterID == first.characterID && $0.entryID == first.entryID &&+ $0.payloadData == first.payloadData &&+ $0.parentHeadIDsData == first.parentHeadIDsData &&+ $0.recordedAt == first.recordedAt })+ guard coherent, let value = first.transitionValue else {+ // Dropping only a disputed leave could leave an independent+ // join open. A source-Work twin can dispute a merged root even+ // when none of its raw addresses belongs to this Work.+ disputedIDs.insert(first.id)+ disputedRoots.formUnion(rows.compactMap { $0.transitionValue?.rootID })+ for row in rows where row.workID == workID {+ quarantinedMembers[row.groupID, default: []].insert(row.characterID)+ }+ return nil+ }+ return value+ }+ for value in transitions where value.workID == workID &&+ (disputedRoots.contains(value.rootID) || disputedIDs.contains(value.rootID)) {+ quarantinedMembers[value.groupID, default: []].insert(value.characterID)+ }+ let projected = project(workID: workID, chapters: chapters,+ facts: facts, transitions: transitions)+ let summaries = projected.groups.filter { groupIDs.contains($0.groupID) }.map { group in+ GroupSummary(groupID: group.groupID, name: group.name, aliases: group.aliases,+ members: group.members.filter {+ !quarantinedMembers[group.groupID, default: []].contains($0.key)+ },+ // Editors compare against the IDs physically selected by this+ // Work's locked transaction. Ancestor rows from a merged source+ // participate in the fold but are not part of that snapshot.+ factEventIDs: facts.filter { $0.workID == workID && $0.groupID == group.groupID }+ .map(\.id).sorted { $0.uuidString < $1.uuidString },+ transitions: group.transitions,+ conflictedTransitions: group.conflictedTransitions.filter {+ !quarantinedMembers[group.groupID, default: []].contains($0.characterID)+ },+ transitionEventIDs: Dictionary(grouping: transitions+ .filter { $0.workID == workID && $0.groupID == group.groupID }, by: \.rootID)+ .mapValues { $0.map(\.id).sorted { $0.uuidString < $1.uuidString } })+ }+ let publishedIDs = Set(summaries.map(\.groupID))+ var disputedMembers = projected.disputedMembers.filter {+ publishedIDs.contains($0.key)+ }+ for group in summaries {+ disputedMembers[group.groupID, default: []].formUnion(+ quarantinedMembers[group.groupID, default: []])+ }+ return GroupProjection(groups: summaries,+ chapters: chapters, transitionIDs: projected.transitionIDs,+ unresolvedSpellings: projected.unresolvedSpellings,+ disputedMembers: disputedMembers)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupSupportInventory.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupSupportInventory.swiftnew file mode 100644index 00000000..83c000b7--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupSupportInventory.swift@@ -0,0 +1,212 @@+import Foundation+import SwiftData++/// Reads only the changed Work's chapters and group events. The same chapter+/// order feeds both the visible ranges and Save-time membership decisions.+enum GroupSupportInventory {+ /// V22 stores rootID in the payload, not an indexed column. One physical+ /// inventory finds foreign successors delivered after a Work merge as well+ /// as named ancestors. Keep every copy of a selected event ID so the roster+ /// can quarantine conflicting or undecodable twins.+ struct TransitionInventory {+ private let byID: [UUID: [GroupTransition]]+ private let byWorkID: [UUID: [GroupTransition]]+ private let idsByRoot: [UUID: Set<UUID>]++ init(rows: [GroupTransition]) {+ byID = Dictionary(grouping: rows, by: \.id)+ byWorkID = Dictionary(grouping: rows, by: \.workID)+ var roots: [UUID: Set<UUID>] = [:]+ for row in rows {+ if let rootID = row.transitionValue?.rootID {+ roots[rootID, default: []].insert(row.id)+ }+ }+ idsByRoot = roots+ }++ func rows(workID: UUID) -> [GroupTransition] {+ var pending = Set((byWorkID[workID] ?? []).map(\.id))+ var known: Set<UUID> = []+ var result: [GroupTransition] = []+ while let id = pending.popFirst() {+ guard known.insert(id).inserted else { continue }+ let copies = byID[id] ?? []+ result += copies+ for row in copies {+ guard let value = row.transitionValue else { continue }+ pending.insert(value.rootID)+ pending.formUnion(value.parentHeadIDs)+ pending.formUnion(idsByRoot[value.rootID] ?? [])+ }+ pending.subtract(known)+ }+ return result+ }+ }++ static func transitionRows(workID: UUID, context: ModelContext) throws -> [GroupTransition] {+ let rows = try context.fetch(FetchDescriptor<GroupTransition>())+ return TransitionInventory(rows: rows).rows(workID: workID)+ }+ // Direct-name identity is elected by RecordMatching after cross-kind span+ // arbitration. Claiming one record UUID here would prematurely refuse a+ // stronger same-kind tier before that election runs.+ static let characterClaimID = UUID(uuidString: "00000000-0000-0000-0000-000000000001")!+ static let placeClaimID = UUID(uuidString: "00000000-0000-0000-0000-000000000002")!++ static func chapterRows(work: WorkGroup, context: ModelContext) throws -> [WorkChapterRow] {+ let entries = Array(Dictionary(grouping: work.rows.flatMap { $0.entries ?? [] }, by: \.id).values+ .compactMap { rows -> EntrySnapshot? in+ guard let group = LibraryRepository.entryGroups(rows, canonicalWorkIDs: [:]).values.first,+ !group.isTorn else { return nil }+ return try? LibraryRepository.snapshot(group)+ })+ let chapters = entries.filter { $0.authoredTarget?.kind == .chapter || $0.authoredTarget == nil }+ return try LibraryRepository.workChapterRows(chapters, context: context)+ }+ static func chapters(work: WorkGroup, context: ModelContext) throws -> [GroupChapter] {+ WorkChapterRow.inChapterOrder(try chapterRows(work: work, context: context))+ .map { GroupChapter(id: $0.id, label: $0.displayTitle) }+ }+ /// Expand only the selected Work's fact IDs and their named causal parents.+ /// The edit path needs the same ancestry as the read projection after a+ /// Work merge; neither path may silently omit a contradictory physical twin.+ static func factRows(selected: [GroupFactEvent], context: ModelContext) throws -> [GroupFactEvent] {+ let factIDs = Array(Set(selected.map(\.id)))+ var rows = factIDs.isEmpty ? [] : try context.fetch(FetchDescriptor<GroupFactEvent>(+ predicate: #Predicate { factIDs.contains($0.id) }))+ var known = Set(rows.map(\.id))+ var pending = Set(rows.flatMap { $0.factValue?.parentHeadIDs ?? [] })+ .subtracting(known)+ while !pending.isEmpty {+ let ids = Array(pending); pending = []+ let ancestors = try context.fetch(FetchDescriptor<GroupFactEvent>(+ predicate: #Predicate { ids.contains($0.id) }))+ rows += ancestors+ known.formUnion(ancestors.map(\.id))+ pending = Set(ancestors.flatMap { $0.factValue?.parentHeadIDs ?? [] })+ .subtracting(known)+ }+ return rows+ }+ /// The history pass already has every physical fact row. Use that same+ /// bounded parent closure without another fetch per Work or ancestor.+ static func factRows(selected: [GroupFactEvent], allRows: [GroupFactEvent]) -> [GroupFactEvent] {+ let byID = Dictionary(grouping: allRows, by: \.id)+ var pending = Set(selected.map(\.id))+ var known: Set<UUID> = []+ var result: [GroupFactEvent] = []+ while let id = pending.popFirst() {+ guard known.insert(id).inserted else { continue }+ let copies = byID[id] ?? []+ result += copies+ for row in copies {+ pending.formUnion(row.factValue?.parentHeadIDs ?? [])+ }+ pending.subtract(known)+ }+ return result+ }+ static func projection(work: WorkGroup, context: ModelContext,+ chapters override: [GroupChapter]? = nil,+ transitionInventory: TransitionInventory? = nil) throws -> GroupProjection {+ let workID = work.id+ let selectedGroups = try context.fetch(FetchDescriptor<NamedCharacterGroup>(+ predicate: #Predicate { $0.workID == workID }))+ guard !selectedGroups.isEmpty else {+ return GroupRoster.project(workID: workID, chapters: [], groupRows: [],+ factRows: [], transitionRows: [])+ }+ let selectedFacts = try context.fetch(FetchDescriptor<GroupFactEvent>(+ predicate: #Predicate { $0.workID == workID }))+ // Application UUIDs are not unique in CloudKit. Once the Work has+ // selected relevant IDs, expand each to every physical copy, including+ // a contradictory copy claiming another Work. The roster fold must see+ // those twins to quarantine rather than publish one convenient row.+ let groupIDs = Array(Set(selectedGroups.map(\.id)))+ let groupRows = try context.fetch(FetchDescriptor<NamedCharacterGroup>(+ predicate: #Predicate { groupIDs.contains($0.id) }))+ let factRows = try Self.factRows(selected: selectedFacts, context: context)+ let transitionRows: [GroupTransition]+ if let transitionInventory {+ transitionRows = transitionInventory.rows(workID: workID)+ } else {+ transitionRows = try Self.transitionRows(workID: workID, context: context)+ }+ return GroupRoster.project(workID: workID,+ chapters: try override ?? chapters(work: work, context: context),+ groupRows: groupRows, factRows: factRows, transitionRows: transitionRows)+ }++ static func supports(pairs: Set<AssociationPair>,+ sources: [UUID: AssociationEndpointInventory.Source],+ context: ModelContext,+ chapterSpines: [UUID: [GroupChapter]] = [:],+ projectedTargets: [AssociationRecordAddress: AssociationEndpointInventory.Target]? = nil) throws -> [AssociationPair: [AssociationGroupSupport]] {+ var result: [AssociationPair: [AssociationGroupSupport]] = [:]+ let workIDs = Array(Set(pairs.map(\.workID)))+ guard !workIDs.isEmpty else { return result }+ let works = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { workIDs.contains($0.id) }))+ let workGroups = LibraryRepository.workGroups(works,+ types: try LibraryRepository.workTypeDirectory(context: context))+ let transitionInventory = TransitionInventory(rows:+ try context.fetch(FetchDescriptor<GroupTransition>()))+ for (workID, group) in workGroups where !group.isTorn {+ let projection = try projection(work: group, context: context,+ chapters: chapterSpines[workID],+ transitionInventory: transitionInventory)+ guard !projection.groups.isEmpty else { continue }+ func recordClaims<Row: RecordRow>(_ type: Row.Type,+ claimID: UUID) throws -> [GroupNameClaim] {+ let scoped = try Row.rows(of: group.rows, context: context)+ let grouped = Dictionary(grouping: scoped, by: \.recordID)+ var claims: [GroupNameClaim] = []+ for (id, copies) in grouped {+ let address = AssociationRecordAddress(kind: Row.kind, id: id)+ let names: [String]+ if let projected = projectedTargets?[address] {+ names = projected.workID == workID ? projected.names : []+ } else {+ names = copies.flatMap { [$0.name, $0.nameKey] + $0.aliases }+ }+ claims += names.map { GroupNameClaim(kind: Row.kind == .character+ ? .character : .place, id: claimID, spelling: $0) }+ }+ for (address, projected) in projectedTargets ?? [:]+ where address.kind == Row.kind && projected.workID == workID+ && grouped[address.id] == nil {+ claims += projected.names.map { GroupNameClaim(kind: Row.kind == .character+ ? .character : .place, id: claimID, spelling: $0) }+ }+ return claims+ }+ let characterClaims = try recordClaims(CharacterRecord.self,+ claimID: characterClaimID)+ let placeClaims = try recordClaims(Place.self, claimID: placeClaimID)+ let groupClaims = projection.groups.flatMap { summary in+ ([summary.name].compactMap { $0 } + summary.aliases).map {+ GroupNameClaim(kind: .group, id: summary.groupID, spelling: $0)+ }+ }+ let claims = characterClaims + placeClaims + groupClaims+ // Every pair at one chapter reads the same note, claims and roster.+ // Resolve its spans once, then select each addressed character.+ var resolvedChapters: [UUID: GroupReferenceResolution] = [:]+ for pair in pairs where pair.workID == workID && pair.kind == .character {+ guard let source = sources[pair.entryID], source.eligible,+ source.workID == workID else { continue }+ let resolved: GroupReferenceResolution+ if let cached = resolvedChapters[pair.entryID] {+ resolved = cached+ } else {+ resolved = GroupReferenceResolver.resolve(note: source.note,+ chapterID: pair.entryID, claims: claims, roster: projection)+ resolvedChapters[pair.entryID] = resolved+ }+ result[pair] = resolved.associationSupports(for: pair.recordID)+ }+ }+ return result+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupTransitionRebind.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupTransitionRebind.swiftnew file mode 100644index 00000000..1f2b79a2--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupTransitionRebind.swift@@ -0,0 +1,57 @@+import Foundation++/// Rebind only complete, physically coherent roots. A compatible set of live+/// heads can be observed by one successor; distinct values stay separate so+/// the ordinary editor can resolve them explicitly after the identity moves.+enum GroupTransitionRebind {+ enum RootState {+ case live([GroupTransitionFact])+ case removed+ case uncertain+ }++ static func states(rows: [GroupTransition]) -> [UUID: RootState] {+ let copiesByID = Dictionary(grouping: rows, by: \.id)+ let rootIDs = Set(rows.compactMap { $0.transitionValue?.rootID })+ let coherent = copiesByID.values.compactMap { copies -> GroupTransitionFact? in+ guard let first = copies.first else { return nil }+ let raw = GroupRawTransition(first)+ guard copies.allSatisfy({ GroupRawTransition($0) == raw }) else { return nil }+ return first.transitionValue+ }+ var result: [UUID: RootState] = [:]+ for rootID in rootIDs {+ let physicalIDs = Set(rows.compactMap { row in+ row.transitionValue?.rootID == rootID ? row.id : nil+ })+ let chain = coherent.filter { $0.rootID == rootID }+ let byID = Dictionary(uniqueKeysWithValues: chain.map { ($0.id, $0) })+ guard Set(byID.keys) == physicalIDs,+ let root = byID[rootID], root.rootID == root.id,+ chain.allSatisfy({ GroupRoster.complete($0.id, in: byID,+ parents: { $0.parentHeadIDs }) &&+ ($0.id == rootID || GroupRoster.hasAncestor($0.id,+ ancestor: rootID, in: byID,+ parents: { $0.parentHeadIDs })) }) else {+ result[rootID] = .uncertain+ continue+ }+ if chain.contains(where: { $0.action == .remove }) {+ result[rootID] = .removed+ continue+ }+ let parents = Set(chain.flatMap(\.parentHeadIDs))+ let heads = chain.filter { !parents.contains($0.id) }+ .sorted { $0.id.uuidString < $1.id.uuidString }+ result[rootID] = heads.isEmpty ? .uncertain : .live(heads)+ }+ return result+ }++ static func sameValue(_ heads: [GroupTransitionFact]) -> Bool {+ guard let first = heads.first else { return false }+ return heads.allSatisfy { $0.workID == first.workID &&+ $0.groupID == first.groupID && $0.characterID == first.characterID &&+ $0.chapterID == first.chapterID && $0.action == first.action }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupWorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupWorkMerge.swiftnew file mode 100644index 00000000..c9b2c10d--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupWorkMerge.swift@@ -0,0 +1,117 @@+import Foundation+import SwiftData++/// The survivor receives new group identities and causal successors. Source+/// events remain byte-identical, so a late CloudKit delivery cannot disagree+/// with a rewritten copy of the same application UUID.+enum GroupWorkMerge {+ enum Refusal: Error, CustomStringConvertible {+ case unresolvedSourceGroup++ var description: String {+ "Source group history must be resolved before merging its Work"+ }+ }++ static func transfer(source: WorkGroup, targetWorkID: UUID,+ context: ModelContext, recordedAt: Date) throws {+ let projection = try GroupSupportInventory.projection(work: source,+ context: context)+ let sourceID = source.id+ let sourceGroups = try context.fetch(FetchDescriptor<NamedCharacterGroup>(+ predicate: #Predicate { $0.workID == sourceID }))+ let sourceFacts = try context.fetch(FetchDescriptor<GroupFactEvent>(+ predicate: #Predicate { $0.workID == sourceID }))+ let allFacts = try GroupSupportInventory.factRows(selected: sourceFacts,+ context: context)+ let coherentFacts = Dictionary(grouping: allFacts, by: \.id).values.compactMap {+ copies -> GroupFact? in+ guard let first = copies.first else { return nil }+ let raw = GroupRawFact(first)+ guard copies.allSatisfy({ GroupRawFact($0) == raw }) else { return nil }+ return first.factValue+ }+ let factsByID = Dictionary(uniqueKeysWithValues: coherentFacts.map { ($0.id, $0) })+ let visibleIDs = Set(projection.groups.map(\.groupID))+ let absentIDs = Set(sourceGroups.map(\.id)).subtracting(visibleIDs)+ let deletedIDs = Set(absentIDs.filter { groupID in+ let events = coherentFacts.filter { $0.groupID == groupID &&+ $0.workID == sourceID && GroupRoster.complete($0.id, in: factsByID,+ parents: { $0.parentHeadIDs }) }+ return events.contains(where: { if case .create = $0.operation { return true }; return false }) &&+ events.contains(where: { if case .delete = $0.operation { return true }; return false })+ })+ guard absentIDs == deletedIDs,+ projection.groups.allSatisfy({ $0.name != nil &&+ projection.unresolvedSpellings[$0.groupID, default: []].isEmpty }) else {+ throw Refusal.unresolvedSourceGroup+ }+ guard !projection.groups.isEmpty else { return }+ let sourceTransitions = try GroupSupportInventory.transitionRows(workID: sourceID,+ context: context)+ let states = GroupTransitionRebind.states(rows: sourceTransitions)+ for summary in projection.groups {+ guard let name = summary.name else { throw Refusal.unresolvedSourceGroup }+ let sourceRows = sourceTransitions.filter {+ $0.workID == sourceID && $0.groupID == summary.groupID+ }+ guard sourceRows.allSatisfy({ $0.transitionValue != nil }) else {+ throw Refusal.unresolvedSourceGroup+ }+ let roots = Set(sourceRows.compactMap { $0.transitionValue?.rootID })+ var successors: [GroupTransitionFact] = []+ for rootID in roots {+ guard let state = states[rootID] else { throw Refusal.unresolvedSourceGroup }+ switch state {+ case .removed: continue+ case .uncertain: throw Refusal.unresolvedSourceGroup+ case .live(let heads):+ guard let first = heads.first,+ heads.allSatisfy({ $0.workID == sourceID &&+ $0.groupID == summary.groupID &&+ $0.characterID == first.characterID }) else {+ throw Refusal.unresolvedSourceGroup+ }+ if GroupTransitionRebind.sameValue(heads) {+ successors.append(.init(rootID: rootID, workID: targetWorkID,+ groupID: summary.groupID, characterID: first.characterID,+ chapterID: first.chapterID,+ parentHeadIDs: heads.map(\.id), action: first.action))+ } else {+ successors += heads.map { head in+ .init(rootID: rootID, workID: targetWorkID,+ groupID: summary.groupID, characterID: head.characterID,+ chapterID: head.chapterID,+ parentHeadIDs: [head.id], action: head.action)+ }+ }+ }+ }+ let destinationID = UUID()+ context.insert(NamedCharacterGroup(id: destinationID,+ workID: targetWorkID))+ let inheritedFactIDs = sourceFacts.filter { $0.groupID == summary.groupID }+ .map(\.id)+ let create = GroupFact(groupID: destinationID, workID: targetWorkID,+ parentHeadIDs: inheritedFactIDs, operation: .create(name: name))+ context.insert(try GroupFactEvent(fact: create,+ recordedAt: recordedAt))+ var parent = create.id+ for alias in summary.aliases {+ let fact = GroupFact(groupID: destinationID, workID: targetWorkID,+ parentHeadIDs: [parent], operation: .addAlias(alias))+ context.insert(try GroupFactEvent(fact: fact,+ recordedAt: recordedAt))+ parent = fact.id+ }+ for planned in successors {+ let successor = GroupTransitionFact(rootID: planned.rootID,+ workID: targetWorkID, groupID: destinationID,+ characterID: planned.characterID, chapterID: planned.chapterID,+ parentHeadIDs: planned.parentHeadIDs, action: planned.action)+ context.insert(try GroupTransition(fact: successor,+ recordedAt: recordedAt))+ }+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryConfiguration.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryConfiguration.swiftindex bc36bd28..84f41ec5 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryConfiguration.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryConfiguration.swift@@ -174,6 +174,11 @@ public struct LibraryConfiguration: Sendable, Equatable { rootDirectory.appending(path: Self.syncStatusFilename) } + /// Device-local cursor for bounded chapter relinking after group changes.+ public var groupHistoryURL: URL {+ rootDirectory.appending(path: "GroupHistoryReconciliation.json")+ }+ /// Written before an import's first save and removed after its last, so an /// interrupted import is reportable however long afterwards (Req 4.4). public var importSidecarURL: URL {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex 5803052a..58c25490 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift@@ -3,6 +3,7 @@ import Foundation /// Test seam for the app's view-model layer to consume repository operations /// without coupling directly to the actor or its persistence internals. public protocol LibraryProviding: Sendable {+ func commitWorkDetailEdit(_ request: WorkDetailEditTransaction) async throws -> WorkDetailEditOutcome func recordCopyContext(sourceWorkID: UUID) async throws -> RecordCopyContext func previewRecordCopy(sourceWorkID: UUID, destinationWorkID: UUID, selections: [RecordCopySelection], includeNotes: Bool) async throws -> RecordCopyPreview func commitRecordCopy(_ preview: RecordCopyPreview) async throws -> RecordCopyOutcome@@ -24,6 +25,8 @@ public protocol LibraryProviding: Sendable { 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 removeChapterAssociation(pair: AssociationPair) async throws -> Bool+ func restoreChapterAssociation(pair: AssociationPair) async throws -> Bool func associationNoteBasis(pair: AssociationPair) async throws -> AssociationNoteBasis? func saveAssociationNote(basis: AssociationNoteBasis, text: String) async throws -> AssociationNoteWriteOutcome func clearAssociationNote(basis: AssociationNoteBasis) async throws -> AssociationNoteWriteOutcome@@ -139,6 +142,18 @@ public protocol LibraryProviding: Sendable { workID: UUID, operations: [RecordEditOperation] ) async throws -> RecordEditOutcome + /// The group editor's one-save event transaction and reciprocal roster.+ func commitGroupEdits(workID: UUID, operations: [GroupEditOperation],+ currentChapterID: UUID?) async throws -> GroupEditOutcome+ func characterGroups(workID: UUID) async throws -> [GroupSummary]+ func groupSuggestionMembershipIsEffective(workID: UUID, chapterID: UUID,+ groupName: String, characterName: String) async throws -> Bool+ func groupSuggestionLeaveIsApplicable(workID: UUID, chapterID: UUID,+ groupName: String, characterName: String) async throws -> Bool+ func groupSuggestionSkips(workID: UUID) async throws -> Set<GroupSuggestionSkip>+ func skipGroupSuggestion(_ skip: GroupSuggestionSkip,+ sourceFingerprint: String) async throws -> GroupEditOutcome+ /// The configured work-type list for the settings screen and the editor's /// picker: active entries, plus the removed ones works still use (Reqs 1.1, /// 1.7). One row per identity — duplicate rows are folded, merged entries@@ -625,6 +640,22 @@ public protocol LibraryProviding: Sendable { } public extension LibraryProviding {+ func commitGroupEdits(workID: UUID, operations: [GroupEditOperation],+ currentChapterID: UUID? = nil) async throws -> GroupEditOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "editing character groups",+ reason: "Group editing is unavailable in this library")+ }+ func characterGroups(workID: UUID) async throws -> [GroupSummary] { [] }+ func groupSuggestionMembershipIsEffective(workID: UUID, chapterID: UUID,+ groupName: String, characterName: String) async throws -> Bool { false }+ func groupSuggestionLeaveIsApplicable(workID: UUID, chapterID: UUID,+ groupName: String, characterName: String) async throws -> Bool { false }+ func groupSuggestionSkips(workID: UUID) async throws -> Set<GroupSuggestionSkip> { [] }+ func skipGroupSuggestion(_ skip: GroupSuggestionSkip,+ sourceFingerprint: String) async throws -> GroupEditOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "skipping group suggestion",+ reason: "Group suggestions are unavailable in this library")+ } func recordHistory(workID: UUID, kind: RecordKind, recordID: UUID) async throws -> RecordHistorySnapshot { throw LibraryRepositoryError.invalidInput(operation: "reading record history", reason: "unavailable in this library") }@@ -644,6 +675,8 @@ public extension LibraryProviding { throw LibraryRepositoryError.invalidInput(operation: "preserving pending mention review", reason: "unavailable in this library") } func chapterAssociations(entryID: UUID) async throws -> [ChapterAssociationSnapshot] { [] }+ func removeChapterAssociation(pair: AssociationPair) async throws -> Bool { false }+ func restoreChapterAssociation(pair: AssociationPair) async throws -> Bool { false } func associationNoteBasis(pair: AssociationPair) async throws -> AssociationNoteBasis? { nil } func detachedAssociationNotes() async throws -> [DetachedAssociationNoteSnapshot] { [] } func saveAssociationNote(basis: AssociationNoteBasis, text: String) async throws -> AssociationNoteWriteOutcome {@@ -863,6 +896,9 @@ public extension LibraryProviding { extension LibraryRepository: LibraryProviding {} extension LibraryProviding {+ public func commitWorkDetailEdit(_ request: WorkDetailEditTransaction) async throws -> WorkDetailEditOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "saving Work detail", reason: "Combined edits are unavailable")+ } public func updateWorkWithMembershipReceipt(id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar) async throws -> MembershipWriteReceipt { throw LibraryRepositoryError.invalidInput(operation: "saving membership", reason: "Membership receipts are unavailable") }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Associations.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Associations.swiftindex ff92cc21..9c2a9c61 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Associations.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Associations.swift@@ -2,6 +2,64 @@ import Foundation import SwiftData extension LibraryRepository {+ public func removeChapterAssociation(pair: AssociationPair) async throws -> Bool {+ try await withLockedContext(mode: .exclusive, operation: "removing chapter association") { context in+ let before = try AssociationMutation.capture(context: context, workIDs: [pair.workID],+ entryIDs: [pair.entryID], records: [.init(kind: pair.kind, id: pair.recordID)])+ guard let roots = before.active[pair], !roots.isEmpty else { return false }+ var supports: Set<AssociationPairSupportKey> = []+ // A refreshed direct receipt can validate new aliases on an old+ // root without changing that root's immutable spelling keys. A+ // group-only root does not authorize suppressing nested direct+ // evidence that may become a later independent mention.+ let hasDirectRoot = roots.contains { id in+ guard let acceptance = before.storage.ledger.acceptance(id) else {+ return false+ }+ switch acceptance.support {+ case .some(.group): return false+ case .some(.direct), .none: return true+ }+ }+ if hasDirectRoot, let current = before.endpoints.current(pair) {+ for evidence in before.storage.ledger.receipt(for: current).evidence {+ supports.insert(.direct(spellingKey: evidence.key))+ }+ }+ for id in roots {+ guard let acceptance = before.storage.ledger.acceptance(id) else { continue }+ switch acceptance.support {+ case .direct(let key): supports.insert(.direct(spellingKey: key))+ case .group(let groupID, let key, _): supports.insert(.group(groupID: groupID, spellingKey: key))+ case nil:+ for key in acceptance.spellingKeys { supports.insert(.direct(spellingKey: key)) }+ }+ }+ guard !supports.isEmpty else { return false }+ let timestamp = MillisecondInstant.quantize(self.clock.now())+ let event = AssociationLedgerEvent(payload: .pairCorrection(.init(pair: pair, supports: Array(supports))))+ context.insert(try AssociationEvent(event: event, recordedAt: timestamp))+ do { try self.saveStrategy.save(context) } catch { context.rollback(); throw error }+ return true+ }+ }++ public func restoreChapterAssociation(pair: AssociationPair) async throws -> Bool {+ try await withLockedContext(mode: .exclusive, operation: "restoring chapter association") { context in+ let before = try AssociationMutation.capture(context: context, workIDs: [pair.workID],+ entryIDs: [pair.entryID], records: [.init(kind: pair.kind, id: pair.recordID)])+ let corrections = before.storage.ledger.pairCorrectionIDs(pair: pair)+ guard !corrections.isEmpty else { return false }+ let timestamp = MillisecondInstant.quantize(self.clock.now())+ let event = AssociationLedgerEvent(payload: .pairCorrectionAcknowledgement(+ .init(pair: pair, correctionIDs: corrections)))+ context.insert(try AssociationEvent(event: event, recordedAt: timestamp))+ _ = try Self.recordKnownChapterLinks(entryIDs: [pair.entryID], context: context, timestamp: timestamp)+ do { try self.saveStrategy.save(context) } catch { context.rollback(); throw error }+ return true+ }+ }+ 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)@@ -27,7 +85,8 @@ extension LibraryRepository { 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: []])+ rawNotes: rawByPair[pair, default: []],+ removalCorrectionIDs: storage.ledger.pairCorrectionIDs(pair: pair)) }.sorted { [$0.pair.kind.rawValue, $0.recordName, $0.pair.recordID.uuidString] .lexicographicallyPrecedes([$1.pair.kind.rawValue, $1.recordName, $1.pair.recordID.uuidString]) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swiftindex 8b99533c..6e1c1678 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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 c5ac20a7..7b324936 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismV21MigrationPlan.self,+ migrationPlan: AsterismV22MigrationPlan.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", "20", extensionOpenableMarkerVersion,+ laggingOpenableMarkerVersion, "17", "18", "19", "20", "21", 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 = "21"+ static let extensionOpenableMarkerVersion = "22" // 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+CharacterGroups.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CharacterGroups.swiftnew file mode 100644index 00000000..b98b604e--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CharacterGroups.swift@@ -0,0 +1,445 @@+import Foundation+import SwiftData++public enum GroupSuggestionAction: String, Sendable, Equatable {+ case join, leave+}++/// One editor session is checked and saved together. Event IDs are supplied by+/// the caller so a retry can recognise the operation it already committed.+public struct GroupSuggestionApproval: Sendable, Equatable {+ public let chapterID: UUID+ public let sourceFingerprint: String+ public let groupName: String+ public let characterName: String?+ public let quote: String?+ public let action: GroupSuggestionAction+ public let plannedGroupID: UUID+ public let plannedTransitionID: UUID+ public init(chapterID: UUID, sourceFingerprint: String, groupName: String,+ characterName: String? = nil, quote: String? = nil,+ action: GroupSuggestionAction = .join,+ plannedGroupID: UUID, plannedTransitionID: UUID = UUID()) {+ self.chapterID = chapterID; self.sourceFingerprint = sourceFingerprint+ self.groupName = groupName; self.characterName = characterName; self.quote = quote+ self.action = action+ self.plannedGroupID = plannedGroupID; self.plannedTransitionID = plannedTransitionID+ }+}++public enum GroupEditOperation: Sendable, Equatable {+ case create(groupID: UUID, name: String)+ case fact(groupID: UUID, expectedEventIDs: [UUID], operation: GroupFactOperation)+ case transition(rootID: UUID, groupID: UUID, characterID: UUID,+ chapterID: UUID, action: GroupTransitionAction)+ case reviseTransition(rootID: UUID, expectedEventIDs: [UUID],+ chapterID: UUID, action: GroupTransitionAction)+ case approveSuggestion(GroupSuggestionApproval)+}++public enum GroupEditRefusal: Sendable, Equatable {+ case workGone, workTorn, groupGone, groupTorn, stale, crossWork+ case chapterGone, characterGone, invalidOperation+}++public enum GroupEditOutcome: Sendable, Equatable {+ case committed(groupIDs: [UUID])+ case refused(GroupEditRefusal)+}++extension LibraryRepository {+ public func characterGroups(workID: UUID) async throws -> [GroupSummary] {+ try await withLockedContext(mode: .shared, operation: "reading character groups") { context in+ let rows = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID }))+ guard let group = Self.workGroup(id: workID, rows: rows,+ types: try Self.workTypeDirectory(context: context)), !group.isTorn else { return [] }+ return try GroupSupportInventory.projection(work: group, context: context).groups+ }+ }++ /// Whether both names resolve uniquely and the coherent chapter roster+ /// includes that character.+ public func groupSuggestionMembershipIsEffective(workID: UUID, chapterID: UUID,+ groupName: String, characterName: String) async throws -> Bool {+ try await withLockedContext(mode: .shared,+ operation: "checking proposed group join") { context in+ let workRows = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate {+ $0.id == workID+ }))+ guard let work = Self.workGroup(id: workID, rows: workRows,+ types: try Self.workTypeDirectory(context: context)), !work.isTorn else { return false }+ let projection = try GroupSupportInventory.projection(work: work, context: context)+ let key = RecordNameKey.normalize(groupName)+ let groups = projection.groups.filter { group in+ ([group.name].compactMap { $0 } + group.aliases).contains {+ RecordNameKey.normalize($0) == key+ }+ }+ guard groups.count == 1, let group = groups.first else { return false }+ let rows = try CharacterRecord.rows(of: work.rows, context: context)+ let targets = Self.recordGroups(rows).values.map { Self.matchTarget($0) }+ guard case .unique(let characterID) = RecordMatching.recognition(+ nameKey: RecordNameKey.normalize(characterName), among: targets),+ let character = Self.recordGroup(id: characterID,+ rows: try CharacterRecord.rows(ids: [characterID], context: context)),+ !character.isTorn, character.rows.allSatisfy({ $0.ownerWorkID == workID })+ else { return false }+ return projection.members(groupID: group.groupID,+ chapterID: chapterID).contains(characterID)+ }+ }++ /// A leave is inclusive at its named chapter. Suppress the exact accepted+ /// transition, but allow a later explicit leave to extend the boundary.+ public func groupSuggestionLeaveIsApplicable(workID: UUID, chapterID: UUID,+ groupName: String, characterName: String) async throws -> Bool {+ try await withLockedContext(mode: .shared,+ operation: "checking accepted group leave") { context in+ let workRows = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate {+ $0.id == workID+ }))+ guard let work = Self.workGroup(id: workID, rows: workRows,+ types: try Self.workTypeDirectory(context: context)), !work.isTorn else { return false }+ let projection = try GroupSupportInventory.projection(work: work, context: context)+ let groupKey = RecordNameKey.normalize(groupName)+ let groups = projection.groups.filter { group in+ ([group.name].compactMap { $0 } + group.aliases).contains {+ RecordNameKey.normalize($0) == groupKey+ }+ }+ guard groups.count == 1, let group = groups.first else { return false }+ let records = try CharacterRecord.rows(of: work.rows, context: context)+ let targets = Self.recordGroups(records).values.map { Self.matchTarget($0) }+ guard case .unique(let characterID) = RecordMatching.recognition(+ nameKey: RecordNameKey.normalize(characterName), among: targets) else { return false }+ if group.transitions.contains(where: { transition in+ transition.action == .leave && transition.chapterID == chapterID &&+ transition.characterID == characterID+ }) { return false }+ if projection.members(groupID: group.groupID, chapterID: chapterID).contains(characterID) {+ return true+ }+ return projection.hasMembershipBefore(groupID: group.groupID,+ characterID: characterID, chapterID: chapterID)+ }+ }++ public func commitGroupEdits(workID: UUID, operations: [GroupEditOperation],+ currentChapterID: UUID? = nil) async throws -> GroupEditOutcome {+ guard !operations.isEmpty else { return .committed(groupIDs: []) }+ let outcome: GroupEditOutcome = try await withLockedContext(mode: .exclusive,+ operation: "committing character group edits") { context in+ let result = try self.applyGroupEdits(workID: workID, operations: operations,+ currentChapterID: currentChapterID, context: context)+ if case .committed = result {+ do { try saveStrategy.save(context) }+ catch { context.rollback(); throw error }+ }+ return result+ }+ if case .committed = outcome {+ // The current chapter was saved atomically above. A failed+ // historical sweep is retried from the device-local cursor at the+ // next activation; it cannot turn a committed edit into a refusal.+ _ = try? await reconcileGroupHistory()+ }+ return outcome+ }+ internal func applyGroupEdits(workID: UUID, operations: [GroupEditOperation],+ currentChapterID: UUID? = nil, context: ModelContext) throws -> GroupEditOutcome {+ guard !operations.isEmpty else { return .committed(groupIDs: []) }+ let workRows = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID }))+ guard !workRows.isEmpty else { return .refused(.workGone) }+ guard let work = Self.workGroup(id: workID, rows: workRows,+ types: try Self.workTypeDirectory(context: context)), !work.isTorn else {+ return .refused(.workTorn)+ }+ if let currentChapterID {+ let rows = try context.fetch(FetchDescriptor<Entry>(+ predicate: #Predicate { $0.id == currentChapterID }))+ guard !rows.isEmpty else { return .refused(.chapterGone) }+ guard rows.allSatisfy({ $0.work?.id == workID &&+ AssociationEndpointInventory.eligible($0) }) else {+ return .refused(.crossWork)+ }+ }+ let selectedGroups = try context.fetch(FetchDescriptor<NamedCharacterGroup>(+ predicate: #Predicate { $0.workID == workID }))+ let selectedFacts = try context.fetch(FetchDescriptor<GroupFactEvent>(+ predicate: #Predicate { $0.workID == workID }))+ let groupIDs = Array(Set(selectedGroups.map(\.id)))+ var groupRows = groupIDs.isEmpty ? [] : try context.fetch(FetchDescriptor<NamedCharacterGroup>(+ predicate: #Predicate { groupIDs.contains($0.id) }))+ var factRows = try GroupSupportInventory.factRows(selected: selectedFacts, context: context)+ var transitionRows = try GroupSupportInventory.transitionRows(workID: workID, context: context)+ var touchedChapters = Set(currentChapterID.map { [$0] } ?? [])+ for operation in operations {+ switch operation {+ case .transition(_, _, _, let chapterID, _):+ touchedChapters.insert(chapterID)+ case .reviseTransition(let rootID, _, let chapterID, _):+ touchedChapters.insert(chapterID)+ touchedChapters.formUnion(transitionRows.filter {+ $0.workID == workID && $0.transitionValue?.rootID == rootID+ }.map(\.entryID))+ case .approveSuggestion(let approval): touchedChapters.insert(approval.chapterID)+ default: break+ }+ }+ let before = try AssociationMutation.capture(context: context,+ workIDs: [workID], entryIDs: touchedChapters)+ let timestamp = MillisecondInstant.quantize(clock.now())+ var created: [UUID] = []+ // The editor's basis names this Work's events. Ancestors from a+ // merged source establish causal completeness but are not new+ // current-Work heads the reader was asked to compare.+ let initialFactIDs = Dictionary(grouping: factRows.filter { $0.workID == workID },+ by: \.groupID).mapValues { Set($0.map(\.id)) }+ func refuse(_ reason: GroupEditRefusal) -> GroupEditOutcome {+ context.rollback(); return .refused(reason)+ }+ func validateGroup(_ groupID: UUID) -> GroupEditRefusal? {+ let rows = groupRows.filter { $0.id == groupID }+ guard !rows.isEmpty else { return .groupGone }+ guard rows.allSatisfy({ $0.workID == workID }) else { return .crossWork }+ let currentIDs = Set(factRows.filter {+ $0.groupID == groupID && $0.workID == workID+ }.map(\.id))+ // Include every physical copy of each current-Work fact ID.+ // An inherited source fact is ancestry, but a foreign twin of+ // a current alias must invalidate the editor's loaded basis.+ let facts = factRows.filter { currentIDs.contains($0.id) }+ guard !facts.isEmpty,+ facts.allSatisfy({ $0.groupID == groupID && $0.workID == workID &&+ $0.factValue != nil }) else { return .groupTorn }+ guard Dictionary(grouping: facts, by: \.id).values.allSatisfy({ copies in+ guard let first = copies.first else { return false }+ return copies.allSatisfy { $0.workID == first.workID &&+ $0.groupID == first.groupID && $0.payloadData == first.payloadData &&+ $0.parentHeadIDsData == first.parentHeadIDsData &&+ $0.recordedAt == first.recordedAt }+ }) else { return .groupTorn }+ let projection = GroupRoster.project(workID: workID, chapters: [],+ groupRows: rows, factRows: factRows, transitionRows: [])+ return projection.groups.contains { $0.groupID == groupID } ? nil : .groupTorn+ }+ func validateMember(_ characterID: UUID, chapterID: UUID) throws -> GroupEditRefusal? {+ let characters = try CharacterRecord.rows(ids: [characterID], context: context)+ guard !characters.isEmpty else { return .characterGone }+ guard characters.allSatisfy({ $0.ownerWorkID == workID }),+ let group = Self.recordGroup(id: characterID, rows: characters),+ !group.isTorn else { return .crossWork }+ let entries = try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { $0.id == chapterID }))+ guard !entries.isEmpty else { return .chapterGone }+ guard entries.allSatisfy({ $0.work?.id == workID &&+ AssociationEndpointInventory.eligible($0) }) else { return .crossWork }+ return nil+ }+ for operation in operations {+ switch operation {+ case .approveSuggestion(let approval):+ let chapterID = approval.chapterID+ let entries = try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate {+ $0.id == chapterID+ }))+ guard !entries.isEmpty, entries.allSatisfy({ $0.work?.id == workID &&+ AssociationEndpointInventory.eligible($0) &&+ CharacterCoverageFingerprint.of($0.note) == approval.sourceFingerprint }) else {+ return refuse(.stale)+ }+ let note = entries[0].note+ let groupName = approval.groupName.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !RecordMentionGrounding.completeNameEvidence(names: [groupName], in: note).isEmpty else {+ return refuse(.stale)+ }+ if let characterName = approval.characterName {+ guard let quote = approval.quote, !quote.isEmpty,+ note.precomposedStringWithCanonicalMapping.range(+ of: quote.precomposedStringWithCanonicalMapping) != nil,+ !RecordMentionGrounding.completeNameEvidence(names: [groupName], in: quote).isEmpty,+ !RecordMentionGrounding.completeNameEvidence(names: [characterName], in: quote).isEmpty+ else { return refuse(.stale) }+ }+ let names = GroupRoster.project(workID: workID, chapters: [],+ groupRows: groupRows, factRows: factRows,+ transitionRows: transitionRows).groups.filter { summary in+ ([summary.name].compactMap { $0 } + summary.aliases).contains {+ RecordNameKey.normalize($0) == RecordNameKey.normalize(groupName)+ }+ }+ guard names.count <= 1 else { return refuse(.groupTorn) }+ if approval.action == .leave, names.isEmpty { return refuse(.stale) }+ if approval.action == .leave, approval.characterName == nil { return refuse(.stale) }+ let resolvedGroupID: UUID+ if let existing = names.first {+ if approval.characterName == nil { return refuse(.stale) }+ resolvedGroupID = existing.groupID+ } else {+ let plannedID = approval.plannedGroupID+ let collision = try context.fetch(FetchDescriptor<NamedCharacterGroup>(+ predicate: #Predicate { $0.id == plannedID }))+ guard collision.isEmpty else { return refuse(.stale) }+ let row = NamedCharacterGroup(id: plannedID, workID: workID)+ let fact = try GroupFactEvent(fact: .init(groupID: plannedID,+ workID: workID, operation: .create(name: groupName)),+ recordedAt: timestamp)+ context.insert(row); context.insert(fact)+ groupRows.append(row); factRows.append(fact)+ created.append(plannedID); resolvedGroupID = plannedID+ }+ if let characterName = approval.characterName {+ let records = try CharacterRecord.rows(of: work.rows, context: context)+ let targets = Self.recordGroups(records).values.map { Self.matchTarget($0) }+ guard case .unique(let characterID) = RecordMatching.recognition(+ nameKey: RecordNameKey.normalize(characterName), among: targets),+ let group = Self.recordGroup(id: characterID,+ rows: try CharacterRecord.rows(ids: [characterID], context: context)),+ !group.isTorn, group.rows.allSatisfy({ $0.ownerWorkID == workID }) else {+ return refuse(.characterGone)+ }+ let membershipProjection = try GroupSupportInventory.projection(work: work,+ context: context)+ let isMember = membershipProjection.members(groupID: resolvedGroupID,+ chapterID: approval.chapterID).contains(characterID)+ if approval.action == .join, names.first != nil, isMember {+ return refuse(.stale)+ }+ let hasPriorMembership = membershipProjection.hasMembershipBefore(+ groupID: resolvedGroupID, characterID: characterID,+ chapterID: approval.chapterID)+ if approval.action == .leave, !isMember && !hasPriorMembership {+ return refuse(.stale)+ }+ if approval.action == .leave,+ membershipProjection.groups.first(where: {+ $0.groupID == resolvedGroupID+ })?.transitions.contains(where: { transition in+ transition.action == .leave && transition.chapterID == approval.chapterID &&+ transition.characterID == characterID+ }) == true {+ return refuse(.stale)+ }+ let plannedID = approval.plannedTransitionID+ let collision = try context.fetch(FetchDescriptor<GroupTransition>(+ predicate: #Predicate { $0.id == plannedID }))+ guard collision.isEmpty else { return refuse(.stale) }+ let fact = GroupTransitionFact(id: plannedID, rootID: plannedID,+ workID: workID, groupID: resolvedGroupID,+ characterID: characterID, chapterID: approval.chapterID,+ action: approval.action == .join ? .join : .leave)+ let row = try GroupTransition(fact: fact, recordedAt: timestamp)+ context.insert(row); transitionRows.append(row)+ }+ case .create(let groupID, let name):+ guard !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {+ return refuse(.invalidOperation)+ }+ let allIDs = try context.fetch(FetchDescriptor<NamedCharacterGroup>(+ predicate: #Predicate { $0.id == groupID }))+ guard allIDs.isEmpty else { return refuse(.stale) }+ let row = NamedCharacterGroup(id: groupID, workID: workID)+ let fact = try GroupFactEvent(fact: .init(groupID: groupID, workID: workID,+ operation: .create(name: name)), recordedAt: timestamp)+ context.insert(row); context.insert(fact)+ groupRows.append(row); factRows.append(fact); created.append(groupID)+ case .fact(let groupID, let expected, let factOperation):+ guard case .create = factOperation else {+ if let refusal = validateGroup(groupID) { return refuse(refusal) }+ let observed = factRows.filter {+ $0.workID == workID && $0.groupID == groupID+ }.map(\.id)+ guard (initialFactIDs[groupID] ?? []) == Set(expected), Set(expected).count == expected.count else {+ return refuse(.stale)+ }+ let fact = try GroupFactEvent(fact: .init(groupID: groupID,+ workID: workID, parentHeadIDs: observed,+ operation: factOperation), recordedAt: timestamp)+ context.insert(fact); factRows.append(fact)+ if case .delete = factOperation {+ for characterID in Set(transitionRows.filter {+ $0.groupID == groupID+ }.map(\.characterID)) {+ try GroupRecordMutation.advance(workID: workID,+ from: characterID, to: nil, context: context,+ recordedAt: timestamp, groupID: groupID)+ }+ }+ continue+ }+ return refuse(.invalidOperation)+ case .transition(let rootID, let groupID, let characterID, let chapterID, let action):+ guard action != .remove else { return refuse(.invalidOperation) }+ if let refusal = validateGroup(groupID) { return refuse(refusal) }+ if let refusal = try validateMember(characterID, chapterID: chapterID) { return refuse(refusal) }+ guard !transitionRows.contains(where: { $0.id == rootID }) else { return refuse(.stale) }+ let fact = GroupTransitionFact(id: rootID, rootID: rootID, workID: workID,+ groupID: groupID, characterID: characterID, chapterID: chapterID, action: action)+ let row = try GroupTransition(fact: fact, recordedAt: timestamp)+ context.insert(row); transitionRows.append(row)+ case .reviseTransition(let rootID, let expected, let chapterID, let action):+ let selectedIDs = Set(transitionRows.filter {+ $0.transitionValue?.rootID == rootID+ }.map(\.id))+ // Select the logical chain, then expand those application+ // IDs back to every physical copy. A malformed twin has+ // no decodable rootID but still disputes the selected ID.+ let chains = transitionRows.filter { selectedIDs.contains($0.id) }+ guard Dictionary(grouping: chains, by: \.id).values.allSatisfy({ copies in+ guard let first = copies.first else { return false }+ return copies.allSatisfy { $0.workID == first.workID &&+ $0.groupID == first.groupID && $0.characterID == first.characterID &&+ $0.entryID == first.entryID && $0.payloadData == first.payloadData &&+ $0.parentHeadIDsData == first.parentHeadIDsData &&+ $0.recordedAt == first.recordedAt }+ }) else { return refuse(.stale) }+ let chain = Dictionary(grouping: chains, by: \.id).values.compactMap {+ $0.first?.transitionValue+ }+ guard chain.contains(where: { $0.id == rootID && $0.rootID == rootID }) else {+ return refuse(.stale)+ }+ let currentIDs = Set(chain.filter { $0.workID == workID }.map(\.id))+ guard !currentIDs.isEmpty, currentIDs == Set(expected),+ Set(expected).count == expected.count else {+ return refuse(.stale)+ }+ let byID = Dictionary(uniqueKeysWithValues: chain.map { ($0.id, $0) })+ guard chain.filter({ $0.workID == workID }).allSatisfy({ event in+ GroupRoster.complete(event.id, in: byID,+ parents: { $0.parentHeadIDs }) &&+ (event.id == rootID || GroupRoster.hasAncestor(event.id,+ ancestor: rootID, in: byID,+ parents: { $0.parentHeadIDs }))+ }) else { return refuse(.stale) }+ let projection = GroupRoster.project(workID: workID, chapters: [],+ groupRows: groupRows, factRows: factRows,+ transitionRows: transitionRows)+ let resolved = projection.groups.flatMap(\.transitions).first(where: {+ $0.rootID == rootID && $0.workID == workID+ })+ let conflict = projection.groups.flatMap(\.conflictedTransitions).first(where: {+ $0.rootID == rootID && Set($0.expectedEventIDs) == currentIDs+ })+ guard let groupID = resolved?.groupID ?? conflict?.groupID,+ let characterID = resolved?.characterID ?? conflict?.characterID else {+ return refuse(.stale)+ }+ if let refusal = validateGroup(groupID) { return refuse(refusal) }+ if let refusal = try validateMember(characterID, chapterID: chapterID) {+ return refuse(refusal)+ }+ touchedChapters.formUnion(chain.filter { $0.workID == workID }.map(\.chapterID))+ let event = GroupTransitionFact(rootID: rootID, workID: workID,+ groupID: groupID, characterID: characterID,+ chapterID: chapterID, parentHeadIDs: expected, action: action)+ let row = try GroupTransition(fact: event, recordedAt: timestamp)+ context.insert(row); transitionRows.append(row)+ }+ }+ try before.finish(context: context, timestamp: timestamp)+ try Self.recordKnownChapterLinks(entryIDs: touchedChapters, context: context,+ timestamp: timestamp)+ return .committed(groupIDs: created)+ }++}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swiftindex 30b0ef7b..a79be53d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift@@ -120,6 +120,9 @@ extension LibraryRepository { diagnostics = refreshed setQuarantine(refreshed.quarantineMap()) + try invalidateGroupHistoryAfterImport()+ _ = try await reconcileGroupHistory()+ // Q46's second half: a reconcile trigger that arrived mid-import deferred // rather than interleaving with the chunk saves. It re-fires here, now // that the flag has dropped and the diagnoses describe the imported graph.@@ -473,6 +476,7 @@ extension LibraryRepository { if !payload.characters.isEmpty || !payload.suppressions.isEmpty || !payload.places.isEmpty || !payload.placeSuppressions.isEmpty || payload.carriesCoverage || !payload.associationEvents.isEmpty || !payload.pairNoteVersions.isEmpty+ || !payload.groups.isEmpty || !payload.groupFacts.isEmpty || !payload.groupTransitions.isEmpty || !associations.before.active.isEmpty { try mergeImportedRecords( payload, workTargets: workTargets, workRows: workRows,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swiftindex 4d18af5f..bff66dd5 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift@@ -170,6 +170,8 @@ extension LibraryRepository { entity(WorkCredit.self), entity(WorkDistinctPair.self), entity(NoEpisodeAction.self), entity(EntrySource.self), entity(AssociationEvent.self), entity(PairNoteVersion.self),+ entity(NamedCharacterGroup.self), entity(GroupFactEvent.self),+ entity(GroupTransition.self), ]), EmptyLibraryPhase(name: "5 works", entities: [entity(Work.self)]), EmptyLibraryPhase(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupHistory.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupHistory.swiftnew file mode 100644index 00000000..351465c7--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupHistory.swift@@ -0,0 +1,311 @@+import Foundation+import SwiftData++struct GroupHistoryReconciliationReport: Sendable {+ var selectedWorkIDs: [UUID] = []+ var scannedChapterIDs: [UUID] = []+ var batchSizes: [Int] = []+ var associationSaves = 0+}++private struct GroupHistoryCursor: Codable {+ var digest: String+ var nextIndex: Int+ var completed: Bool+ var chapterDigest: String? = nil+ var targetDigest: String? = nil+}++private struct GroupHistorySidecar: Codable {+ var works: [String: GroupHistoryCursor] = [:]++ static func read(_ url: URL) throws -> Self {+ guard FileManager.default.fileExists(atPath: url.path) else { return .init() }+ return try JSONDecoder().decode(Self.self, from: Data(contentsOf: url))+ }++ func write(_ url: URL) throws {+ try FileManager.default.createDirectory(at: url.deletingLastPathComponent(),+ withIntermediateDirectories: true)+ try JSONEncoder().encode(self).write(to: url, options: .atomic)+ }+}++extension LibraryRepository {+ /// An import can restore chapter/group rows with IDs already represented in+ /// the local completion sidecar. Forget that device-local cursor only after+ /// the import commits, then derive links from the resulting store again.+ func invalidateGroupHistoryAfterImport() throws {+ let url = configuration.groupHistoryURL+ if FileManager.default.fileExists(atPath: url.path) {+ try FileManager.default.removeItem(at: url)+ }+ }++ /// Compare event inventory before touching chapters. Only Works whose group+ /// digest moved open their chapter spine; a resumed pass commits at most 128+ /// saved chapters, then persists its cursor after the association save.+ @discardableResult+ func reconcileGroupHistory(maxBatches: Int? = nil) async throws -> GroupHistoryReconciliationReport {+ let sidecarURL = configuration.groupHistoryURL+ var sidecar = try GroupHistorySidecar.read(sidecarURL)+ let digests = try await withLockedContext(mode: .shared,+ operation: "inventorying character group history") { context -> [UUID: String] in+ let groups = try context.fetch(FetchDescriptor<NamedCharacterGroup>())+ let facts = try context.fetch(FetchDescriptor<GroupFactEvent>())+ let transitions = try context.fetch(FetchDescriptor<GroupTransition>())+ let transitionInventory = GroupSupportInventory.TransitionInventory(rows: transitions)+ let workIDs = Set(groups.map(\.workID) + facts.map(\.workID) ++ transitions.map(\.workID) + sidecar.works.keys.compactMap(UUID.init(uuidString:)))+ var result: [UUID: String] = [:]+ for workID in workIDs {+ let selectedGroupIDs = Set(groups.filter { $0.workID == workID }.map(\.id))+ let selectedFacts = facts.filter { $0.workID == workID }+ // Match the read projection's complete physical parent closure.+ // An inherited source fact can hydrate after this Work's cursor+ // completed even when its member targets did not change.+ let factRows = GroupSupportInventory.factRows(selected: selectedFacts,+ allRows: facts)+ let tokens = groups.filter { selectedGroupIDs.contains($0.id) }.map {+ "group/\($0.id)/\($0.workID)"+ } + factRows.map {+ "fact/\($0.id)/\($0.workID)/\($0.groupID)/\($0.payloadData.base64EncodedString())/\($0.parentHeadIDsData.base64EncodedString())/\($0.recordedAt.timeIntervalSinceReferenceDate.bitPattern)"+ } + transitionInventory.rows(workID: workID).map {+ "transition/\($0.id)/\($0.workID)/\($0.groupID)/\($0.characterID)/\($0.entryID)/\($0.payloadData.base64EncodedString())/\($0.parentHeadIDsData.base64EncodedString())/\($0.recordedAt.timeIntervalSinceReferenceDate.bitPattern)"+ }+ result[workID] = AssociationDigest.of("group-history/inventory/v1", tokens.sorted())+ }+ return result+ }+ var report = GroupHistoryReconciliationReport()+ let batchLimit = maxBatches ?? Int.max+ for workID in digests.keys.sorted(by: { $0.uuidString < $1.uuidString }) {+ guard let digest = digests[workID] else { continue }+ let key = workID.uuidString+ if sidecar.works[key]?.digest != digest {+ sidecar.works[key] = GroupHistoryCursor(digest: digest,+ nextIndex: 0, completed: false)+ try sidecar.write(sidecarURL)+ }+ let chapters = try await withLockedContext(mode: .shared,+ operation: "selecting changed Work group chapters") { context -> ([UUID], String)? in+ let rows = try context.fetch(FetchDescriptor<Work>(+ predicate: #Predicate { $0.id == workID }))+ guard let work = Self.workGroup(id: workID, rows: rows,+ types: try Self.workTypeDirectory(context: context)), !work.isTorn else {+ return nil+ }+ let projection = try GroupSupportInventory.projection(work: work,+ context: context)+ // Only current, coherently resolved transition heads require a+ // live record endpoint. Raw ancestors remain in the projection+ // so late causal parents are still validated, but a removed or+ // merged-away character must not stall unrelated reconciliation.+ let memberIDs = Array(Set(projection.groups.flatMap(\.transitions)+ .filter { $0.workID == workID && $0.action != .remove }+ .map(\.characterID)))+ let members = try CharacterRecord.rows(ids: memberIDs, context: context)+ let memberGroups = Self.recordGroups(members)+ guard memberIDs.allSatisfy({ id in+ guard let group = memberGroups[id], !group.isTorn else { return false }+ return group.rows.allSatisfy { $0.ownerWorkID == workID }+ }) else { return nil }+ let targetDigest = AssociationDigest.of("group-history/targets/v1",+ members.map { row in+ "\(row.id)/\(row.ownerWorkID?.uuidString ?? "")/\(row.name)/\(row.nameKey)/\(row.aliases.sorted().joined(separator: ","))"+ }.sorted())+ return (try GroupSupportInventory.chapters(work: work,+ context: context).map(\.id), targetDigest)+ }+ // A group event can hydrate before its Work. Keep the cursor owed,+ // and compare the saved spine on every retry: a chapter inserted+ // before the numeric offset must restart a bounded, idempotent pass.+ guard let (chapters, targetDigest) = chapters else { continue }+ let chapterDigest = AssociationDigest.of("group-history/spine/v1",+ chapters.map(\.uuidString))+ if sidecar.works[key]?.chapterDigest != chapterDigest ||+ sidecar.works[key]?.targetDigest != targetDigest {+ sidecar.works[key]?.chapterDigest = chapterDigest+ sidecar.works[key]?.targetDigest = targetDigest+ sidecar.works[key]?.nextIndex = 0+ sidecar.works[key]?.completed = false+ try sidecar.write(sidecarURL)+ }+ guard sidecar.works[key]?.completed == false else { continue }+ report.selectedWorkIDs.append(workID)+ guard !chapters.isEmpty else { continue }+ while let index = sidecar.works[key]?.nextIndex, index < chapters.count {+ guard report.batchSizes.count < batchLimit else { return report }+ let batch = Array(chapters[index..<min(index + 128, chapters.count)])+ let wrote = try await withLockedContext(mode: .exclusive,+ operation: "relinking changed Work group chapters") { context -> Bool in+ let before = try AssociationMutation.capture(context: context,+ workIDs: [workID], entryIDs: Set(batch))+ let timestamp = MillisecondInstant.quantize(clock.now())+ try before.finish(context: context, timestamp: timestamp)+ let retired = try Self.retireUnsupportedGroupRoots(workID: workID,+ entryIDs: Set(batch), context: context, timestamp: timestamp)+ let linked = try Self.recordKnownChapterLinks(entryIDs: Set(batch),+ context: context, timestamp: timestamp, groupOnly: true)+ let wrote = retired || linked+ if wrote {+ do { try saveStrategy.save(context) }+ catch { context.rollback(); throw error }+ }+ return wrote+ }+ if wrote { report.associationSaves += 1 }+ report.scannedChapterIDs += batch+ report.batchSizes.append(batch.count)+ sidecar.works[key]?.nextIndex = index + batch.count+ sidecar.works[key]?.completed = index + batch.count == chapters.count+ try sidecar.write(sidecarURL)+ }+ }+ return report+ }++ private static func retireUnsupportedGroupRoots(workID: UUID,+ entryIDs: Set<UUID>, context: ModelContext, timestamp: Date) throws -> Bool {+ let storage = try AssociationStorageInventory.read(context: context,+ workIDs: [workID], includeNotes: false)+ let pairs = storage.ledger.pairs.filter { entryIDs.contains($0.entryID) }+ guard !pairs.isEmpty else { return false }+ let endpoints = try AssociationEndpointInventory.read(context: context,+ pairs: pairs)+ let allGroups = try context.fetch(FetchDescriptor<NamedCharacterGroup>())+ let allFacts = try context.fetch(FetchDescriptor<GroupFactEvent>())+ let allTransitions = try context.fetch(FetchDescriptor<GroupTransition>())+ let connectedTransitions = GroupSupportInventory.TransitionInventory(+ rows: allTransitions).rows(workID: workID)+ let anchorIDs = Array(Set(connectedTransitions.compactMap {+ $0.transitionValue?.chapterID+ }))+ let anchorRows = try context.fetch(FetchDescriptor<Entry>(+ predicate: #Predicate { anchorIDs.contains($0.id) }))+ let validAnchorIDs = Set(Self.entryGroups(anchorRows,+ canonicalWorkIDs: [:]).compactMap { id, group -> UUID? in+ guard !group.isTorn, group.rows.allSatisfy({+ $0.work?.id == workID && AssociationEndpointInventory.eligible($0)+ }) else { return nil }+ return id+ })+ // This fold only needs canonical uncertainty, not chapter order. Give+ // it the bounded, verified anchors so a missing independent leave is+ // disputed without treating every healthy member as unresolved.+ let resolutionChapters = validAnchorIDs.sorted {+ $0.uuidString < $1.uuidString+ }.map { GroupChapter(id: $0, label: "") }+ let resolution = GroupRoster.project(workID: workID,+ chapters: resolutionChapters,+ groupRows: allGroups, factRows: allFacts,+ transitionRows: connectedTransitions)+ func coherent(_ groupID: UUID, spellingKey: String,+ characterID: UUID, transitionIDs: [UUID]) -> Bool {+ guard !resolution.unresolvedSpellings[groupID, default: []].contains(spellingKey),+ !resolution.disputedMembers[groupID, default: []].contains(characterID)+ else { return false }+ let groupRows = allGroups.filter { $0.id == groupID }+ guard !groupRows.isEmpty,+ groupRows.allSatisfy({ $0.workID == workID }) else { return false }+ let currentFacts = allFacts.filter {+ $0.groupID == groupID && $0.workID == workID+ }+ let factRows = GroupSupportInventory.factRows(selected: currentFacts,+ allRows: allFacts)+ guard !factRows.isEmpty,+ factRows.allSatisfy({ $0.factValue != nil &&+ ($0.workID != workID || $0.groupID == groupID) }),+ Dictionary(grouping: factRows, by: \.id).values.allSatisfy({ rows in+ guard let first = rows.first else { return false }+ return rows.allSatisfy { $0.workID == first.workID &&+ $0.groupID == first.groupID &&+ $0.payloadData == first.payloadData &&+ $0.parentHeadIDsData == first.parentHeadIDsData &&+ $0.recordedAt == first.recordedAt }+ }) else { return false }+ let factsByID = Dictionary(grouping: factRows, by: \.id)+ .compactMapValues { $0.first?.factValue }+ guard currentFacts.allSatisfy({+ GroupRoster.complete($0.id, in: factsByID,+ parents: { $0.parentHeadIDs })+ }) else { return false }+ let selectedTransitionIDs = Set(allTransitions.filter {+ $0.groupID == groupID && $0.workID == workID+ }.map(\.id))+ let supportIDs = Set(transitionIDs)+ let supportRoots = Set(connectedTransitions.filter {+ supportIDs.contains($0.id) && $0.workID == workID+ }.compactMap { $0.transitionValue?.rootID })+ let connectedIDs = Set(connectedTransitions.filter { row in+ supportRoots.contains(row.id) || row.transitionValue.map {+ supportRoots.contains($0.rootID)+ } == true+ }.map(\.id))+ let transitionRows = connectedTransitions.filter {+ connectedIDs.contains($0.id)+ }+ guard !supportRoots.isEmpty,+ supportIDs.isSubset(of: selectedTransitionIDs),+ transitionRows.allSatisfy({ $0.transitionValue != nil &&+ ($0.workID != workID || $0.groupID == groupID) }),+ Dictionary(grouping: transitionRows, by: \.id).values.allSatisfy({ rows in+ guard let first = rows.first else { return false }+ return rows.allSatisfy { $0.workID == first.workID &&+ $0.groupID == first.groupID &&+ $0.characterID == first.characterID &&+ $0.entryID == first.entryID && $0.payloadData == first.payloadData &&+ $0.parentHeadIDsData == first.parentHeadIDsData &&+ $0.recordedAt == first.recordedAt }+ }) else { return false }+ let transitionsByID = Dictionary(grouping: transitionRows, by: \.id)+ .compactMapValues { $0.first?.transitionValue }+ guard transitionsByID.values.allSatisfy({ value in+ guard let root = transitionsByID[value.rootID],+ root.rootID == root.id,+ GroupRoster.complete(value.id, in: transitionsByID,+ parents: { $0.parentHeadIDs }) else { return false }+ return value.id == value.rootID || GroupRoster.hasAncestor(+ value.id, ancestor: value.rootID, in: transitionsByID,+ parents: { $0.parentHeadIDs })+ }) else { return false }+ guard transitionsByID.values.allSatisfy({+ validAnchorIDs.contains($0.chapterID)+ }) else { return false }+ return true+ }+ var wrote = false+ for pair in pairs {+ guard endpoints.liveWorkIDs.contains(workID),+ let source = endpoints.sources[pair.entryID], source.workID == workID,+ let target = endpoints.targets[.init(kind: pair.kind,+ id: pair.recordID)], target.workID == workID else { continue }+ let current = endpoints.current(pair)+ let active = current.map {+ storage.ledger.activeAcceptanceIDs(for: $0)+ } ?? []+ let unsupported = storage.ledger.unretiredAcceptanceIDs(for: pair)+ .subtracting(active).filter { id in+ if case .group(let groupID, let spellingKey, let transitionIDs) =+ storage.ledger.acceptance(id)?.support {+ // A later independent transition can change proof IDs+ // without removing this chapter's group/spelling support.+ // Keep the older root and its authored note recoverable.+ if current?.groupSupports.contains(where: {+ $0.groupID == groupID && $0.spellingKey == spellingKey+ }) == true { return false }+ return coherent(groupID, spellingKey: spellingKey,+ characterID: pair.recordID,+ transitionIDs: transitionIDs)+ }+ return false+ }+ guard !unsupported.isEmpty else { continue }+ context.insert(try AssociationEvent(event: .init(payload: .retire(+ .init(pair: pair, acceptanceIDs: Array(unsupported)))),+ recordedAt: timestamp))+ wrote = true+ }+ return wrote+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupSuggestionSkip.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupSuggestionSkip.swiftnew file mode 100644index 00000000..2d3295ec--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupSuggestionSkip.swift@@ -0,0 +1,55 @@+import Foundation+import SwiftData++extension LibraryRepository {+ public func groupSuggestionSkips(workID: UUID) async throws -> Set<GroupSuggestionSkip> {+ try await withLockedContext(mode: .shared,+ operation: "reading skipped group suggestions") { context in+ try AssociationStorageInventory.read(context: context,+ workIDs: [workID], includeNotes: false).ledger.groupSuggestionSkips+ }+ }++ /// Skip is evidence-scoped rather than revision-scoped. A new sentence in+ /// the chapter does not resurrect the same group name or join quote.+ public func skipGroupSuggestion(_ skip: GroupSuggestionSkip,+ sourceFingerprint: String) async throws -> GroupEditOutcome {+ try await withLockedContext(mode: .exclusive,+ operation: "skipping group suggestion") { context in+ let chapterID = skip.chapterID+ let rows = try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate {+ $0.id == chapterID+ }))+ guard !rows.isEmpty, rows.allSatisfy({ $0.work?.id == skip.workID &&+ AssociationEndpointInventory.eligible($0) &&+ CharacterCoverageFingerprint.of($0.note) == sourceFingerprint }) else {+ return .refused(.stale)+ }+ let note = rows[0].note+ guard !RecordMentionGrounding.completeNameEvidence(names: [skip.groupKey],+ in: note).isEmpty else { return .refused(.stale) }+ if skip.kind == .join || skip.kind == .leave {+ guard let characterKey = skip.characterKey,+ note.precomposedStringWithCanonicalMapping.range(+ of: skip.evidenceKey.precomposedStringWithCanonicalMapping) != nil,+ !RecordMentionGrounding.completeNameEvidence(names: [skip.groupKey],+ in: skip.evidenceKey).isEmpty,+ !RecordMentionGrounding.completeNameEvidence(names: [characterKey],+ in: skip.evidenceKey).isEmpty else { return .refused(.stale) }+ } else if skip.characterKey != nil || skip.evidenceKey != skip.groupKey {+ return .refused(.invalidOperation)+ }+ let storage = try AssociationStorageInventory.read(context: context,+ workIDs: [skip.workID], includeNotes: false)+ if storage.ledger.groupSuggestionSkips.contains(skip) {+ return .committed(groupIDs: [])+ }+ context.insert(try AssociationEvent(event: .init(+ payload: .groupSuggestionSkip(skip)),+ recordedAt: MillisecondInstant.quantize(clock.now())))+ do { try saveStrategy.save(context) }+ catch { context.rollback(); throw error }+ return .committed(groupIDs: [])+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecognisedCharacters.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecognisedCharacters.swiftindex ef97a2b2..a157bdf3 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecognisedCharacters.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecognisedCharacters.swift@@ -7,14 +7,16 @@ extension LibraryRepository { /// 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)+ return try await commitRecognisedCharacter(request, restoration: nil,+ requiresAutomaticArbitration: true) } /// 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)+ return try await commitRecognisedCharacter(request, restoration: nil,+ requiresAutomaticArbitration: false) } private static func validateRecognisedCharacterAuthority(_ request: DecisionRequest, originalKind: RecordKind) throws {@@ -26,7 +28,9 @@ extension LibraryRepository { } } - private func commitRecognisedCharacter(_ request: DecisionRequest, restoration: SkippedCharacterLinkSnapshot?) async throws -> DecisionOutcome {+ private func commitRecognisedCharacter(_ request: DecisionRequest,+ restoration: SkippedCharacterLinkSnapshot?,+ requiresAutomaticArbitration: Bool) async throws -> DecisionOutcome { guard let key = request.reviewedKey else { throw LibraryRepositoryError.invalidInput(operation: "saving recognised character links", reason: "missing original key") }@@ -37,7 +41,8 @@ extension LibraryRepository { 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)+ let characterRows = try CharacterRecord.rows(of: works, context: context)+ let targets = Self.recordGroups(characterRows).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)@@ -51,6 +56,49 @@ extension LibraryRepository { return .refused(.reRouted(to: nil)) } if let refusal = Self.strictSourceRefusal(request, workRows: works, before: before) { return .refused(refusal) }+ // Automatic recognition must use the same complete-name arbitration+ // as the Save linker, against the final saved text and all current+ // kinds. A literal "Jake" inside "Team Jake" is not direct evidence.+ // Restoration is a separate explicit reader decision.+ if requiresAutomaticArbitration {+ let roster = try GroupSupportInventory.projection(work: work, context: context)+ let placeRows = try Place.rows(of: works, context: context)+ let characterClaims: [GroupNameClaim] = characterRows.flatMap { row in+ ([row.name, row.nameKey] + row.aliases).map {+ GroupNameClaim(kind: .character,+ id: GroupSupportInventory.characterClaimID, spelling: $0)+ }+ }+ let placeClaims: [GroupNameClaim] = placeRows.flatMap { row in+ ([row.name, row.nameKey] + row.aliases).map {+ GroupNameClaim(kind: .place,+ id: GroupSupportInventory.placeClaimID, spelling: $0)+ }+ }+ let groupClaims: [GroupNameClaim] = roster.groups.flatMap { group in+ ([group.name].compactMap { $0 } + group.aliases).map {+ GroupNameClaim(kind: .group, id: group.groupID, spelling: $0)+ }+ }+ let claims = characterClaims + placeClaims + groupClaims+ 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 ?? ""+ }+ let resolved = GroupReferenceResolver.resolve(note: text,+ chapterID: source.ref.entryID, claims: claims, roster: roster)+ let allowed = Set(request.mentions.first(where: {+ $0.entryID == source.ref.entryID+ })?.spellingKeys ?? [key.nameKey])+ guard resolved.mentions.contains(where: { mention in+ mention.kind == .character && allowed.contains(mention.spellingKey) &&+ RecordMatching.recognition(nameKey: mention.spellingKey,+ among: targets) == .unique(targetID)+ }) else { return .refused(.staleSource(source.ref)) }+ }+ } for source in request.sourceAuthority { let text: String switch source.ref {@@ -209,6 +257,7 @@ extension LibraryRepository { 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)+ return try await commitRecognisedCharacter(request, restoration: captured,+ requiresAutomaticArbitration: false) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordEditing.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordEditing.swiftindex 5b474d75..a1d63ccb 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordEditing.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordEditing.swift@@ -89,6 +89,9 @@ public enum RecordEditOperation: Sendable, Equatable { /// **commit** and retained thereafter (Q46), and creating clears a standing /// suppression of that key under its own kind (Q44, Req 3.2). case create(RecordDraft)+ /// The Work editor already gives a draft row an identity so a group+ /// transition in the same Save can name it before either row exists.+ case createIdentified(id: UUID, draft: RecordDraft) case update(basis: RecordEditBasis, draft: RecordDraft) /// Deletion suppresses the retained, current and alias keys and every /// deleted fact's triple (Q50, Req 3.3, Req 3.4).@@ -154,7 +157,7 @@ extension RecordEditOperation { /// source's; the destination is the other one by construction. internal var kind: RecordKind { switch self {- case .create(let draft): draft.kind+ case .create(let draft), .createIdentified(_, let draft): draft.kind case .update(let basis, _): basis.kind case .delete(let basis): basis.kind case .combine(let source, _): source.kind@@ -171,7 +174,7 @@ extension RecordEditOperation { /// The refusal where the operation's own kinds disagree, or nil. internal var kindMismatch: RecordEditRefusal? { switch self {- case .create, .delete:+ case .create, .createIdentified, .delete: nil case .update(let basis, let draft): draft.kind == basis.kind ? nil : .kindMismatch(recordID: basis.recordID)@@ -208,9 +211,35 @@ extension LibraryRepository { workID: UUID, operations: [RecordEditOperation] ) async throws -> RecordEditOutcome { guard !operations.isEmpty else { return .committed(recordIDs: []) }- return try await withLockedContext(+ let outcome: RecordEditOutcome = try await withLockedContext( mode: .exclusive, operation: "committing record edits" ) { context in+ let result = try self.applyRecordEdits(workID: workID, operations: operations, context: context)+ if case .committed = result { try self.saveStrategy.save(context) }+ return result+ }+ if case .committed = outcome { _ = try? await reconcileGroupHistory() }+ return outcome+ }++ internal func applyRecordEdits(workID: UUID, operations: [RecordEditOperation],+ context: ModelContext) throws -> RecordEditOutcome {+ guard !operations.isEmpty else { return .committed(recordIDs: []) }+ let plannedIDs = operations.compactMap { operation -> UUID? in+ if case .createIdentified(let id, _) = operation { return id }+ return nil+ }+ if Set(plannedIDs).count != plannedIDs.count,+ let repeated = plannedIDs.first(where: { id in plannedIDs.filter { $0 == id }.count > 1 }) {+ return .refused(.basisMismatch(recordID: repeated, name: ""))+ }+ if !plannedIDs.isEmpty {+ let existingCharacters = try CharacterRecord.rows(ids: plannedIDs, context: context)+ let existingPlaces = try Place.rows(ids: plannedIDs, context: context)+ if let occupied = (existingCharacters.map(\.recordID) + existingPlaces.map(\.recordID)).first {+ return .refused(.basisMismatch(recordID: occupied, name: ""))+ }+ } let workRows = try context.fetch( FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID })) guard !workRows.isEmpty else { return .refused(.workGone) }@@ -247,7 +276,7 @@ extension LibraryRepository { let selectedRecords = Set(operations.flatMap { operation -> [AssociationRecordAddress] in switch operation {- case .create: return []+ case .create, .createIdentified: 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):@@ -321,24 +350,38 @@ extension LibraryRepository { case .combine(let source, let target): associationRebinds.append(.recordMerge(workID: workID, kind: source.kind, fromRecordID: source.recordID, toRecordID: target.recordID))+ if source.kind == .character {+ try GroupRecordMutation.advance(workID: workID,+ from: source.recordID, to: target.recordID,+ context: context, recordedAt: timestamp)+ } 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):+ if basis.kind == .character {+ try GroupRecordMutation.advance(workID: workID,+ from: basis.recordID, to: nil,+ context: context, recordedAt: timestamp)+ }+ case .create(let draft), .createIdentified(_, let draft): for id in ids { additionalRecords.insert(.init(kind: draft.kind, id: id)) }- case .update, .delete: break+ case .delete(let basis):+ if basis.kind == .character {+ try GroupRecordMutation.advance(workID: workID,+ from: basis.recordID, to: nil,+ context: context, recordedAt: timestamp)+ }+ case .update: break } } } try associationBefore.finish(context: context, timestamp: timestamp, rebinds: associationRebinds, additionalRecords: additionalRecords)- try self.saveStrategy.save(context) return .committed(recordIDs: written)- } } /// Q108: verifies a basis on **first touch only**, and reports whether this@@ -377,10 +420,13 @@ extension LibraryRepository { context: ModelContext ) -> RecordEditOutcome { switch operation {- case .create(let draft):+ case .create(let draft), .createIdentified(_, let draft):+ let id: UUID+ if case .createIdentified(let planned, _) = operation { id = planned }+ else { id = UUID() } let key = RecordNameKey.normalize(draft.name) let row = Row.make(- id: UUID(), name: draft.name, nameKey: key, aliases: draft.aliases,+ id: id, name: draft.name, nameKey: key, aliases: draft.aliases, note: draft.note, facts: draft.facts, timestamp: timestamp, work: nil) context.insert(row) // Made unattached, inserted, then attached — the ordering a UUID
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swiftindex 2fe117e1..3a3e225d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift@@ -110,10 +110,10 @@ extension LibraryRepository { 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+ let candidates = try Self.workGroups(works, types: types).values+ .map { group -> ExtractionCandidate? in guard !group.isTorn else { return nil }- return Self.extractionCandidate(+ return try Self.extractionCandidate( group, characters: charactersByWork[group.id] ?? [], characterSuppressions: characterSuppressionsByWork[group.id] ?? [],@@ -121,8 +121,10 @@ extension LibraryRepository { 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)+ coherentRecordIDs: coherentRecordsByWork[group.id, default: [:]], ambiguousPendingSources: ambiguousPendingSources,+ context: context) }+ return candidates.compactMap { $0 } // Newest activity first, UUID as the tie-break so two devices // examine the same works in the same order. .sorted {@@ -143,14 +145,17 @@ extension LibraryRepository { placeSuppressions: [PlaceSuppression], ledger: AssociationLedgerInventory, activePairs: Set<AssociationPair>, decisions: [AssociationPair: [String: AssociationSpellingDecision]], endpoints: AssociationEndpointInventory,- coherentRecordIDs: [RecordKind: Set<UUID>], ambiguousPendingSources: Set<AssociationReviewSource>- ) -> ExtractionCandidate? {+ coherentRecordIDs: [RecordKind: Set<UUID>], ambiguousPendingSources: Set<AssociationReviewSource>,+ context: ModelContext+ ) throws -> 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 knownGroupNames = try GroupSupportInventory.projection(work: group, context: context)+ .groups.flatMap { summary in ([summary.name].compactMap { $0 }) + summary.aliases } let records: [RecordKind: [MatchTarget]] = [.character: characterHalf.targets, .place: placeHalf.targets] let suppressions: [RecordKind: SuppressionIndex] = [ .character: suppressionIndex(characterSuppressions), .place: suppressionIndex(placeSuppressions),@@ -167,7 +172,8 @@ extension LibraryRepository { ref: .genericNotes, text: genericNotes, fingerprint: CharacterCoverageFingerprint.of(genericNotes),- coveredFingerprint: carrier.genericNotesExtractionFingerprint, displayTitle: "Work note — no chapter"))+ coveredFingerprint: carrier.genericNotesExtractionFingerprint,+ displayTitle: "Work note — no chapter", knownGroupNames: knownGroupNames)) // 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)@@ -209,7 +215,7 @@ extension LibraryRepository { 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))+ isChapter: eligible, stableOrder: sources.count, knownGroupNames: knownGroupNames)) // 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))@@ -234,7 +240,8 @@ extension LibraryRepository { .place: suppressionIndex(placeSuppressions), ], mentionIndex: .init(workID: group.id, eligibleEntries: eligibleEntries, eligibilityByEntry: eligibilityByEntry, activePairs: activePairs, decisions: decisions, sourceGuards: sourceGuards,- coherentRecordIDs: coherentRecordIDs, coverageBases: coverageBases, pendingReviewReferences: pendingReferences))+ coherentRecordIDs: coherentRecordIDs, coverageBases: coverageBases, pendingReviewReferences: pendingReferences),+ knownGroupNames: knownGroupNames) } /// One kind's match targets and accepted fact triples, from its rows.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+SaveTimeKnownLinks.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+SaveTimeKnownLinks.swiftindex f0d3d1ef..a7db7124 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+SaveTimeKnownLinks.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+SaveTimeKnownLinks.swift@@ -6,7 +6,8 @@ extension LibraryRepository { /// 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 {+ static func recordKnownChapterLinks(entryIDs: Set<UUID>, context: ModelContext,+ timestamp: Date, groupOnly: Bool = false) 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 }@@ -15,16 +16,18 @@ extension LibraryRepository { 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>] = [:]+ var groupCandidates: [AssociationPair: [AssociationGroupSupport]] = [:] for (workID, work) in groups { struct Directory { let targets: [MatchTarget] let names: [String] let claimedKeys: Set<String>+ let claims: [GroupNameClaim] } 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: []) }+ guard !ids.isEmpty else { return .init(targets: [], names: [], claimedKeys: [], claims: []) } // 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))@@ -39,37 +42,77 @@ extension LibraryRepository { } } 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 kind: GroupMentionKind = Row.kind == .character ? .character : .place+ let claimID = kind == .character ? GroupSupportInventory.characterClaimID+ : GroupSupportInventory.placeClaimID+ let claims = records.values.flatMap { group in group.rows.flatMap { row in+ ([row.name, row.nameKey] + row.aliases).map { GroupNameClaim(kind: kind,+ id: claimID, spelling: $0) }+ } }+ return .init(targets: targets, names: names,+ claimedKeys: Set(names.map(RecordNameKey.normalize)), claims: claims) } let characters = try directory(CharacterRecord.self), places = try directory(Place.self)+ let roster = try GroupSupportInventory.projection(work: work, context: context)+ let groupClaims = roster.groups.flatMap { group -> [GroupNameClaim] in+ ([group.name].compactMap { $0 } + group.aliases).map {+ GroupNameClaim(kind: .group, id: group.groupID, spelling: $0)+ }+ } 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 resolved = GroupReferenceResolver.resolve(note: source.note, chapterID: source.id,+ claims: characters.claims + places.claims + groupClaims, roster: roster)+ for mention in resolved.mentions where mention.kind != .group && !groupOnly {+ let kind: RecordKind = mention.kind == .character ? .character : .place+ let targets = kind == .character ? characters.targets : places.targets+ guard case .unique(let id) = RecordMatching.recognition(nameKey: mention.spellingKey, among: targets)+ else { continue } let pair = AssociationPair(workID: workID, entryID: source.id, kind: kind, recordID: id)- candidates[pair, default: []].insert(evidence.key)+ candidates[pair, default: []].insert(mention.spellingKey)+ }+ for support in resolved.groupSupports {+ for member in support.members {+ let pair = AssociationPair(workID: workID, entryID: source.id,+ kind: .character, recordID: member)+ groupCandidates[pair, default: []] += resolved.associationSupports(for: member)+ } } } }- 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))+ let pairs = Set(candidates.keys).union(groupCandidates.keys)+ guard !pairs.isEmpty else { return false }+ let storage = try AssociationStorageInventory.read(context: context, workIDs: Set(pairs.map(\.workID)), includeNotes: false)+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs) 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 }+ for pair in pairs.sorted(by: { AssociationDigest.pairToken($0).lexicographicallyPrecedes(AssociationDigest.pairToken($1)) }) {+ let supports = Array(Set(groupCandidates[pair, default: []]))+ guard let current = endpoints.current(pair, groupSupports: supports), 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 supported = candidates[pair, default: []].intersection(receipt.evidence.map(\.key)).filter {+ !storage.ledger.isPairSupportSuppressed(pair: pair, support: .direct(spellingKey: $0))+ }+ if !supported.isEmpty && storage.ledger.activeAcceptanceIDs(for:+ .init(pair: current.pair, sourceFingerprint: current.sourceFingerprint,+ matchingFingerprint: current.matchingFingerprint, evidence: current.evidence)).isEmpty { let event = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: Array(supported))), validation: receipt) context.insert(try AssociationEvent(event: event, recordedAt: timestamp)); wrote = true }+ for support in supports {+ guard !storage.ledger.isPairSupportSuppressed(pair: pair,+ support: .group(groupID: support.groupID, spellingKey: support.spellingKey)) else { continue }+ let groupCurrent = AssociationCurrentPair(pair: current.pair,+ sourceFingerprint: current.sourceFingerprint,+ matchingFingerprint: current.matchingFingerprint, evidence: [],+ groupSupports: [support])+ guard storage.ledger.activeAcceptanceIDs(for: groupCurrent).isEmpty else { continue }+ let groupReceipt = storage.ledger.receipt(for: current, groupSupport: support)+ guard !groupReceipt.evidence.isEmpty else { continue }+ let acceptance = AssociationAcceptance(pair: pair, spellingKeys: [support.spellingKey],+ support: .group(groupID: support.groupID, spellingKey: support.spellingKey,+ transitionEventIDs: support.transitionEventIDs))+ context.insert(try AssociationEvent(event: .init(payload: .accept(acceptance),+ validation: groupReceipt), 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)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swiftindex dfe09dca..e5b2b4fb 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swift@@ -136,6 +136,35 @@ extension LibraryRepository { try await withLockedContext( mode: .exclusive, operation: "removing a site membership" ) { context in+ let diagnoses = try self.applySiteMembershipRemovals(workID: workID,+ removed: doomed, context: context)+ let remaining = try Self.fetchWorkGroup(id: workID, context: context)+ let affectedHostnames = doomed.union(remaining.rows.flatMap {+ $0.membershipValues.map(\.hostname)+ })+ do { try self.saveStrategy.save(context) } catch {+ throw LibraryRepositoryError.libraryUnavailable(+ operation: "removing a site membership",+ reason: String(describing: error))+ }+ // T-2291: publish what this commit's own validation left behind, for+ // every hostname it wrote to — the step the deletion commit and the+ // teaching commits take, and the one this path was missing.+ //+ // A removal is the repair for exactly the diagnosis the removed row+ // caused, so without this the hostname stays quarantined until the+ // next launch: the foreground refresh carries the tuple set forward+ // (`LibraryDiagnostics.union`) rather than re-deriving it, so a stale+ // entry never falls out on its own. A diagnosis the removal left+ // standing is re-recorded unchanged, so nothing it did not repair is+ // cleared.+ self.publishPostCommitDiagnoses(across: affectedHostnames, in: diagnoses)+ }+ }++ internal func applySiteMembershipRemovals(workID: UUID, removed doomed: Set<String>,+ context: ModelContext) throws -> [String: LibraryValidationError] {+ guard !doomed.isEmpty else { return [:] } let group = try Self.fetchWorkGroup(id: workID, context: context) for hostname in doomed.sorted() { guard group.rows.contains(where: { $0.membership(for: hostname) != nil }) else {@@ -202,24 +231,7 @@ extension LibraryRepository { "Removing the site produced an invalid library state on " + "\(introduced.hostname): \(introduced.diagnosis)") }- do { try self.saveStrategy.save(context) } catch {- throw LibraryRepositoryError.libraryUnavailable(- operation: "removing a site membership",- reason: String(describing: error))- }- // T-2291: publish what this commit's own validation left behind, for- // every hostname it wrote to — the step the deletion commit and the- // teaching commits take, and the one this path was missing.- //- // A removal is the repair for exactly the diagnosis the removed row- // caused, so without this the hostname stays quarantined until the- // next launch: the foreground refresh carries the tuple set forward- // (`LibraryDiagnostics.union`) rather than re-deriving it, so a stale- // entry never falls out on its own. A diagnosis the removal left- // standing is re-recorded unchanged, so nothing it did not repair is- // cleared.- self.publishPostCommitDiagnoses(across: hostnames, in: diagnoses)- }+ return diagnoses } /// Sets the name a site presents under, from its own settings screen.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swiftindex 54218ab4..6376a86e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift@@ -145,6 +145,7 @@ public struct WorkDetailPresentation: Sendable, Equatable { /// row ids it was folded from, which is what the credits editor writes back /// through so a hidden role survives a commit (Q32, Q52). public let credits: [CreditDisplay]+ public let characterGroups: [GroupSummary] public init( work: WorkSnapshot, pulse: RatingPulse, lastNotedURLString: String?,@@ -153,8 +154,9 @@ public struct WorkDetailPresentation: Sendable, Equatable { places: [WorkRecordPresentation] = [], captureOrder: [UUID: Int] = [:], links: [WorkLinkSnapshot] = [],- credits: [CreditDisplay] = []+ credits: [CreditDisplay] = [], characterGroups: [GroupSummary] = [] ) {+ self.characterGroups = characterGroups self.places = places self.credits = credits self.work = work@@ -338,7 +340,8 @@ extension LibraryRepository { captureOrder: captureOrder, titles: titles, dates: dates, keys: keys), captureOrder: captureOrder, links: links,- credits: credits[id])+ credits: credits[id],+ characterGroups: group.isTorn ? [] : try GroupSupportInventory.projection(work: group, context: context).groups) } } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetailEdit.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetailEdit.swiftnew file mode 100644index 00000000..cdbd12c6--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetailEdit.swift@@ -0,0 +1,137 @@+import Foundation+import SwiftData++/// The Work editor's one Save. Every mutation runs against the same locked+/// context and reaches the store through one save only after all checks pass.+public struct WorkDetailMetadataEdit: Sendable, Equatable {+ public let basis: WorkEditBasis+ public let draft: WorkMetadataDraft+ public let calendar: Calendar++ public init(basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar) {+ self.basis = basis+ self.draft = draft+ self.calendar = calendar+ }+}++public struct WorkDetailEditTransaction: Sendable, Equatable {+ public let workID: UUID+ public let metadata: WorkDetailMetadataEdit?+ public let recordOperations: [RecordEditOperation]+ public let linkOperations: [WorkLinkEditOperation]+ public let groupOperations: [GroupEditOperation]+ public let workURL: WorkURLContract?+ public let membershipRemovalHostnames: [String]++ public init(workID: UUID, metadata: WorkDetailMetadataEdit? = nil,+ recordOperations: [RecordEditOperation] = [],+ linkOperations: [WorkLinkEditOperation] = [],+ groupOperations: [GroupEditOperation] = [],+ workURL: WorkURLContract? = nil,+ membershipRemovalHostnames: [String] = []) {+ self.workID = workID+ self.metadata = metadata+ self.recordOperations = recordOperations+ self.linkOperations = linkOperations+ self.groupOperations = groupOperations+ self.workURL = workURL+ self.membershipRemovalHostnames = membershipRemovalHostnames+ }+}++public enum WorkDetailEditOutcome: Sendable, Equatable {+ case committed(receipt: MembershipWriteReceipt, recordIDs: [UUID], groupIDs: [UUID])+ case metadataRefused(MembershipWriteReceipt)+ case recordRefused(RecordEditRefusal)+ case groupRefused(GroupEditRefusal)+ case linkRefused(WorkLinkError)+ case urlRefused(WorkURLCommitOutcome)+}++extension LibraryRepository {+ public func commitWorkDetailEdit(_ request: WorkDetailEditTransaction) async throws+ -> WorkDetailEditOutcome {+ var validatedLinks: [WorkLinkEditOperation] = []+ do {+ for operation in request.linkOperations {+ switch operation {+ case .add(let other, let type):+ guard other != request.workID else { return .linkRefused(.selfLink) }+ validatedLinks.append(.add(otherWorkID: other, type: try LinkType.validate(type)))+ case .retype(let id, let type):+ validatedLinks.append(.retype(linkID: id, type: try LinkType.validate(type)))+ case .remove: validatedLinks.append(operation)+ }+ }+ } catch let refusal as WorkLinkError { return .linkRefused(refusal) }+ let outcome: WorkDetailEditOutcome = try await withLockedContext(mode: .exclusive,+ operation: "committing Work detail edit") { context in+ var committed = false+ defer { if !committed { Self.rollbackMembershipWrite(context) } }+ var urlDiagnoses: [String: LibraryValidationError]?+ if let url = request.workURL {+ guard url.basis.workID == request.workID else {+ return .urlRefused(.invalidated(reason: "Work URL targets another Work"))+ }+ let result = try self.applyWorkURL(url, context: context,+ postCommitDiagnoses: &urlDiagnoses)+ guard case .committed = result else { return .urlRefused(result) }+ }+ var receipt = MembershipWriteReceipt(outcome: .committed)+ if let metadata = request.metadata {+ receipt = try self.applyWorkMetadata(id: request.workID, basis: metadata.basis,+ draft: metadata.draft, calendar: metadata.calendar, context: context)+ guard receipt.outcome == .committed else { return .metadataRefused(receipt) }+ }+ let records = try self.applyRecordEdits(workID: request.workID,+ operations: request.recordOperations, context: context)+ let recordIDs: [UUID]+ switch records {+ case .committed(let ids): recordIDs = ids+ case .refused(let reason): return .recordRefused(reason)+ }+ if let refusal = try self.applyLinkEdits(workID: request.workID,+ operations: validatedLinks, context: context) {+ return .linkRefused(refusal)+ }+ let groups = try self.applyGroupEdits(workID: request.workID,+ operations: request.groupOperations, context: context)+ let groupIDs: [UUID]+ switch groups {+ case .committed(let ids): groupIDs = ids+ case .refused(let reason): return .groupRefused(reason)+ }+ var removalDiagnoses: [String: LibraryValidationError]?+ let removed = Set(request.membershipRemovalHostnames)+ if !removed.isEmpty {+ removalDiagnoses = try self.applySiteMembershipRemovals(workID: request.workID,+ removed: removed, context: context)+ }+ // `applySiteMembershipRemovals` validates the complete affected+ // hostname set and returns one diagnosis entry per hostname; reuse+ // those keys instead of re-fetching the Work and traversing its+ // membership relationship a second time.+ let removalHostnames = Set(removalDiagnoses.map { Array($0.keys) } ?? [])+ do { try self.saveStrategy.save(context) }+ catch {+ throw LibraryRepositoryError.libraryUnavailable(operation: "saving Work detail",+ reason: String(describing: error))+ }+ committed = true+ if let url = request.workURL, let urlDiagnoses {+ self.publishPostCommitDiagnoses(across: [url.basis.siteHostname.value],+ in: urlDiagnoses)+ }+ if let removalDiagnoses {+ self.publishPostCommitDiagnoses(across: removalHostnames, in: removalDiagnoses)+ }+ return .committed(receipt: receipt, recordIDs: recordIDs, groupIDs: groupIDs)+ }+ if case .committed = outcome,+ !request.groupOperations.isEmpty || !request.recordOperations.isEmpty {+ _ = try? await reconcileGroupHistory()+ }+ return outcome+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swiftindex 0ab9e6be..f7c7bcc2 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swift@@ -214,13 +214,22 @@ extension LibraryRepository { let refusal: WorkLinkError? = try await withLockedContext( mode: .exclusive, operation: "committing related-work links" ) { context in+ let refusal = try self.applyLinkEdits(workID: workID, operations: validated, context: context)+ if refusal == nil { try self.commit(context, operation: "committing related-work links") }+ return refusal+ }+ if let refusal { throw refusal }+ }++ internal func applyLinkEdits(workID: UUID, operations: [WorkLinkEditOperation],+ context: ModelContext) throws -> WorkLinkError? { let timestamp = MillisecondInstant.quantize(self.clock.now()) // The pairs this step has already staged, so a session that added // the same work twice is refused by the same sentence a stored // duplicate earns — a pending insert is not reliably visible to a // predicated fetch. var staged: Set<WorkPairKey> = []- for operation in validated {+ for operation in operations { switch operation { case .add(let otherWorkID, let type): let types = try Self.workTypeDirectory(context: context)@@ -265,10 +274,7 @@ extension LibraryRepository { context.delete(link) } }- try self.commit(context, operation: "committing related-work links") return nil- }- if let refusal { throw refusal } } // MARK: - Reading
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swiftindex 82a910f4..73822add 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift@@ -48,6 +48,30 @@ extension LibraryRepository { public func commitWorkURL(_ contract: WorkURLContract) async throws -> WorkURLCommitOutcome { try await withLockedContext(mode: .exclusive, operation: "committing Work URL") { context in+ var diagnoses: [String: LibraryValidationError]?+ let outcome = try self.applyWorkURL(contract, context: context,+ postCommitDiagnoses: &diagnoses)+ if case .committed = outcome {+ do { try self.saveStrategy.save(context) }+ catch {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<Site>())+ _ = try? context.fetch(FetchDescriptor<WorkSiteMembership>())+ throw LibraryRepositoryError.libraryUnavailable(+ operation: "atomically saving confirmed Work URL", reason: String(describing: error))+ }+ if let diagnoses {+ self.publishPostCommitDiagnoses(across: [contract.basis.siteHostname.value],+ in: diagnoses)+ }+ }+ return outcome+ }+ }++ internal func applyWorkURL(_ contract: WorkURLContract, context: ModelContext,+ postCommitDiagnoses: inout [String: LibraryValidationError]?) throws -> WorkURLCommitOutcome { let currentBasis: WorkURLBasis do { currentBasis = try Self.buildWorkURLBasis(@@ -183,26 +207,13 @@ extension LibraryRepository { reason: "Work URL change produced an invalid library state: \(introduced.diagnosis)" ) }- do {- try self.saveStrategy.save(context)- } catch {- context.rollback()- _ = try? context.fetch(FetchDescriptor<Work>())- _ = try? context.fetch(FetchDescriptor<Site>())- _ = try? context.fetch(FetchDescriptor<WorkSiteMembership>())- throw LibraryRepositoryError.libraryUnavailable(- operation: "atomically saving confirmed Work URL",- reason: String(describing: error)- )- } // T-2289: this commit is the repair for a wrong-host Work URL // diagnosis, so it publishes what it left behind — nil when the // write repaired the hostname, or the diagnosis it still carries // (T-1956 lets a commit land over one it did not introduce).- self.publishPostCommitDiagnoses(across: [hostname], in: diagnoses)+ postCommitDiagnoses = diagnoses workMergeLogger.debug("Committed confirmed Work URL for Work \(work.id.uuidString)") return .committed(workID: work.id)- } } // MARK: - Work Merge@@ -381,7 +392,8 @@ extension LibraryRepository { } public func commitMerge(_ contract: WorkMergeContract) async throws -> WorkMergeCommitOutcome {- try await withLockedContext(mode: .exclusive, operation: "committing Merge") { context in+ let result: WorkMergeCommitOutcome = try await withLockedContext(+ mode: .exclusive, operation: "committing Merge") { context in // 1. Refetch current basis let currentBasis: WorkMergeBasis // The basis build already fetched both sides' credit rows and folded@@ -688,6 +700,13 @@ extension LibraryRepository { Self.moveCharacters(from: sourceGroup, to: targetGroup, timestamp: timestamp) try Self.movePlaces( from: sourceGroup, to: targetGroup, timestamp: timestamp, context: context)+ do {+ try GroupWorkMerge.transfer(source: sourceGroup, targetWorkID: targetID,+ context: context, recordedAt: timestamp)+ } catch let refusal as GroupWorkMerge.Refusal {+ context.rollback()+ return .invalidated(reason: refusal.description)+ } // Delete the source group whole (Req 2.2): a group is deleted // entirely or not at all, and a proper subset left behind is the@@ -695,8 +714,6 @@ extension LibraryRepository { 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 // invalid result rolls back and reports instead of persisting damage.@@ -748,6 +765,8 @@ extension LibraryRepository { ) return .committed(targetID: targetID) }+ if case .committed = result { _ = try? await reconcileGroupHistory() }+ return result } /// Writes a `.toReadMatch` survivor's raw values to one target row, each
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex 7c12fbb3..f8b884d9 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -603,6 +603,7 @@ public actor LibraryRepository { // still ahead of it. Re-firing until quiet would be correct too — passes // are idempotent and a no-op pass is cheap — but it makes the recursion // depend on arrival timing for no property this does not already have.+ _ = try await reconcileGroupHistory() await refireDeferredReconcile() return outcome }@@ -1503,27 +1504,37 @@ public actor LibraryRepository { public func updateWorkWithMembershipReceipt( id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar ) async throws -> MembershipWriteReceipt {+ return try await withLockedContext(mode: .exclusive, operation: "updating Work") { context in+ let receipt = try self.applyWorkMetadata(id: id, basis: basis, draft: draft,+ calendar: calendar, context: context)+ guard receipt.outcome == .committed else {+ Self.rollbackMembershipWrite(context)+ return receipt+ }+ do { try saveStrategy.save(context) }+ catch {+ Self.rollbackMembershipWrite(context)+ throw LibraryRepositoryError.libraryUnavailable(+ operation: "atomically saving Work metadata", reason: String(describing: error))+ }+ return receipt+ }+ }++ internal func applyWorkMetadata(id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft,+ calendar: Calendar, context: ModelContext) throws -> MembershipWriteReceipt { guard !draft.displayTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw LibraryRepositoryError.invalidInput(operation: "updating Work", reason: "display title is blank") } let normalizedTags = Self.normalizeTags(draft.genreTags) let normalizedVerdict = Self.normalizeVerdict(draft.verdict)- // Req 2.2 and Q15: a position is finite and carries at most one fraction- // digit. The editor parses through `SeriesPosition.parse`, which already- // guarantees both — this refuses the value a caller built by hand, before- // any row is touched. if let membership = draft.membership { guard membership.position.isFinite,- membership.position == SeriesPosition.rounded(membership.position)- else {- throw LibraryRepositoryError.invalidInput(- operation: "updating Work",+ membership.position == SeriesPosition.rounded(membership.position) else {+ throw LibraryRepositoryError.invalidInput(operation: "updating Work", reason: "series position must be finite with at most one fraction digit") } }- return try await withLockedContext(mode: .exclusive, operation: "updating Work") { context in- var didCommit = false- defer { if !didCommit { Self.rollbackMembershipWrite(context) } } let group: WorkGroup switch try self.resolveWorkWriteTarget(id: id, basis: basis, context: context) { case .refused(let conflict): return MembershipWriteReceipt(outcome: .conflict(conflict))@@ -1666,18 +1677,9 @@ public actor LibraryRepository { } work.modifiedAt = timestamp }- do { try saveStrategy.save(context) }- catch {- throw LibraryRepositoryError.libraryUnavailable(- operation: "atomically saving Work metadata",- reason: String(describing: error)- )- }- didCommit = true return MembershipWriteReceipt(outcome: .committed, transitions: [ .init(addressedWorkIDs: [id], resolvedWorkID: group.id, before: initialMembership, after: Self.presentedMembership(of: group)) ])- } } /// Repoints **every** row of the addressed Entry group (Req 2.7). A manual
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Models.swift b/Packages/AsterismCore/Sources/AsterismCore/Models.swiftindex 5fcc4dd6..b7e8f33c 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 V21's, nested inside `AsterismSchemaV21`+// The live model classes are V22's, nested inside `AsterismSchemaV22` // (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 = 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+public typealias Entry = AsterismSchemaV22.Entry+public typealias Work = AsterismSchemaV22.Work+public typealias Site = AsterismSchemaV22.Site+public typealias TitlePattern = AsterismSchemaV22.TitlePattern+public typealias URLRulePattern = AsterismSchemaV22.URLRulePattern+public typealias WorkTypeEntity = AsterismSchemaV22.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 = AsterismSchemaV21.WorkSiteMembership+public typealias WorkSiteMembership = AsterismSchemaV22.WorkSiteMembership /// V8: a reader's "not the same work" over an unordered pair of Works (Q20).-public typealias WorkDistinctPair = AsterismSchemaV21.WorkDistinctPair+public typealias WorkDistinctPair = AsterismSchemaV22.WorkDistinctPair /// V11: a reader-named, ordered collection a Work belongs to at most once /// (`series-and-related-works` Decision 1).-public typealias Series = AsterismSchemaV21.Series+public typealias Series = AsterismSchemaV22.Series /// V11: an undirected, typed connection between two distinct Works /// (`series-and-related-works` Decision 5).-public typealias WorkLink = AsterismSchemaV21.WorkLink+public typealias WorkLink = AsterismSchemaV22.WorkLink /// V12: a person a work is credited to, a reader-managed directory record /// (`work-creators` Decision 2).-public typealias Creator = AsterismSchemaV21.Creator+public typealias Creator = AsterismSchemaV22.Creator /// V12: one entry in the ordered role list credits reference by identity /// (`work-creators` Decision 1).-public typealias CreatorRole = AsterismSchemaV21.CreatorRole+public typealias CreatorRole = AsterismSchemaV22.CreatorRole /// V12: one work-and-creator pairing, carrying the roles that creator holds on /// that work (`work-creators` Decision 6).-public typealias WorkCredit = AsterismSchemaV21.WorkCredit+public typealias WorkCredit = AsterismSchemaV22.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 = AsterismSchemaV21.Character-public typealias CharacterSuppression = AsterismSchemaV21.CharacterSuppression+public typealias CharacterRecord = AsterismSchemaV22.Character+public typealias CharacterSuppression = AsterismSchemaV22.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 = AsterismSchemaV21.Place+public typealias Place = AsterismSchemaV22.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 = AsterismSchemaV21.PlaceSuppression-public typealias EntrySource = AsterismSchemaV21.EntrySource-public typealias NoEpisodeAction = AsterismSchemaV21.NoEpisodeAction+public typealias PlaceSuppression = AsterismSchemaV22.PlaceSuppression+public typealias EntrySource = AsterismSchemaV22.EntrySource+public typealias NoEpisodeAction = AsterismSchemaV22.NoEpisodeAction /// The presentation-enum tolerance policy for the **model accessors**, in one /// place (Q2).@@ -137,7 +137,7 @@ enum JSONBlob { } } -extension AsterismSchemaV21 {+extension AsterismSchemaV22 { @Model public final class Entry {@@ -1770,7 +1770,7 @@ public final class PlaceSuppression { } } -} // extension AsterismSchemaV21+} // extension AsterismSchemaV22 /// 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/RecordMentionGrounding.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordMentionGrounding.swiftindex f2bbf986..99a76410 100644--- a/Packages/AsterismCore/Sources/AsterismCore/RecordMentionGrounding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/RecordMentionGrounding.swift@@ -25,9 +25,18 @@ public enum RecordMentionGrounding { } /// 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] {+ public static func completeNameEvidence(names: [String], in source: String) -> [AssociationEvidence] { evidence(names: names, in: source, completeNames: true) }+ /// Source ranges for complete, grounded names. Group/character/place span+ /// arbitration uses these same boundaries and capitalization rules rather+ /// than maintaining a second literal matcher.+ static func completeNameSpans(name: String, in source: String) -> [Range<String.Index>] {+ guard !name.isEmpty && name.count <= maximumNameLength &&+ !pronouns.contains(RecordNameKey.normalize(name)) else { return [] }+ return occurrenceRanges(of: name, in: source, completeNames: true)+ .filter { capitalised(String(source[$0])) }+ } /// 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] {@@ -50,12 +59,17 @@ public enum RecordMentionGrounding { !spelling.contains(where: \.isCased) || spelling.contains { $0.isCased && !$0.isLowercase } } private static func occurrences(of name: String, in source: String, completeNames: Bool = false) -> [String] {+ occurrenceRanges(of: name, in: source, completeNames: completeNames)+ .map { String(source[$0]) }+ }+ private static func occurrenceRanges(of name: String, in source: String,+ completeNames: Bool) -> [Range<String.Index>] { let needle = name.precomposedStringWithCanonicalMapping guard !needle.isEmpty else { return [] }- var from = source.startIndex, values: [String] = []+ var from = source.startIndex, values: [Range<String.Index>] = [] 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])) }+ if !completeNames || RecordNameBoundaries.contains(range, in: source) { values.append(range) } from = range.upperBound } return values
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift b/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swiftindex ced3c039..3efe4a13 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift@@ -37,12 +37,14 @@ public struct ShareCharacter: Sendable, Equatable, Identifiable { /// The note the work page shows for this character, trimmed of surrounding /// whitespace by the read; `""` where there is none. public let note: String+ public let memberships: [String] - public init(id: UUID, name: String, aliases: [String] = [], note: String = "") {+ public init(id: UUID, name: String, aliases: [String] = [], note: String = "", memberships: [String] = []) { self.id = id self.name = name self.aliases = aliases self.note = note+ self.memberships = memberships } } @@ -121,6 +123,7 @@ public enum ShareCharacterChips { if !character.note.isEmpty { parts.append(character.note) }+ parts.append(contentsOf: character.memberships) if parts.count == 1 { parts.append(emptyDetailText) }@@ -165,6 +168,7 @@ public struct ShareLastNote: Sendable, Equatable { /// duplicate both. public struct ShareWorkContext: Sendable, Equatable { public let characters: [ShareCharacter]+ public let groups: [ShareCharacter] /// The work's own notes, trimmed; `""` where the work has none, where the /// notes half of the read failed, and where no read has happened yet. public let workNote: String@@ -175,10 +179,11 @@ public struct ShareWorkContext: Sendable, Equatable { public let lastNote: ShareLastNote? public init(- characters: [ShareCharacter] = [], workNote: String = "",+ characters: [ShareCharacter] = [], groups: [ShareCharacter] = [], workNote: String = "", lastNote: ShareLastNote? = nil ) { self.characters = characters+ self.groups = groups self.workNote = workNote self.lastNote = lastNote }@@ -282,6 +287,19 @@ extension LibraryRepository { // both halves. No exclusion: the ranking needs the whole work, and the // notes half applies `excludingEntryID` where it selects (Q32). let allRows = works.flatMap(\.entryValues)+ let groupValues: [GroupSummary]+ if let work = workGroup(id: id, rows: works, types: try workTypeDirectory(context: context)), !work.isTorn {+ groupValues = try GroupSupportInventory.projection(work: work, context: context).groups+ } else { groupValues = [] }+ let characterNames = Dictionary(grouping: works.flatMap(\.characterValues), by: \.id)+ .compactMapValues { rows in rows.first?.name }+ let shareGroups = groupValues.map { group in+ ShareCharacter(id: group.groupID, name: group.name ?? "Unresolved group", aliases: group.aliases,+ note: group.members.isEmpty ? "No members" : "",+ memberships: group.members.compactMap { id, ranges in+ characterNames[id].map { GroupMembershipText.membership(name: $0, ranges: ranges) }+ }.sorted())+ } // Bucketed once, for both halves: the index below is one input per // logical entry, and the last-note selection walks the same buckets to // find the ones that could carry an answer.@@ -310,7 +328,8 @@ extension LibraryRepository { // trim nothing. return ShareCharacter( id: group.id, name: content.name, aliases: content.aliases,- note: content.note.trimmingCharacters(in: .whitespacesAndNewlines))+ note: content.note.trimmingCharacters(in: .whitespacesAndNewlines),+ memberships: GroupMembershipText.character(group.id, groups: groupValues)) } do {@@ -336,7 +355,7 @@ extension LibraryRepository { chapterSequence: currentChapterSequence, chapterTitle: currentChapterTitle) else { return ShareWorkContext(- characters: characters, workNote: workNote, lastNote: nil)+ characters: characters, groups: shareGroups, workNote: workNote, lastNote: nil) } // The same buckets the index was built from, read a second time —@@ -398,7 +417,7 @@ extension LibraryRepository { }?.0 guard let selected else { return ShareWorkContext(- characters: characters, workNote: workNote, lastNote: nil)+ characters: characters, groups: shareGroups, workNote: workNote, lastNote: nil) } let entry = try snapshot(selected)@@ -408,7 +427,7 @@ extension LibraryRepository { // capture title is unreachable as a heading (Decision 4). let title = entry.chapterTitle ?? entry.chapterSequence ?? "" return ShareWorkContext(- characters: characters,+ characters: characters, groups: shareGroups, workNote: workNote, lastNote: ShareLastNote( title: title.trimmingCharacters(in: .whitespacesAndNewlines),@@ -424,7 +443,7 @@ extension LibraryRepository { shareWorkContextLogger.debug( "Share work context: notes read failed — \(String(describing: error), privacy: .public)" )- return ShareWorkContext(characters: characters)+ return ShareWorkContext(characters: characters, groups: shareGroups) } }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionAssembler.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionAssembler.swiftindex 9ffbf0e0..e4009d5f 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionAssembler.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionAssembler.swift@@ -126,6 +126,13 @@ public enum CharacterExtractionAssembler { ) -> Survivor? { let recognition = RecordMatching.recognition(nameKey: key.nameKey, among: context.records(of: key.kind).map(\.matchTarget))+ // Existing group names and aliases are known record identities. A new+ // character with exactly that spelling is a model type collision; do+ // not create it. A real character record with that same name remains+ // reviewable, and duplicate/torn matches remain unresolved for the+ // reader rather than being silently discarded.+ if key.kind == .character, context.knownGroupNameKeys.contains(key.nameKey),+ recognition == .noMatch { return nil } let unresolved: Bool if noteFirst && key.kind == .character { switch recognition {
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBridge.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBridge.swiftindex 75cec052..45a91042 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBridge.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBridge.swift@@ -50,7 +50,8 @@ extension CharacterExtractionContext { } self.init( records: records, acceptedFacts: acceptedFacts,- suppressedNameKeys: suppressedNameKeys, suppressedFacts: suppressedFacts, mentionIndex: candidate.mentionIndex)+ suppressedNameKeys: suppressedNameKeys, suppressedFacts: suppressedFacts,+ mentionIndex: candidate.mentionIndex, knownGroupNameKeys: candidate.knownGroupNameKeys) } } @@ -72,7 +73,8 @@ extension ExtractionCandidate { ExtractionSource( workID: workID, workTitle: displayTitle, source: $0.ref, text: $0.text, fingerprint: $0.fingerprint, mentionEligibilityDigest: $0.mentionEligibilityDigest,- displayTitle: $0.displayTitle, capturedAt: $0.capturedAt, isChapter: $0.isChapter, stableOrder: $0.stableOrder)+ displayTitle: $0.displayTitle, capturedAt: $0.capturedAt, isChapter: $0.isChapter,+ stableOrder: $0.stableOrder, knownGroupNames: knownGroupNames) } }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionTypes.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionTypes.swiftindex ff1d49b1..07e002c4 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionTypes.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionTypes.swift@@ -26,11 +26,15 @@ public struct ExtractionSource: Sendable, Equatable { public var capturedAt: Date? public var isChapter: Bool public var stableOrder: Int+ /// Current Work group names and aliases, used only to distinguish a group+ /// mention from a newly named character. This is on-device model context.+ public var knownGroupNames: [String] public var attemptFingerprint: String { mentionEligibilityDigest ?? fingerprint } public init(workID: UUID, workTitle: String, source: SourceRef, text: String, fingerprint: String, mentionEligibilityDigest: String? = nil,- displayTitle: String = "", capturedAt: Date? = nil, isChapter: Bool = false, stableOrder: Int = 0) {+ displayTitle: String = "", capturedAt: Date? = nil, isChapter: Bool = false,+ stableOrder: Int = 0, knownGroupNames: [String] = []) { self.workID = workID self.workTitle = workTitle self.source = source@@ -39,6 +43,7 @@ public struct ExtractionSource: Sendable, Equatable { self.mentionEligibilityDigest = mentionEligibilityDigest self.displayTitle = displayTitle; self.capturedAt = capturedAt self.isChapter = isChapter; self.stableOrder = stableOrder+ self.knownGroupNames = knownGroupNames } } @@ -193,6 +198,10 @@ public struct CharacterExtractionContext: Sendable, Equatable { public var suppressedNameKeys: [RecordKind: Set<String>] /// Fact triples the reader unticked or deleted. public var suppressedFacts: [RecordKind: Set<RecordFactIdentity>]+ /// Normalized names and aliases of groups already recorded for this Work.+ /// A matching name is not a new character unless it resolves to an+ /// existing character record.+ public var knownGroupNameKeys: Set<String> /// **Per kind, every slot stated — the only initialiser.** ///@@ -205,12 +214,14 @@ public struct CharacterExtractionContext: Sendable, Equatable { acceptedFacts: [RecordKind: Set<RecordFactIdentity>], suppressedNameKeys: [RecordKind: Set<String>], suppressedFacts: [RecordKind: Set<RecordFactIdentity>],- mentionIndex: AssociationMentionIndex = .empty) {+ mentionIndex: AssociationMentionIndex = .empty,+ knownGroupNameKeys: Set<String> = []) { self.mentionIndex = mentionIndex self.records = records self.acceptedFacts = acceptedFacts self.suppressedNameKeys = suppressedNameKeys self.suppressedFacts = suppressedFacts+ self.knownGroupNameKeys = knownGroupNameKeys } public func records(of kind: RecordKind) -> [ExistingCharacter] { records[kind] ?? [] }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/ExtractionResult.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/ExtractionResult.swiftindex 40379ddc..361123f4 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/ExtractionResult.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/ExtractionResult.swift@@ -82,9 +82,53 @@ public struct ExtractionResult: Sendable, Equatable { @Guide(description: "Named places in the story this note mentions. Empty if it names none.") public var places: [ExtractedPlace] - public init(characters: [ExtractedCharacter] = [], places: [ExtractedPlace] = []) {+ /// Reader-reviewed group names and chapter-anchored transitions from the+ /// same model answer. Model output alone never writes them to the library.+ public var groups: [ExtractedGroup]+ public var groupJoins: [ExtractedGroupJoin]+ public var groupLeaves: [ExtractedGroupLeave]++ public init(characters: [ExtractedCharacter] = [], places: [ExtractedPlace] = [],+ groups: [ExtractedGroup] = [], groupJoins: [ExtractedGroupJoin] = [],+ groupLeaves: [ExtractedGroupLeave] = []) { self.characters = characters self.places = places+ self.groups = groups+ self.groupJoins = groupJoins+ self.groupLeaves = groupLeaves+ }+}++@Generable+public struct ExtractedGroup: Sendable, Equatable {+ @Guide(description: "A named group of story characters, spelled exactly as this chapter note names it. Do not infer unnamed groups.")+ public var name: String+ public init(name: String = "") { self.name = name }+}++@Generable+public struct ExtractedGroupJoin: Sendable, Equatable {+ @Guide(description: "The group name exactly as this chapter note spells it.")+ public var groupName: String+ @Guide(description: "The named character who joins the group in this chapter note.")+ public var characterName: String+ @Guide(description: "The exact words in the chapter note that say the character joins the group, copied verbatim.")+ public var quote: String+ public init(groupName: String = "", characterName: String = "", quote: String = "") {+ self.groupName = groupName; self.characterName = characterName; self.quote = quote+ }+}++@Generable+public struct ExtractedGroupLeave: Sendable, Equatable {+ @Guide(description: "The group name exactly as this chapter note spells it.")+ public var groupName: String+ @Guide(description: "The named character who leaves the group in this chapter note.")+ public var characterName: String+ @Guide(description: "The exact words in the chapter note that say the character leaves the group, copied verbatim.")+ public var quote: String+ public init(groupName: String = "", characterName: String = "", quote: String = "") {+ self.groupName = groupName; self.characterName = characterName; self.quote = quote } } @@ -103,13 +147,23 @@ public struct NamedExtractionResult: Sendable, Equatable { 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] = []) {+ @Guide(description: "Named story-character groups explicitly named in this chapter note. Empty if none.")+ public var groups: [ExtractedGroup]+ @Guide(description: "Explicit statements in this chapter note that a named character joins a named group. Empty if none.")+ public var groupJoins: [ExtractedGroupJoin]+ @Guide(description: "Explicit statements in this chapter note that a named character leaves a named group. Empty if none.")+ public var groupLeaves: [ExtractedGroupLeave]+ public init(characters: [NamedExtractionEntity] = [], places: [NamedExtractionEntity] = [],+ groups: [ExtractedGroup] = [], groupJoins: [ExtractedGroupJoin] = [],+ groupLeaves: [ExtractedGroupLeave] = []) { self.characters = characters self.places = places+ self.groups = groups; self.groupJoins = groupJoins; self.groupLeaves = groupLeaves } public var legacyValue: ExtractionResult { ExtractionResult(characters: characters.map { .init(name: $0.name) },- places: places.map { .init(name: $0.name) })+ places: places.map { .init(name: $0.name) },+ groups: groups, groupJoins: groupJoins, groupLeaves: groupLeaves) } }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/FoundationCharacterExtractionModelClient.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/FoundationCharacterExtractionModelClient.swiftindex 881fee9f..b269bf67 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/FoundationCharacterExtractionModelClient.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/FoundationCharacterExtractionModelClient.swift@@ -44,10 +44,11 @@ public struct FoundationCharacterExtractionModelClient: CharacterExtractionModel // MARK: - Prompting - /// Names-only extraction; saved source prose is displayed directly and never- /// synthesized into facts or annotations.+ /// Names-only character/place extraction plus exact chapter-grounded group+ /// claims. Saved prose is displayed directly and never synthesized into facts. static let instructions = """- You extract named story characters and named places from a reader's private \+ You extract named story characters and named places, and named groups of \+ characters from a reader's private \ note about one chapter of a serial story. The note is informal and may be \ short. @@ -71,22 +72,38 @@ public struct FoundationCharacterExtractionModelClient: CharacterExtractionModel no places, return an empty list of places. A pronoun is never a character. Do not infer a name from a pronoun.+ A group is a named collection of story characters, such as "Team Loser". \+ Report a group only when its full name appears in the note. Do not turn \+ unnamed crowds or organisations into groups. A join or leave requires an \+ explicit sentence in the chapter note saying a named character joins or \+ leaves a named group. Copy the exact words as the transition quote. Do not \+ infer membership from merely mentioning the character and group together, \+ or from later absence. Do not report transitions from general Work notes. Spell each name exactly as the note spells it, character for character.- Copy names verbatim. Return names only: no facts, summaries, paraphrases,- quotes, annotations or other prose. A character or place the note only+ Copy names verbatim. Return names only for characters and places: no facts, \+ summaries, paraphrases or annotations. The join or leave quote is the sole exception. \+ A character or place the note only mentions by name is reported with no facts. """ /// The source as the model sees it: the work's display title and one- /// source's text, and nothing else (Req 1.4, Q42).+ /// source's text plus the Work's group-name context needed to classify+ /// group mentions (Req 1.4, Q42; T-2491 acceptance follow-up). static func prompt(for source: ExtractionSource) -> String {- """+ let groupNames = source.knownGroupNames.isEmpty ? "None recorded." :+ source.knownGroupNames.joined(separator: ", ")+ return """ The story is titled "\(source.workTitle)". \(Self.sourceDescription(source.source)): \(source.text) + Known group names and aliases already recorded for this Work: \(groupNames)+ Do not report a known group as a character solely because the note mentions it. \+ A same-name character is still reportable when the note explicitly identifies one.+ List the named story characters and the named places this note mentions, \- returning names only.+ along with named groups. For a chapter note, include explicit joins and \+ leaves with a verbatim quote from the note. Return character and place names only otherwise. """ }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/GroupExtractionGrounding.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/GroupExtractionGrounding.swiftnew file mode 100644index 00000000..5b603af8--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/GroupExtractionGrounding.swift@@ -0,0 +1,99 @@+import AsterismCore+import Foundation++/// A model claim grounded in one saved chapter revision. Approval still has to+/// recheck this revision and the current Work, group and character identities.+public struct GroundedGroupSuggestion: Sendable, Equatable, Identifiable {+ public enum Kind: Sendable, Equatable { case create, join, leave }+ public let kind: Kind+ public let workID: UUID+ public let chapterID: UUID+ public let sourceFingerprint: String+ public let groupName: String+ public let characterName: String?+ public let quote: String?+ public let sourceEvidence: ProposalSourceEvidence+ public init(kind: Kind, workID: UUID, chapterID: UUID, sourceFingerprint: String,+ groupName: String, characterName: String?, quote: String?,+ sourceEvidence: ProposalSourceEvidence) {+ self.kind = kind+ self.workID = workID+ self.chapterID = chapterID+ self.sourceFingerprint = sourceFingerprint+ self.groupName = groupName+ self.characterName = characterName+ self.quote = quote+ self.sourceEvidence = sourceEvidence+ }+ public var id: String {+ [workID.uuidString, chapterID.uuidString, sourceFingerprint,+ kind == .create ? "create" : kind == .join ? "join" : "leave",+ RecordNameKey.normalize(groupName), characterName.map(RecordNameKey.normalize) ?? ""]+ .joined(separator: "/")+ }+ public var skipIdentity: GroupSuggestionSkip {+ .init(workID: workID, chapterID: chapterID,+ kind: kind == .create ? .create : kind == .join ? .join : .leave,+ groupKey: RecordNameKey.normalize(groupName),+ characterKey: characterName.map(RecordNameKey.normalize),+ evidenceKey: quote ?? RecordNameKey.normalize(groupName))+ }+}++/// Mechanical provenance gate for the model's group output. A generic note or+/// prose that merely names a person and group cannot create a join proposal.+public enum GroupExtractionGrounding {+ public static func ground(_ result: ExtractionResult,+ from source: ExtractionSource) -> [GroundedGroupSuggestion] {+ guard source.isChapter, let chapterID = source.source.entryID else { return [] }+ let evidence = ProposalSourceEvidence(source: source,+ spellings: result.groups.map(\.name) + result.groupJoins.map(\.groupName) ++ result.groupLeaves.map(\.groupName))+ var values: [GroundedGroupSuggestion] = [], seen: Set<String> = []+ func groundedName(_ name: String, in text: String) -> Bool {+ let spelling = name.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !spelling.isEmpty, spelling.count <= 100 else { return false }+ return !RecordMentionGrounding.completeNameEvidence(names: [spelling], in: text).isEmpty+ }+ for group in result.groups {+ let name = group.name.trimmingCharacters(in: .whitespacesAndNewlines)+ guard groundedName(name, in: source.text) else { continue }+ let value = GroundedGroupSuggestion(kind: .create, workID: source.workID,+ chapterID: chapterID, sourceFingerprint: source.fingerprint,+ groupName: name, characterName: nil, quote: nil, sourceEvidence: evidence)+ if seen.insert(value.id).inserted { values.append(value) }+ }+ for join in result.groupJoins {+ let name = join.groupName.trimmingCharacters(in: .whitespacesAndNewlines)+ let character = join.characterName.trimmingCharacters(in: .whitespacesAndNewlines)+ let quote = join.quote.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !quote.isEmpty,+ source.text.precomposedStringWithCanonicalMapping.range(+ of: quote.precomposedStringWithCanonicalMapping) != nil,+ groundedName(name, in: quote), groundedName(character, in: quote),+ groundedName(name, in: source.text), groundedName(character, in: source.text)+ else { continue }+ let value = GroundedGroupSuggestion(kind: .join, workID: source.workID,+ chapterID: chapterID, sourceFingerprint: source.fingerprint,+ groupName: name, characterName: character, quote: quote,+ sourceEvidence: evidence)+ if seen.insert(value.id).inserted { values.append(value) }+ }+ for leave in result.groupLeaves {+ let name = leave.groupName.trimmingCharacters(in: .whitespacesAndNewlines)+ let character = leave.characterName.trimmingCharacters(in: .whitespacesAndNewlines)+ let quote = leave.quote.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !quote.isEmpty,+ source.text.precomposedStringWithCanonicalMapping.range(+ of: quote.precomposedStringWithCanonicalMapping) != nil,+ groundedName(name, in: quote), groundedName(character, in: quote),+ groundedName(name, in: source.text), groundedName(character, in: source.text)+ else { continue }+ let value = GroundedGroupSuggestion(kind: .leave, workID: source.workID,+ chapterID: chapterID, sourceFingerprint: source.fingerprint,+ groupName: name, characterName: character, quote: quote, sourceEvidence: evidence)+ if seen.insert(value.id).inserted { values.append(value) }+ }+ return values+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismTestSupport/TestFixtures.swift b/Packages/AsterismCore/Sources/AsterismTestSupport/TestFixtures.swiftindex 13ef0834..d9915bc5 100644--- a/Packages/AsterismCore/Sources/AsterismTestSupport/TestFixtures.swift+++ b/Packages/AsterismCore/Sources/AsterismTestSupport/TestFixtures.swift@@ -115,7 +115,8 @@ public nonisolated enum TestFixtures { /// ordinary case, so every case written before V12 keeps describing a /// work with no credits — and the detail's own `credits` is what the /// editor seeds its draft from, never `work.credits`.- credits: [CreditDisplay] = []+ credits: [CreditDisplay] = [],+ characterGroups: [GroupSummary] = [] ) -> WorkDetailPresentation { let rows = chapterRows ?? work.entries.map { entry in WorkChapterRow(@@ -135,7 +136,8 @@ public nonisolated enum TestFixtures { ?? work.entries.max(by: { $0.lastSharedAt < $1.lastSharedAt })?.rawURLString, chapterRows: rows, links: links,- credits: credits)+ credits: credits,+ characterGroups: characterGroups) } /// One related-work link, stated where a case is *about* the section.
diff --git a/Packages/AsterismCore/Sources/ConstellationKit/ConstellationRecipes.swift b/Packages/AsterismCore/Sources/ConstellationKit/ConstellationRecipes.swiftindex 2901e8fb..ef2e9f8d 100644--- a/Packages/AsterismCore/Sources/ConstellationKit/ConstellationRecipes.swift+++ b/Packages/AsterismCore/Sources/ConstellationKit/ConstellationRecipes.swift@@ -1,4 +1,7 @@ import SwiftUI+#if canImport(UIKit)+import UIKit+#endif // MARK: - Shared treatment constants @@ -398,3 +401,268 @@ public struct ConstellationSegmentedControl<Value: Hashable>: View { .accessibilityAddTraits(isSelected ? [.isSelected] : []) } }++/// A Liquid Glass segmented picker for mutually-exclusive choices.+/// When a horizontal native control cannot fit without compressing its labels,+/// a stacked SwiftUI capsule fallback uses the same selection palette; that+/// adaptive fallback does not have the native control's glass material.+public struct ConstellationLiquidGlassSegmentedControl<Value: Hashable>: View {+ private let values: [Value]+ @Binding private var selection: Value+ private let containerLabel: String+ private let title: (Value) -> String+ private let identifier: (Value) -> String+ private let controlIdentifier: String++ public init(+ values: [Value],+ selection: Binding<Value>,+ containerLabel: String,+ title: @escaping (Value) -> String,+ identifier: @escaping (Value) -> String,+ controlIdentifier: String+ ) {+ self.values = values+ self._selection = selection+ self.containerLabel = containerLabel+ self.title = title+ self.identifier = identifier+ self.controlIdentifier = controlIdentifier+ }++ public var body: some View {+ #if canImport(UIKit)+ ViewThatFits(in: .horizontal) {+ UIKitLiquidGlassSegmentedControl(+ values: values,+ selection: $selection,+ containerLabel: containerLabel,+ title: title,+ identifier: identifier,+ controlIdentifier: controlIdentifier)+ .fixedSize(horizontal: true, vertical: false)+ .frame(minHeight: 44)++ VStack(alignment: .leading, spacing: 0) {+ ForEach(values, id: \.self) { value in+ Button {+ selection = value+ } label: {+ Text(title(value))+ .font(.caption.weight(.semibold))+ .lineLimit(1)+ .fixedSize(horizontal: true, vertical: false)+ .foregroundStyle(+ selection == value+ ? AsterismColors.cyan : AsterismColors.secondaryText)+ .frame(maxWidth: .infinity, minHeight: 44)+ .background {+ if selection == value {+ Capsule()+ .fill(AsterismColors.selectedMarkFill)+ .overlay {+ Capsule().strokeBorder(+ AsterismColors.selectedMarkBorder, lineWidth: 1)+ }+ .frame(height: 32)+ }+ }+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityIdentifier(identifier(value))+ .accessibilityAddTraits(selection == value ? [.isSelected] : [])+ }+ }+ .background {+ RoundedRectangle(cornerRadius: AsterismLayout.cardRadius, style: .continuous)+ .fill(AsterismColors.cardFill)+ .overlay {+ RoundedRectangle(+ cornerRadius: AsterismLayout.cardRadius, style: .continuous)+ .strokeBorder(AsterismColors.cardBorder, lineWidth: 1)+ }+ .allowsHitTesting(false)+ }+ .accessibilityElement(children: .contain)+ .accessibilityLabel(containerLabel)+ .accessibilityIdentifier(controlIdentifier)+ }+ #else+ Picker(containerLabel, selection: $selection) {+ ForEach(values, id: \.self) { value in+ Text(title(value))+ .tag(value)+ .accessibilityIdentifier(identifier(value))+ }+ }+ .pickerStyle(.segmented)+ .controlSize(.large)+ .tint(AsterismColors.cyan)+ .frame(minHeight: 44)+ .labelsHidden()+ .accessibilityLabel(containerLabel)+ .accessibilityIdentifier(controlIdentifier)+ #endif+ }+}++enum SegmentedAccessibilityFrameLayout {+ static func frame(+ index: Int,+ count: Int,+ width: CGFloat,+ height: CGFloat,+ isRightToLeft: Bool+ ) -> CGRect {+ guard count > 0, (0..<count).contains(index) else { return .zero }+ let visualIndex = isRightToLeft ? count - index - 1 : index+ return CGRect(x: CGFloat(visualIndex) * width, y: 0, width: width, height: height)+ }+}++#if canImport(UIKit)+@MainActor+private final class CyanAccessibleSegmentedControl: UISegmentedControl {+ private var optionLabels: [String] = []+ private var optionIdentifiers: [String] = []+ private var optionElements: [OptionElement] = []++ func configureAccessibility(labels: [String], identifiers: [String]) {+ optionLabels = labels+ optionIdentifiers = identifiers+ if optionElements.count != labels.count {+ optionElements = labels.indices.map { OptionElement(index: $0, container: self) }+ }+ refreshOptionElements()+ }++ override func layoutSubviews() {+ super.layoutSubviews()+ refreshOptionElements()+ }++ override var intrinsicContentSize: CGSize {+ let systemSize = super.intrinsicContentSize+ return CGSize(width: systemSize.width, height: max(systemSize.height, 44))+ }++ override func accessibilityElementCount() -> Int { optionLabels.count }++ override func accessibilityElement(at index: Int) -> Any? {+ guard optionElements.indices.contains(index) else { return nil }+ return optionElements[index]+ }++ override func index(ofAccessibilityElement element: Any) -> Int {+ guard let option = element as? OptionElement,+ let index = optionElements.firstIndex(of: option) else { return NSNotFound }+ return index+ }++ fileprivate func activateOption(at index: Int) -> Bool {+ guard optionLabels.indices.contains(index) else { return false }+ selectedSegmentIndex = index+ refreshOptionElements()+ sendActions(for: .valueChanged)+ UIAccessibility.post(notification: .layoutChanged, argument: self)+ return true+ }++ private func refreshOptionElements() {+ guard optionLabels.count == optionIdentifiers.count,+ optionElements.count == optionLabels.count else { return }+ let width = bounds.width / CGFloat(max(optionElements.count, 1))+ let isRightToLeft = effectiveUserInterfaceLayoutDirection == .rightToLeft+ for index in optionElements.indices {+ let element = optionElements[index]+ element.accessibilityLabel = optionLabels[index]+ element.accessibilityIdentifier = optionIdentifiers[index]+ element.accessibilityTraits = index == selectedSegmentIndex ? [.button, .selected] : [.button]+ element.accessibilityFrameInContainerSpace = SegmentedAccessibilityFrameLayout.frame(+ index: index,+ count: optionElements.count,+ width: width,+ height: bounds.height,+ isRightToLeft: isRightToLeft)+ }+ }++ private final class OptionElement: UIAccessibilityElement {+ let index: Int+ weak var owner: CyanAccessibleSegmentedControl?++ init(index: Int, container: CyanAccessibleSegmentedControl) {+ self.index = index+ self.owner = container+ super.init(accessibilityContainer: container)+ }++ @MainActor override func accessibilityActivate() -> Bool {+ owner?.activateOption(at: index) ?? false+ }+ }+}++/// Native segmented control with the same soft selected wash and adaptive cyan+/// label used by the SwiftUI capsule recipe. Keep styling on this instance;+/// never use UIAppearance.+private struct UIKitLiquidGlassSegmentedControl<Value: Hashable>: UIViewRepresentable {+ let values: [Value]+ @Binding var selection: Value+ let containerLabel: String+ let title: (Value) -> String+ let identifier: (Value) -> String+ let controlIdentifier: String++ func makeCoordinator() -> Coordinator { Coordinator(self) }++ func makeUIView(context: Context) -> CyanAccessibleSegmentedControl {+ let control = CyanAccessibleSegmentedControl(items: values.map(title))+ control.selectedSegmentTintColor = UIColor(AsterismColors.selectedMarkFill)+ control.setTitleTextAttributes(+ [.foregroundColor: UIColor(AsterismColors.cyan)], for: .selected)+ control.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)),+ for: .valueChanged)+ control.accessibilityLabel = containerLabel+ control.accessibilityIdentifier = controlIdentifier+ control.isAccessibilityElement = false+ control.selectedSegmentIndex = values.firstIndex(of: selection) ?? UISegmentedControl.noSegment+ control.configureAccessibility(labels: values.map(title), identifiers: values.map(identifier))+ return control+ }++ func updateUIView(_ control: CyanAccessibleSegmentedControl, context: Context) {+ context.coordinator.parent = self+ if control.numberOfSegments != values.count {+ control.removeAllSegments()+ for (index, value) in values.enumerated() {+ control.insertSegment(withTitle: title(value), at: index, animated: false)+ }+ } else {+ for (index, value) in values.enumerated() {+ control.setTitle(title(value), forSegmentAt: index)+ }+ }+ control.selectedSegmentTintColor = UIColor(AsterismColors.selectedMarkFill)+ control.setTitleTextAttributes(+ [.foregroundColor: UIColor(AsterismColors.cyan)], for: .selected)+ control.accessibilityLabel = containerLabel+ control.accessibilityIdentifier = controlIdentifier+ control.isAccessibilityElement = false+ control.selectedSegmentIndex = values.firstIndex(of: selection) ?? UISegmentedControl.noSegment+ control.configureAccessibility(labels: values.map(title), identifiers: values.map(identifier))+ }++ @MainActor final class Coordinator: NSObject {+ var parent: UIKitLiquidGlassSegmentedControl++ init(_ parent: UIKitLiquidGlassSegmentedControl) { self.parent = parent }++ @MainActor @objc func changed(_ sender: UISegmentedControl) {+ guard parent.values.indices.contains(sender.selectedSegmentIndex) else { return }+ parent.selection = parent.values[sender.selectedSegmentIndex]+ }+ }+}+#endif
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationGroupSupportTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationGroupSupportTests.swiftnew file mode 100644index 00000000..2d3c5c51--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationGroupSupportTests.swift@@ -0,0 +1,181 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Typed group association support")+struct AssociationGroupSupportTests {+ private let pair = AssociationPair(workID: UUID(), entryID: UUID(),+ kind: .character, recordID: UUID())+ private let groupID = UUID()+ private let joinID = UUID()+ private func current(_ evidence: [AssociationEvidence] = []) -> AssociationCurrentPair {+ .init(pair: pair, sourceFingerprint: "saved-source", matchingFingerprint: "current-character",+ evidence: evidence)+ }+ private var group: AssociationGroupSupport {+ .init(groupID: groupID, spellingKey: "team jake", spelling: "Team Jake",+ transitionEventIDs: [joinID])+ }+ private func groupRoot(_ current: AssociationCurrentPair) -> AssociationLedgerEvent {+ let acceptance = AssociationAcceptance(pair: pair, spellingKeys: [group.spellingKey],+ support: .group(groupID: groupID, spellingKey: group.spellingKey,+ transitionEventIDs: [joinID]))+ let raw = AssociationLedgerEvent(payload: .accept(acceptance))+ return raw.validated(by: AssociationLedgerInventory(events: [raw])+ .receipt(for: current, groupSupport: group))+ }++ @Test("A group-only root validates against source, character, group and transition proof")+ func completeGroupReceipt() {+ let state = current()+ let root = groupRoot(state)+ let ledger = AssociationLedgerInventory(events: [root])+ #expect(ledger.activeAcceptanceIDs(for: state).isEmpty)+ #expect(ledger.activeAcceptanceIDs(for: state, groupSupports: [group]) == [root.id])+ let changedRoster = AssociationGroupSupport(groupID: groupID, spellingKey: "team jake",+ spelling: "Team Jake", transitionEventIDs: [UUID()])+ #expect(ledger.activeAcceptanceIDs(for: state, groupSupports: [changedRoster]).isEmpty)+ let changedSource = AssociationCurrentPair(pair: pair, sourceFingerprint: "edited-source",+ matchingFingerprint: "current-character", evidence: [])+ #expect(ledger.activeAcceptanceIDs(for: changedSource, groupSupports: [group]).isEmpty)+ }++ @Test("A typed group root cannot borrow a legacy direct receipt")+ func groupCannotUseDirectReceipt() {+ let state = current([.init(key: "team jake", spelling: "Team Jake")])+ let raw = AssociationLedgerEvent(payload: .accept(.init(pair: pair,+ spellingKeys: ["team jake"], support: .group(groupID: groupID,+ spellingKey: "team jake", transitionEventIDs: [joinID]))))+ let forged = raw.validated(by: AssociationLedgerInventory(events: [raw])+ .receipt(for: state))+ let ledger = AssociationLedgerInventory(events: [forged])+ #expect(ledger.activeAcceptanceIDs(for: state).isEmpty)+ #expect(ledger.activeAcceptanceIDs(for: state, groupSupports: [group]).isEmpty)+ }++ @Test("A V22 typed direct root must name a key in the current direct evidence")+ func typedDirectKeyMismatch() {+ let state = current([.init(key: "bjorn", spelling: "Bjorn")])+ let raw = AssociationLedgerEvent(payload: .accept(.init(pair: pair,+ spellingKeys: ["jake"], support: .direct(spellingKey: "jake"))))+ let forged = raw.validated(by: AssociationLedgerInventory(events: [raw])+ .receipt(for: state))+ #expect(AssociationLedgerInventory(events: [forged])+ .activeAcceptanceIDs(for: state).isEmpty)+ }++ @Test("Standing rejection suppresses group support until explicitly acknowledged")+ func rejectedGroupSpelling() {+ let state = current()+ let old = groupRoot(state)+ let rejection = AssociationLedgerEvent(payload: .reject(.init(pair: pair,+ spellingKeys: [group.spellingKey])))+ let blocked = AssociationLedgerInventory(events: [old, rejection])+ #expect(blocked.activeAcceptanceIDs(for: state, groupSupports: [group]).isEmpty)+ let raw = AssociationLedgerEvent(payload: .accept(.init(pair: pair,+ spellingKeys: [group.spellingKey],+ reconsideredRejectionIDs: [rejection.id],+ support: .group(groupID: groupID, spellingKey: group.spellingKey,+ transitionEventIDs: [joinID]))))+ let basis = AssociationLedgerInventory(events: [old, rejection, raw])+ let acknowledged = raw.validated(by: basis.receipt(for: state, groupSupport: group))+ let after = AssociationLedgerInventory(events: [old, rejection, acknowledged])+ #expect(after.activeAcceptanceIDs(for: state, groupSupports: [group]) ==+ [acknowledged.id])+ }++ @Test("Independent direct and group roots publish one pair until both lose support")+ func directAndGroupUnion() {+ let direct = current([.init(key: "jake", spelling: "Jake")])+ let old = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["jake"])))+ let directRoot = old.validated(by: AssociationLedgerInventory(events: [old]).receipt(for: direct))+ let groupRoot = groupRoot(direct)+ let ledger = AssociationLedgerInventory(events: [directRoot, groupRoot])+ #expect(ledger.activeAcceptanceIDs(for: direct, groupSupports: [group]) ==+ [directRoot.id, groupRoot.id])+ #expect(ledger.activeAcceptanceIDs(for: direct, groupSupports: []) == [directRoot.id])+ #expect(ledger.activeAcceptanceIDs(for: current(), groupSupports: [group]) == [groupRoot.id])+ #expect(ledger.activeAcceptanceIDs(for: current(), groupSupports: []).isEmpty)+ }++ @Test("Two group roots remain independently valid when one is retired")+ func twoGroupsAndRetirement() {+ let state = current()+ let first = groupRoot(state)+ let secondSupport = AssociationGroupSupport(groupID: UUID(), spellingKey: "other team",+ spelling: "Other Team", transitionEventIDs: [UUID()])+ let secondValue = AssociationLedgerEvent(payload: .accept(.init(pair: pair,+ spellingKeys: [secondSupport.spellingKey],+ support: .group(groupID: secondSupport.groupID,+ spellingKey: secondSupport.spellingKey,+ transitionEventIDs: secondSupport.transitionEventIDs))))+ let second = secondValue.validated(by: AssociationLedgerInventory(events: [secondValue])+ .receipt(for: state, groupSupport: secondSupport))+ let both = AssociationLedgerInventory(events: [first, second])+ #expect(both.activeAcceptanceIDs(for: state,+ groupSupports: [group, secondSupport]) == [first.id, second.id])+ let retired = AssociationLedgerEvent(payload: .retire(.init(pair: pair,+ acceptanceIDs: [first.id])))+ let after = AssociationLedgerInventory(events: [first, second, retired])+ #expect(after.activeAcceptanceIDs(for: state,+ groupSupports: [group, secondSupport]) == [second.id])+ }++ @Test("An unsupported group root detaches its authored note without deleting exact text")+ func noteRecovery() {+ let state = current()+ let root = groupRoot(state)+ let ledger = AssociationLedgerInventory(events: [root])+ let note = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id],+ text: " authored note ")+ let notes = AssociationNoteFold(notes: [note], ledger: ledger)+ #expect(notes.textHeads(for: pair,+ activeAcceptanceIDs: ledger.activeAcceptanceIDs(for: state, groupSupports: [group]))+ .map(\.text) == [" authored note "])+ #expect(notes.detachedTextHeads(activeAcceptanceIDs: ledger.activeAcceptanceIDs(+ for: state, groupSupports: [])).map(\.text) == [" authored note "])+ }++ @Test("V21 direct acceptance JSON keeps its legacy shape")+ func oldDirectEncoding() throws {+ let old = AssociationAcceptance(pair: pair, spellingKeys: ["jake"])+ let data = try JSONBlob.encode(old)+ let json = try #require(String(data: data, encoding: .utf8))+ #expect(!json.contains("support"))+ #expect(try JSONBlob.decode(AssociationAcceptance.self, from: data).support == nil)+ let receipt = AssociationLedgerInventory(events: []).receipt(for: current([+ .init(key: "jake", spelling: "Jake")]))+ let receiptData = try JSONBlob.encode(receipt)+ #expect(!String(decoding: receiptData, as: UTF8.self).contains("groupSupport"))+ #expect(try JSONBlob.decode(AssociationValidationReceipt.self,+ from: receiptData) == receipt)+ }++ @Test("A group-only pair passes the real endpoint gate only with saved complete evidence")+ func groupOnlyEndpoint() throws {+ let schema = Schema(versionedSchema: AsterismSchemaV22.self)+ let container = try ModelContainer(for: schema, configurations: [+ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)])+ let context = ModelContext(container)+ let work = Work(id: pair.workID, displayTitle: "Story", timestamp: .distantPast)+ let entry = Entry(id: pair.entryID, captureTitle: "Chapter 5",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: .distantPast, note: "Team Loser gathers.")+ try entry.authorTarget(.init(kind: .chapter))+ entry.work = work+ let person = CharacterRecord(id: pair.recordID, name: "Bjorn",+ nameKey: "bjorn", work: work)+ context.insert(work); context.insert(entry); context.insert(person)+ try context.save()+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: [pair])+ #expect(endpoints.current(pair) == nil)+ let support = AssociationGroupSupport(groupID: groupID, spellingKey: "team loser",+ spelling: "Team Loser", transitionEventIDs: [joinID])+ #expect(endpoints.current(pair, groupSupports: [support])?.groupSupports == [support])+ let stale = AssociationGroupSupport(groupID: groupID, spellingKey: "team loser",+ spelling: "Missing Team", transitionEventIDs: [joinID])+ #expect(endpoints.current(pair, groupSupports: [stale]) == nil)+ withExtendedLifetime(container) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationIntegrationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationIntegrationTests.swiftindex 491c8009..4bc67008 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationIntegrationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationIntegrationTests.swift@@ -110,6 +110,125 @@ struct AssociationIntegrationTests { #expect(!after.evidence.contains { $0.spelling == "Alice" || $0.spelling == "Nova" }) withExtendedLifetime(fixture) {} }+ @Test func removeAfterDirectReceiptRefreshSuppressesEveryCurrentAliasUntilRestore() async throws {+ let firstNote = "Alice arrives."+ let refreshedNote = "Alice, Ali, and Ally arrive."+ let (fixture, ids) = try await fixture(note: firstNote,+ aliases: ["Ali", "Ally"])+ let repository = fixture.repository+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: ids.character)+ #expect(try await repository.commitDecision(decision(ids,+ note: firstNote)) == .committed(recordID: ids.character))+ let original = try #require(try await repository.chapterAssociations(+ entryID: ids.entry).first(where: { $0.pair == pair })?+ .activeAcceptanceIDs.first)+ let noteText = "Exact Alice association note"+ let noteBasis = try #require(try await repository.associationNoteBasis(pair: pair))+ #expect(try await repository.saveAssociationNote(basis: noteBasis,+ text: noteText) == .committed)+ let entry = try await repository.entry(id: ids.entry)+ #expect(try await repository.updateEntry(id: ids.entry,+ basis: .init(entry: entry), note: refreshedNote,+ rating: nil) == .committed)+ let refreshed = try #require(try await repository.chapterAssociations(+ entryID: ids.entry).first(where: { $0.pair == pair }))+ #expect(refreshed.activeAcceptanceIDs == [original])+ #expect(Set(refreshed.evidence.map(\.key)) == ["alice", "ali", "ally"])+ let immutableKeys = try await repository.withLockedContext(mode: .shared,+ operation: "checking original direct acceptance keys") { context in+ try AssociationStorageInventory.read(context: context,+ workIDs: [ids.work], includeNotes: false).ledger+ .acceptance(original)?.spellingKeys+ }+ #expect(immutableKeys == ["alice"])++ #expect(try await repository.removeChapterAssociation(pair: pair))+ #expect(try await repository.chapterAssociations(entryID: ids.entry)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs.isEmpty == true)+ for _ in 0..<2 {+ let unchanged = try await repository.entry(id: ids.entry)+ #expect(try await repository.updateEntry(id: ids.entry,+ basis: .init(entry: unchanged), note: refreshedNote,+ rating: nil) == .committed)+ #expect(try await repository.chapterAssociations(entryID: ids.entry)+ .first(where: { $0.pair == pair })?+ .activeAcceptanceIDs.isEmpty == true)+ }+ #expect(try await repository.restoreChapterAssociation(pair: pair))+ let restored = try #require(try await repository.chapterAssociations(+ entryID: ids.entry).first(where: { $0.pair == pair }))+ #expect(restored.activeAcceptanceIDs == [original])+ #expect(try #require(try await repository.associationNoteBasis(+ pair: pair)).heads.map(\.text) == [noteText])+ withExtendedLifetime(fixture) {}+ }+ @Test func groupOnlyRemoveDoesNotSuppressLaterGenuineDirectMention() async throws {+ let fixture = try await M5Fixture()+ let workID = UUID(), entryID = UUID(), characterID = UUID()+ let groupID = UUID(), transitionID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding group-only Jake mention") { context in+ let work = Work(id: workID, displayTitle: "Jake's book",+ timestamp: M5Fixture.epoch)+ let entry = Entry(id: entryID, captureTitle: "Chapter 1",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Team Jake returns.")+ try entry.authorTarget(.init(kind: .chapter, designation: "1"))+ context.insert(work); context.insert(entry)+ entry.work = work+ LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch)+ context.insert(CharacterRecord(id: characterID, name: "Jake",+ nameKey: "jake", work: work))+ context.insert(NamedCharacterGroup(id: groupID, workID: workID))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: workID, operation: .create(name: "Team Jake")),+ recordedAt: M5Fixture.epoch))+ context.insert(try GroupTransition(fact: .init(id: transitionID,+ rootID: transitionID, workID: workID, groupID: groupID,+ characterID: characterID, chapterID: entryID,+ action: .join), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let repository = fixture.repository+ let pair = AssociationPair(workID: workID, entryID: entryID,+ kind: .character, recordID: characterID)+ let originalEntry = try await repository.entry(id: entryID)+ #expect(try await repository.updateEntry(id: entryID,+ basis: .init(entry: originalEntry), note: originalEntry.note,+ rating: nil) == .committed)+ let groupRoot = try #require(try await repository.chapterAssociations(+ entryID: entryID).first(where: { $0.pair == pair })?+ .activeAcceptanceIDs.first)+ let supportAndDirectKeys = try await repository.withLockedContext(mode: .shared,+ operation: "checking nested direct evidence under group-only root") { context in+ let storage = try AssociationStorageInventory.read(context: context,+ workIDs: [workID], includeNotes: false)+ let endpoints = try AssociationEndpointInventory.read(context: context,+ pairs: [pair])+ let current = try #require(endpoints.current(pair))+ return (storage.ledger.acceptance(groupRoot)?.support,+ storage.ledger.receipt(for: current).evidence.map(\.key))+ }+ guard case .some(.group) = supportAndDirectKeys.0 else {+ Issue.record("Expected a group-only acceptance for Team Jake")+ return+ }+ #expect(supportAndDirectKeys.1.contains("jake"))+ #expect(try await repository.removeChapterAssociation(pair: pair))+ #expect(try await repository.chapterAssociations(entryID: entryID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs.isEmpty == true)+ let changed = try await repository.entry(id: entryID)+ #expect(try await repository.updateEntry(id: entryID,+ basis: .init(entry: changed), note: "Jake returns.",+ rating: nil) == .committed)+ let later = try #require(try await repository.chapterAssociations(+ entryID: entryID).first(where: { $0.pair == pair }))+ #expect(later.activeAcceptanceIDs.count == 1)+ #expect(!later.activeAcceptanceIDs.contains(groupRoot))+ withExtendedLifetime(fixture) {}+ } @Test func staleMissingEntryAcceptRefusesBeforeFactsOrAliases() async throws { let (fixture, ids) = try await fixture() var request = decision(ids)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationLedgerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationLedgerTests.swiftindex 39f419d6..53458784 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationLedgerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationLedgerTests.swift@@ -57,6 +57,62 @@ import Testing #expect(inventory.isSuppressed(pair: pair, spellingKey: "alice")) #expect(inventory.activeAcceptanceIDs(for: state(other)).isEmpty) }+ @Test func pairCorrectionSuppressesOnlyCapturedSupportUntilExplicitAcknowledgement() {+ let current = state(pair)+ let direct = AssociationPairSupportKey.direct(spellingKey: "alice")+ let groupID = UUID()+ let group = AssociationPairSupportKey.group(groupID: groupID, spellingKey: "team alice")+ let correction = AssociationLedgerEvent(payload: .pairCorrection(.init(pair: pair, supports: [direct, group])))+ let rejected = AssociationLedgerInventory(events: [correction])+ #expect(rejected.isPairSupportSuppressed(pair: pair, support: direct))+ #expect(rejected.isPairSupportSuppressed(pair: pair, support: group))+ #expect(!rejected.isPairSupportSuppressed(pair: pair,+ support: .group(groupID: UUID(), spellingKey: "team alice")))+ #expect(rejected.activeAcceptanceIDs(for: current).isEmpty)++ let acknowledgement = AssociationLedgerEvent(payload: .pairCorrectionAcknowledgement(+ .init(pair: pair, correctionIDs: [correction.id])))+ let restored = AssociationLedgerInventory(events: [acknowledgement, correction])+ #expect(!restored.isPairSupportSuppressed(pair: pair, support: direct))+ #expect(!restored.isPairSupportSuppressed(pair: pair, support: group))+ #expect(restored.pairCorrectionIDs(pair: pair).isEmpty)+ }+ @Test func pairCorrectionAcknowledgementCannotClearAnotherPair() {+ let correction = AssociationLedgerEvent(payload: .pairCorrection(.init(pair: pair,+ supports: [.direct(spellingKey: "alice")])))+ let other = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let acknowledgement = AssociationLedgerEvent(payload: .pairCorrectionAcknowledgement(+ .init(pair: other, correctionIDs: [correction.id])))+ let inventory = AssociationLedgerInventory(events: [acknowledgement, correction])+ #expect(inventory.invalidIDs.contains(acknowledgement.id))+ #expect(inventory.isPairSupportSuppressed(pair: pair, support: .direct(spellingKey: "alice")))+ }+ @Test func pairCorrectionSuppressesEverySupportCapturedByALegacyDirectRoot() {+ let current = state(pair, spellings: ["Alice", "A. L."])+ let root = accepted(current)+ let correction = AssociationLedgerEvent(payload: .pairCorrection(.init(pair: pair, supports: [+ .direct(spellingKey: "alice"), .direct(spellingKey: "a. l.")+ ])))+ let inventory = AssociationLedgerInventory(events: [root, correction])+ #expect(inventory.activeAcceptanceIDs(for: current).isEmpty)+ }+ @Test func pairCorrectionAndAcknowledgementReplayUnderReorderedAndDuplicateDelivery() throws {+ let correction = AssociationLedgerEvent(payload: .pairCorrection(.init(pair: pair,+ supports: [.direct(spellingKey: "alice"), .group(groupID: work, spellingKey: "team alice")])))+ let acknowledgement = AssociationLedgerEvent(payload: .pairCorrectionAcknowledgement(+ .init(pair: pair, correctionIDs: [correction.id])))+ let encoded = try JSONEncoder().encode(correction)+ let decoded = try JSONDecoder().decode(AssociationLedgerEvent.self, from: encoded)+ #expect(decoded == correction)+ for events in [[correction, acknowledgement], [acknowledgement, correction],+ [correction, acknowledgement, correction]] {+ let inventory = AssociationLedgerInventory(events: events)+ #expect(inventory.invalidIDs.isDisjoint(with: [correction.id, acknowledgement.id]))+ #expect(!inventory.isPairSupportSuppressed(pair: pair, support: .direct(spellingKey: "alice")))+ #expect(!inventory.isPairSupportSuppressed(pair: pair,+ support: .group(groupID: work, spellingKey: "team alice")))+ }+ } @Test func conflictingImmutableCopiesQuarantineIdentity() { let original = accepted(state(pair)) let contradiction = AssociationLedgerEvent(id: original.id, payload: .invalidate(.work(work)))
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swiftindex 89c8c55a..69fda77a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swift@@ -6,7 +6,7 @@ import Testing @Suite("Association physical storage", .serialized) struct AssociationStorageTests { private func container() throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) return try ModelContainer(for: schema, configurations: [ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swiftindex 13f88409..90ab1ae6 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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 78f21b83..8bbee4d5 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismV21MigrationPlan.self,+ migrationPlan: AsterismV22MigrationPlan.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -715,7 +715,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV21MigrationPlan.self,+ migrationPlan: AsterismV22MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -758,7 +758,7 @@ private func createReadySiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -767,7 +767,7 @@ private func createReadySiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV21MigrationPlan.self,+ migrationPlan: AsterismV22MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -802,7 +802,7 @@ private func createReadyDuplicateSiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -811,7 +811,7 @@ private func createReadyDuplicateSiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV21MigrationPlan.self,+ migrationPlan: AsterismV22MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swiftindex 9d9f7279..9ce87fc9 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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("(\(BackupV20Document.formatVersion)/\(BackupV20Document.schemaVersion))"))+ #expect(reason.contains("(\(BackupV21Document.formatVersion)/\(BackupV21Document.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swiftindex ee0c6016..c444a46a 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("(20/21)"))+ #expect(reason.contains("(21/22)")) // 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/BootstrapActionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swiftindex bcd849f3..a90e5874 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() == "21",+ #expect(try root.markerText() == "22", "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("21\n")+ try root.writeMarker("22\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("21\n")+ try root.writeMarker("22\n") case .readinessMarkerWithoutAStore: try root.createStoreDirectory()- try root.writeMarker("21\n")+ try root.writeMarker("22\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 07f1ad10..66a6073b 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("21\n")+ try root.writeMarker("22\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("21\n")+ try root.writeMarker("22\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("21\n")+ try root.writeMarker("22\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("21\n")+ case .twenty: try root.writeMarker("22\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 854011a3..e99c4742 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 = "21\n"+private let readyMarkerBytes = "22\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 36a25602..e80f6201 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("(20/21)"))+ #expect(reason.contains("(21/22)")) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swiftindex 92c99d61..4d31a1dd 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) == ["21.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["22.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) == "21",+ #expect(try markerContent(cfg) == "22", "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 e7a3a6f1..6b78efd4 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(AsterismSchemaV21.models),+ let container = try ModelContainer(for: Schema(AsterismSchemaV22.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 97a2faf7..d202c5c4 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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 f0780650..f707152b 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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) == "21\n")+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "22\n") } private func seed(url: URL, workID: UUID, entryID: UUID, instant: Date) throws {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swiftindex e146e582..f22c51a9 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swiftindex e256c592..7d899702 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) let container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.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 f1cd07b1..b62b8945 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swiftindex 5d0edcdd..2a373510 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swiftindex 6f933d40..7fecf52f 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swiftindex 02a0989c..d9a09123 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.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 e154e731..8f383427 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swiftindex d9a05d63..7e09703b 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 == 21, "the phase list must name every entity")+ #expect(before.count == 24, "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,20 +461,24 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture() try await fixture.seedGoldenLibrary() - let before = try await fixture.repository.backupV20Snapshot()+ let before = try await fixture.repository.backupV21Snapshot() 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.backupV20Snapshot()+ let after = try await fixture.repository.backupV21Snapshot() try BackupV18RestoreAssertions.expectExactRecordsAndFreshNoteClears( 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)+ #expect(after.predecessor.associationEvents == before.predecessor.associationEvents,+ "before=\(before.predecessor.associationEvents.map { $0.value?.payload }) after=\(after.predecessor.associationEvents.map { $0.value?.payload })")+ #expect(after.predecessor.pairNoteVersions == before.predecessor.pairNoteVersions)+ #expect(after.groups == before.groups)+ #expect(after.groupFacts == before.groupFacts)+ #expect(after.groupTransitions == before.groupTransitions) await fixture.tearDown() } @@ -496,10 +500,10 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture(saveStrategy: strategy) try await fixture.seedGoldenLibrary() - let archive = try await fixture.repository.backupV20Snapshot()+ let archive = try await fixture.repository.backupV21Snapshot() _ = try await fixture.repository.emptyLibrary() try await fixture.repository.confirmImport(plan: EmptyLibraryFixture.plan(archive))- let restored = try await fixture.repository.backupV20Snapshot()+ let restored = try await fixture.repository.backupV21Snapshot() let stamps = try await fixture.repository.modificationStampsForTesting() strategy.arm()@@ -509,7 +513,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.backupV20Snapshot() == restored)+ #expect(try await fixture.repository.backupV21Snapshot() == restored) #expect(try await fixture.repository.modificationStampsForTesting() == stamps) await fixture.tearDown() }@@ -880,8 +884,8 @@ private final class EmptyLibraryFixture { urlRulePatterns: payload.urlRules.count)) } - static func plan(_ payload: BackupV20Payload) throws -> BackupImportPlan {- try BackupImporter.plan(from: BackupV20Codec.encode(payload: payload,+ static func plan(_ payload: BackupV21Payload) throws -> BackupImportPlan {+ try BackupImporter.plan(from: BackupV21Codec.encode(payload: payload, metadata: .init(appBuild: "empty-library-test", exportedAt: BackupGoldenLibrary.created))) } @@ -907,6 +911,14 @@ extension LibraryRepository { 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")))+ let groupID = UUID()+ context.insert(NamedCharacterGroup(id: groupID, workID: work.id))+ context.insert(GroupFactEvent(workID: work.id, groupID: groupID,+ payloadData: Data("create".utf8), parentHeadIDsData: Data("[]".utf8),+ recordedAt: .distantPast))+ context.insert(GroupTransition(workID: work.id, groupID: groupID,+ characterID: record.id, entryID: entry.id, payloadData: Data("join".utf8),+ parentHeadIDsData: Data("[]".utf8), recordedAt: .distantPast)) try context.save() } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swiftindex e1392228..9835cfc9 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 = "21\n"+ private static let markerContents = "22\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@@ -301,17 +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", "AsterismSchemaV21",- "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "AsterismV19MigrationPlan", "AsterismV20MigrationPlan", "AsterismV21MigrationPlan",+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", "AsterismSchemaV21", "AsterismSchemaV22",+ "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "AsterismV19MigrationPlan", "AsterismV20MigrationPlan", "AsterismV21MigrationPlan", "AsterismV22MigrationPlan", "atOrAboveV5", "belowV5", "firstV5Major", ]- /// Current archive 20/21 and the released 19/20 and 18/19 shapes+ /// Current archive 21/22 and the released 20/21, 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> = [- // 20/21 preserves raw associations and notes; 19/20 and 18/19 remain- // released shapes for bounded predecessor conversion.+ // 21/22 adds raw group identity and event arrays. Earlier formats+ // remain released shapes for bounded predecessor conversion.+ "BackupV21Codec", "BackupV21Document", "BackupV21Exporter",+ "BackupV21Metadata", "BackupV21Payload", "BackupV21SnapshotProviding",+ "CompatibleBackupV21Document", "backupV21Snapshot", "BackupV20Codec", "BackupV20Document", "BackupV20Exporter", "BackupV20Metadata", "BackupV20Payload", "BackupV20SnapshotProviding", "CompatibleBackupV20Document", "backupV20Snapshot", "projectV19Payload",@@ -383,24 +386,24 @@ struct FrozenLibraryPathTests { } #expect( declared.sorted() == [- "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", "AsterismSchemaV21",+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", "AsterismSchemaV21", "AsterismSchemaV22", ], "the package declares versioned schemas \(declared); Req 3.3 allows only ones a plan references") - let referenced = AsterismV21MigrationPlan.schemas.map { String(describing: $0) }+ let referenced = AsterismV22MigrationPlan.schemas.map { String(describing: $0) } #expect(- referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", "AsterismSchemaV21"],+ referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", "AsterismSchemaV21", "AsterismSchemaV22"], "the plan references \(referenced), which is not the set of declared schemas") // Retain every released snapshot and its lightweight transition. // V20 → V21 adds the two initially empty feature tables. #expect(- AsterismV21MigrationPlan.stages.count == 5,+ AsterismV22MigrationPlan.stages.count == 6, "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(- AsterismSchemaV21.versionIdentifier == Schema.Version(21, 0, 0),+ AsterismSchemaV22.versionIdentifier == Schema.Version(22, 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 cfa41c94..acb5effa 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupMembershipPresentationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupMembershipPresentationTests.swiftnew file mode 100644index 00000000..b919b7dd--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupMembershipPresentationTests.swift@@ -0,0 +1,18 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite struct GroupMembershipPresentationTests {+ @Test func separateClosedAndOpenIntervalsHaveSharedDisclosure() {+ let character = UUID()+ let ranges = [MembershipRange(start: .init(id: UUID(), label: "38"), end: .init(id: UUID(), label: "41")),+ MembershipRange(start: .init(id: UUID(), label: "57"), end: nil)]+ let groups = [GroupSummary(groupID: UUID(), name: "Team Loser", members: [character: ranges]),+ GroupSummary(groupID: UUID(), name: "Empty")]+ #expect(GroupMembershipText.character(character, groups: groups) == ["Team Loser (38–41, 57–)"])+ #expect(GroupMembershipText.character(UUID(), groups: groups).isEmpty)+ let value = ShareCharacter(id: character, name: "Bjorn", memberships: GroupMembershipText.character(character, groups: groups))+ #expect(ShareCharacterChips.detailLabel(for: value).contains("Team Loser (38–41, 57–)"))+ #expect(!ShareCharacterChips.detailLabel(for: value).contains(ShareCharacterChips.emptyDetailText))+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swiftindex a0e7f60d..ebf6fffc 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupReferenceResolverTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupReferenceResolverTests.swiftnew file mode 100644index 00000000..36442c9c--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupReferenceResolverTests.swift@@ -0,0 +1,113 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Named group reference resolution")+struct GroupReferenceResolverTests {+ private let work = UUID(uuidString: "00000000-0000-0000-0000-000000001001")!+ private let chapter = UUID(uuidString: "00000000-0000-0000-0000-000000001002")!+ private let group = UUID(uuidString: "00000000-0000-0000-0000-000000001003")!+ private let jake = UUID(uuidString: "00000000-0000-0000-0000-000000001004")!+ private let bjorn = UUID(uuidString: "00000000-0000-0000-0000-000000001005")!+ private func roster(_ people: [UUID]) -> GroupProjection {+ let create = GroupFact(groupID: group, workID: work,+ operation: .create(name: "Team Jake"))+ let joins = people.map { person -> GroupTransitionFact in+ let id = UUID()+ return GroupTransitionFact(id: id, rootID: id, workID: work,+ groupID: group, characterID: person, chapterID: chapter, action: .join)+ }+ return GroupRoster.project(workID: work, chapters: [.init(id: chapter, label: "5")],+ facts: [create], transitions: joins)+ }+ private var claims: [GroupNameClaim] {+ [.init(kind: .group, id: group, spelling: "Team Jake"),+ .init(kind: .character, id: jake, spelling: "Jake")]+ }++ @Test("The complete group name beats its member name while another direct mention survives")+ func longestMatch() {+ let result = GroupReferenceResolver.resolve(note: "Team Jake meets Jake.",+ chapterID: chapter, claims: claims, roster: roster([jake, bjorn]))+ #expect(result.mentions.map(\.kind) == [.group, .character])+ #expect(result.mentions.map(\.id) == [group, jake])+ #expect(result.characterIDs == [jake, bjorn])+ #expect(result.groupSupports.map(\.groupID) == [group])+ #expect(result.associationSupports(for: bjorn).count == 1)+ #expect(result.associationSupports(for: bjorn).first?.transitionEventIDs.count == 1)+ }++ @Test("An equally complete group and person claim is ambiguous regardless of directory order")+ func equalLengthRefusal() {+ let same = [GroupNameClaim(kind: .group, id: group, spelling: "Alex"),+ GroupNameClaim(kind: .character, id: jake, spelling: "Alex")]+ for directory in [same, same.reversed()] {+ let result = GroupReferenceResolver.resolve(note: "Alex leaves.",+ chapterID: chapter, claims: Array(directory), roster: roster([jake]))+ #expect(result.mentions.isEmpty)+ #expect(result.characterIDs.isEmpty)+ }+ let competitor = UUID()+ let competingGroups = [GroupNameClaim(kind: .group, id: group, spelling: "Team Jake"),+ GroupNameClaim(kind: .group, id: competitor, spelling: "Team Jake"),+ GroupNameClaim(kind: .character, id: jake, spelling: "Jake")]+ let twoGroups = GroupRoster.project(workID: work,+ chapters: [.init(id: chapter, label: "5")],+ facts: [GroupFact(groupID: group, workID: work, operation: .create(name: "Team Jake")),+ GroupFact(groupID: competitor, workID: work, operation: .create(name: "Team Jake"))],+ transitions: [])+ let contested = GroupReferenceResolver.resolve(note: "Team Jake leaves.",+ chapterID: chapter, claims: competingGroups, roster: twoGroups)+ #expect(contested.mentions.isEmpty)+ }++ @Test("Canonical Unicode spellings preserve saved evidence and suppress nested direct names")+ func unicodeAndWholeNames() {+ let claims = [GroupNameClaim(kind: .group, id: group, spelling: "Café Crew"),+ GroupNameClaim(kind: .character, id: jake, spelling: "Café")]+ let result = GroupReferenceResolver.resolve(note: "Cafe\u{301} Crew arrived; Decafé did not.",+ chapterID: chapter, claims: claims, roster: roster([bjorn]))+ #expect(result.mentions.map(\.kind) == [.group])+ #expect(result.mentions.first?.spelling == "Cafe\u{301} Crew")+ #expect(result.characterIDs == [bjorn])+ }++ @Test("A named but empty group yields evidence and no character link")+ func emptyRoster() {+ let result = GroupReferenceResolver.resolve(note: "Team Jake gathers.",+ chapterID: chapter, claims: claims, roster: roster([]))+ #expect(result.mentions.map(\.id) == [group])+ #expect(result.characterIDs.isEmpty)+ }++ @Test("Unanchored Work notes arbitrate spans without assigning chapter membership")+ func unanchoredGroupName() {+ let result = GroupReferenceResolver.resolve(note: "Team Jake meets Jake.",+ chapterID: nil, claims: claims, roster: roster([jake, bjorn]))+ #expect(result.mentions.map(\.kind) == [.group, .character])+ #expect(result.characterIDs == [jake])+ #expect(result.associationSupports(for: bjorn).isEmpty)+ }++ @Test("Physical claim order cannot change the longest-match decision")+ func claimPermutation() {+ let roster = roster([jake, bjorn])+ var generator = SeededMentionGenerator(seed: 0x2491)+ for _ in 0..<128 {+ let candidates = (claims + claims).shuffled(using: &generator)+ let result = GroupReferenceResolver.resolve(note: "Team Jake meets Jake.",+ chapterID: chapter, claims: candidates, roster: roster)+ #expect(result.mentions.map(\.id) == [group, jake])+ #expect(result.characterIDs == [jake, bjorn])+ }+ }+}++private struct SeededMentionGenerator: RandomNumberGenerator {+ var state: UInt64+ init(seed: UInt64) { state = seed }+ mutating func next() -> UInt64 {+ state = state &* 2862933555777941757 &+ 3037000493+ return state+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swiftindex d77bfc75..80f67c1b 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swiftindex c2ea4c5d..6ed9b31a 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swiftindex 95362516..33a15533 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swiftindex 91155bb8..df2192c7 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swiftindex f2ddb75f..375ba9b4 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) == "21",+ #expect(try markerContent(cfg) == "22", "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) == "21", "and the open leaves the marker as it found it")+ #expect(try markerContent(cfg) == "22", "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) == "21",+ #expect(try markerContent(cfg) == "22", "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) == "21")+ #expect(try markerContent(cfg) == "22") 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, "21\n")+ try writeMarker(cfg, "22\n") _ = try await LibraryRepository.openForExtension(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["21.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["22.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 b5804366..61391bdd 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("21\n")+ try root.writeMarker("22\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() == "21")+ #expect(try root.markerText() == "22") #expect(try V4RecordedStoreFixture.recordedModelVersions(at: root.configuration.storeURL)- == ["21.0.0"], "the store the arm opened is recorded at the version it converted to")+ == ["22.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() == "21")+ #expect(try root.markerText() == "22") 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() == "21")+ #expect(try root.markerText() == "22") withExtendedLifetime(root) {} } @@ -217,7 +217,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("a diagnosable library must still open, got \(result)") return }- #expect(try root.markerText() == "21")+ #expect(try root.markerText() == "22") #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() == "21")+ #expect(try root.markerText() == "22") 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 9140dddb..7e23f476 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swiftindex 639a2eae..7c5bf580 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swiftindex b5c3ab6d..a0118dfd 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 == "21")+ #expect(call.markerVersion == "22") #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 == "21")+ #expect(log.calls.first?.markerVersion == "22") #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 == "21")+ #expect(log.calls.first?.markerVersion == "22") #expect(await repository.mirroring.isMirroring) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swiftindex da159491..78e39042 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(AsterismSchemaV21.models.map { String(describing: $0) })+ let declared = Set(AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) var propertiesByEntity: [String: Set<String>] = [:] for entity in schema.entities { propertiesByEntity[entity.name, default: []]@@ -798,7 +798,8 @@ struct ModelContractTests { #expect( declaringSnapshots.sorted() == [ "AsterismSchemaV16.swift", "AsterismSchemaV17.swift",- "AsterismSchemaV18.swift", "AsterismSchemaV19.swift", "AsterismSchemaV20.swift", "AsterismSchemaV21.swift",+ "AsterismSchemaV18.swift", "AsterismSchemaV19.swift", "AsterismSchemaV20.swift",+ "AsterismSchemaV21.swift", "AsterismSchemaV22.swift", ], """ the package declares versioned schemas in \(declaringSnapshots.sorted()); \@@ -1115,7 +1116,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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swiftindex 22897d3b..0df47d0a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift@@ -126,7 +126,7 @@ struct MultiSiteReadPathTests { // 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",+ "AsterismSchemaV20Models.swift", "AsterismSchemaV21Models.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",@@ -210,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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupArchiveTests.swiftnew file mode 100644index 00000000..f8da86bc--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupArchiveTests.swift@@ -0,0 +1,159 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group archive", .serialized)+struct NamedGroupArchiveTests {+ @Test func predecessorArchiveImportsWithNoInventedGroupRows() async throws {+ let source = try await M5Fixture()+ let predecessor = try await source.repository.backupV20Snapshot()+ let data = try BackupV20Codec.encode(payload: predecessor,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let plan = try BackupImporter.plan(from: data)+ #expect(plan.payload.groups.isEmpty)+ #expect(plan.payload.groupFacts.isEmpty)+ #expect(plan.payload.groupTransitions.isEmpty)+ withExtendedLifetime(source) {}+ }++ @Test func currentArchiveRoundTripsGroupFactsAndTransitions() async throws {+ #expect(BackupV21Document.schemaVersion == AsterismSchemaV22.versionIdentifier.major)+ #expect(BackupV21Document.formatVersion == 21)+ let source = try await M5Fixture()+ let workID = UUID(), groupID = UUID(), characterID = UUID(), entryID = UUID()+ try await source.repository.withLockedContext(mode: .exclusive,+ operation: "seeding archive group") { context in+ let work = Work(id: workID, displayTitle: "The book", timestamp: M5Fixture.epoch)+ context.insert(work)+ context.insert(CharacterRecord(id: characterID, name: "Bjorn", nameKey: "bjorn", work: work))+ let chapter = Entry(id: entryID, captureTitle: "Chapter 38", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Team Loser returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "38"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ context.insert(NamedCharacterGroup(id: groupID, workID: workID))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID, workID: workID,+ operation: .create(name: "Team Loser")), recordedAt: M5Fixture.epoch))+ let transitionID = UUID()+ context.insert(try GroupTransition(fact: .init(id: transitionID, rootID: transitionID,+ workID: workID, groupID: groupID, characterID: characterID,+ chapterID: entryID, action: .join), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let payload = try await source.repository.backupV21Snapshot()+ #expect(payload.groups.count == 1)+ #expect(payload.groupFacts.count == 1)+ #expect(payload.groupTransitions.count == 1)+ let data = try BackupV21Codec.encode(payload: payload,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ #expect(try BackupV21Codec.decode(data).payload == payload)+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: BackupImporter.plan(from: data))+ let replay = try await restored.repository.backupV21Snapshot()+ #expect(replay.groups == payload.groups)+ #expect(replay.groupFacts == payload.groupFacts)+ #expect(replay.groupTransitions == payload.groupTransitions)+ withExtendedLifetime((source, restored)) {}+ }++ @Test func conflictingPhysicalFactCopiesRoundTripWithoutChoosingOne() async throws {+ let source = try await M5Fixture()+ let workID = UUID(), groupID = UUID(), factID = UUID()+ try await source.repository.withLockedContext(mode: .exclusive,+ operation: "seeding conflicting group fact copies") { context in+ context.insert(Work(id: workID, displayTitle: "The book", timestamp: M5Fixture.epoch))+ context.insert(NamedCharacterGroup(id: groupID, workID: workID))+ context.insert(try GroupFactEvent(fact: .init(id: factID, groupID: groupID,+ workID: workID, operation: .create(name: "Team Loser")),+ recordedAt: M5Fixture.epoch))+ context.insert(try GroupFactEvent(fact: .init(id: factID, groupID: groupID,+ workID: workID, operation: .create(name: "Other Team")),+ recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let payload = try await source.repository.backupV21Snapshot()+ #expect(payload.groupFacts.count == 2)+ let data = try BackupV21Codec.encode(payload: payload,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let target = try await M5Fixture()+ let plan = try BackupImporter.plan(from: data)+ _ = try await target.repository.confirmImport(plan: plan)+ #expect(try await target.repository.backupV21Snapshot().groupFacts == payload.groupFacts)+ _ = try await target.repository.confirmImport(plan: plan)+ #expect(try await target.repository.backupV21Snapshot().groupFacts == payload.groupFacts)+ withExtendedLifetime((source, target)) {}+ }++ @Test(arguments: [false, true], [false, true])+ func importingCoherentGroupReceiptKeepsItsAuthoredNoteAttached(joinInEarlierChapter: Bool,+ renameCollision: Bool) async throws {+ let source = try await M5Fixture(), target = try await M5Fixture()+ let workID = UUID(), groupID = UUID(), characterID = UUID(), entryID = UUID()+ let earlierID = UUID()+ func seed(_ fixture: M5Fixture, note: String, time: Date,+ characterName: String = "Bjorn") async throws {+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding import target chapter") { context in+ let work = Work(id: workID, displayTitle: "Book", timestamp: time)+ context.insert(work)+ context.insert(CharacterRecord(id: characterID, name: characterName,+ nameKey: RecordNameKey.normalize(characterName), work: work))+ let entry = Entry(id: entryID, captureTitle: "Chapter 38", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: time,+ note: note)+ try entry.authorTarget(.init(kind: .chapter, designation: "38"))+ context.insert(entry); entry.work = work+ LibraryRepository.applyManualAssignment(to: entry, at: time)+ try context.save()+ }+ }+ try await seed(source, note: "Team Loser returns.", time: M5Fixture.epoch)+ try await seed(target, note: "Earlier note.", time: M5Fixture.epoch.addingTimeInterval(-100),+ characterName: renameCollision ? "Team Loser" : "Bjorn")+ if joinInEarlierChapter {+ try await source.repository.withLockedContext(mode: .exclusive,+ operation: "seeding archive-only prior chapter") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == workID })+ let earlier = Entry(id: earlierID, captureTitle: "Chapter 37",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch.addingTimeInterval(-60),+ note: "The team forms.")+ try earlier.authorTarget(.init(kind: .chapter, designation: "37"))+ context.insert(earlier); earlier.work = work+ LibraryRepository.applyManualAssignment(to: earlier, at: M5Fixture.epoch)+ try context.save()+ }+ }+ try await source.repository.withLockedContext(mode: .exclusive,+ operation: "adding source group") { context in+ context.insert(NamedCharacterGroup(id: groupID, workID: workID))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID, workID: workID,+ operation: .create(name: "Team Loser")), recordedAt: M5Fixture.epoch))+ let transitionID = UUID()+ context.insert(try GroupTransition(fact: .init(id: transitionID, rootID: transitionID,+ workID: workID, groupID: groupID, characterID: characterID,+ chapterID: joinInEarlierChapter ? earlierID : entryID,+ action: .join), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let entry = try await source.repository.entry(id: entryID)+ #expect(try await source.repository.updateEntry(id: entryID,+ basis: .init(entry: entry), note: entry.note, rating: entry.rating) == .committed)+ let pair = AssociationPair(workID: workID, entryID: entryID,+ kind: .character, recordID: characterID)+ let basis = try #require(try await source.repository.associationNoteBasis(pair: pair))+ #expect(try await source.repository.saveAssociationNote(basis: basis,+ text: "Bjorn stayed with the team") == .committed)+ let payload = try await source.repository.backupV21Snapshot()+ let data = try BackupV21Codec.encode(payload: payload,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ _ = try await target.repository.confirmImport(plan: BackupImporter.plan(from: data))+ let restored = try #require(try await target.repository.associationNoteBasis(pair: pair))+ #expect(restored.heads.map(\.text) == ["Bjorn stayed with the team"])+ #expect(try await target.repository.detachedAssociationNotes().isEmpty)+ withExtendedLifetime((source, target)) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupRecordOperationsTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupRecordOperationsTests.swiftnew file mode 100644index 00000000..56390c86--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupRecordOperationsTests.swift@@ -0,0 +1,294 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group record operations", .serialized)+struct NamedGroupRecordOperationsTests {+ private struct IDs {+ let work = UUID(), group = UUID(), source = UUID(), target = UUID(), chapter = UUID()+ }++ private func fixture(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 record operations group") { context in+ let work = Work(id: ids.work, displayTitle: "Book", timestamp: M5Fixture.epoch)+ context.insert(work)+ context.insert(CharacterRecord(id: ids.source, name: "Bjorn", nameKey: "bjorn", work: work))+ context.insert(CharacterRecord(id: ids.target, name: "Missha", nameKey: "missha", work: work))+ let chapter = Entry(id: ids.chapter, captureTitle: "Chapter 38",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Team Loser returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "38"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work, operations: [+ .create(groupID: ids.group, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: ids.group, characterID: ids.source,+ chapterID: ids.chapter, action: .join)+ ]) == .committed(groupIDs: [ids.group]))+ return (fixture, ids)+ }++ private func basis(_ fixture: M5Fixture, _ id: UUID) async throws -> RecordEditBasis {+ let row = try #require(try await fixture.repository.m5RecordRows(.character, id: id).first)+ return RecordEditBasis(kind: .character, recordID: id, content: row)+ }++ @Test(arguments: [false, true])+ func characterCombinePreservesConcurrentMembershipHeads(divergent: Bool) async throws {+ let (fixture, ids) = try await fixture()+ let rootID = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "reading membership root before character combine") { context in+ try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.characterID == ids.source &&+ $0.transitionValue?.parentHeadIDs.isEmpty == true }?.id)+ }+ let sourceHeadIDs = [UUID(), UUID()]+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding concurrent membership heads before character combine") { context in+ for (index, id) in sourceHeadIDs.enumerated() {+ context.insert(try GroupTransition(fact: .init(id: id,+ rootID: rootID, workID: ids.work, groupID: ids.group,+ characterID: ids.source, chapterID: ids.chapter,+ parentHeadIDs: [rootID], action: divergent && index == 1 ? .leave : .join),+ recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ let source = try await basis(fixture, ids.source)+ let target = try await basis(fixture, ids.target)+ #expect(try await fixture.repository.commitRecordEdits(workID: ids.work,+ operations: [.combine(source: source, target: target)]) ==+ .committed(recordIDs: [ids.target]))+ let group = try #require(try await fixture.repository.characterGroups(workID: ids.work).first)+ #expect(group.members[ids.source] == nil)+ if divergent {+ let conflict = try #require(group.conflictedTransitions.first { $0.rootID == rootID })+ #expect(conflict.characterID == ids.target)+ #expect(conflict.heads.count == 2)+ #expect(Set(conflict.heads.flatMap(\.parentHeadIDs)) == Set(sourceHeadIDs))+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.reviseTransition(rootID: rootID,+ expectedEventIDs: conflict.expectedEventIDs,+ chapterID: ids.chapter, action: .join)]) == .committed(groupIDs: []))+ #expect(try await fixture.repository.characterGroups(workID: ids.work)+ .first?.members[ids.target]?.count == 1)+ } else {+ #expect(group.members[ids.target]?.count == 1)+ let successor = try #require(group.transitions.first {+ $0.rootID == rootID && $0.characterID == ids.target+ })+ #expect(Set(successor.parentHeadIDs) == Set(sourceHeadIDs))+ }+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: [false, true], [false, true])+ func deletingOrConvertingCharacterTombstonesEveryConcurrentHead(+ divergent: Bool, convert: Bool) async throws {+ let (fixture, ids) = try await fixture()+ let unrelatedRootID = UUID()+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.transition(rootID: unrelatedRootID, groupID: ids.group,+ characterID: ids.target, chapterID: ids.chapter,+ action: .join)]) == .committed(groupIDs: []))+ let rootID = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "reading root before explicit record removal") { context in+ try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.characterID == ids.source &&+ $0.transitionValue?.parentHeadIDs.isEmpty == true }?.id)+ }+ let headIDs = [UUID(), UUID()]+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding concurrent heads before explicit record removal") { context in+ for (index, id) in headIDs.enumerated() {+ context.insert(try GroupTransition(fact: .init(id: id,+ rootID: rootID, workID: ids.work, groupID: ids.group,+ characterID: ids.source, chapterID: ids.chapter,+ parentHeadIDs: [rootID], action: divergent && index == 1 ? .leave : .join),+ recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ let source = try await basis(fixture, ids.source)+ let operation: RecordEditOperation = convert+ ? .convert(basis: source, to: .place,+ draft: .init(kind: .place, name: "Harbor"))+ : .delete(basis: source)+ guard case .committed = try await fixture.repository.commitRecordEdits(+ workID: ids.work, operations: [operation]) else {+ Issue.record("Explicit character removal was refused")+ return+ }+ let group = try #require(try await fixture.repository.characterGroups(workID: ids.work).first)+ #expect(group.members[ids.source] == nil)+ #expect(group.members[ids.target]?.count == 1)+ #expect(!group.conflictedTransitions.contains { $0.rootID == rootID })+ let tombstone = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking complete removal of concurrent source heads") { context in+ try context.fetch(FetchDescriptor<GroupTransition>()).compactMap(\.transitionValue)+ .first { $0.rootID == rootID && $0.action == .remove }+ }+ #expect(tombstone.map { Set($0.parentHeadIDs) } == Set(headIDs))+ withExtendedLifetime(fixture) {}+ }++ @Test func deletingCharacterTombstonesItsGroupTransitions() async throws {+ let (fixture, ids) = try await fixture()+ #expect(try await fixture.repository.characterGroups(workID: ids.work)+ .first?.members[ids.source]?.count == 1)+ let source = try await basis(fixture, ids.source)+ #expect(try await fixture.repository.commitRecordEdits(workID: ids.work,+ operations: [.delete(basis: source)]) ==+ .committed(recordIDs: [ids.source]))+ #expect(try await fixture.repository.characterGroups(workID: ids.work)+ .first?.members[ids.source] == nil)+ let events = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking group transition tombstone") { context in+ try context.fetch(FetchDescriptor<GroupTransition>()).compactMap(\.transitionValue)+ }+ #expect(events.contains { $0.characterID == ids.source && $0.action == .remove })+ withExtendedLifetime(fixture) {}+ }++ @Test func convertingOneMemberRetiresItsRosterWithoutStallingOtherMemberHistory() async throws {+ let strategy = ArmableFailingSaveStrategy()+ let (fixture, ids) = try await fixture(saveStrategy: strategy)+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work, operations: [+ .transition(rootID: UUID(), groupID: ids.group, characterID: ids.target,+ chapterID: ids.chapter, action: .join)+ ]) == .committed(groupIDs: []))+ let sourcePair = AssociationPair(workID: ids.work, entryID: ids.chapter,+ kind: .character, recordID: ids.source)+ let noteText = "Exact Bjorn reader observation"+ let noteBasis = try #require(try await fixture.repository.associationNoteBasis(pair: sourcePair))+ #expect(try await fixture.repository.saveAssociationNote(basis: noteBasis,+ text: noteText) == .committed)+ let source = try await basis(fixture, ids.source)+ let conversion: [RecordEditOperation] = [+ .convert(basis: source, to: .place, draft: .init(kind: .place, name: "Harbor"))]++ strategy.resetCount()+ strategy.failFrom = 1+ do {+ _ = try await fixture.repository.commitRecordEdits(workID: ids.work,+ operations: conversion)+ Issue.record("Injected conversion save must fail")+ } catch { }+ strategy.failFrom = nil+ #expect(try await !fixture.repository.m5RecordRows(.character, id: ids.source).isEmpty)+ let rolledBack = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking failed conversion transition") { context in+ try context.fetch(FetchDescriptor<GroupTransition>()).compactMap(\.transitionValue)+ }+ #expect(!rolledBack.contains { $0.characterID == ids.source && $0.action == .remove })+ #expect(try #require(try await fixture.repository.associationNoteBasis(+ pair: sourcePair)).heads.map(\.text) == [noteText])++ guard case .committed(let convertedIDs) = try await fixture.repository.commitRecordEdits(+ workID: ids.work, operations: conversion) else {+ Issue.record("Conversion should commit after the injected failure")+ return+ }+ let placeID = try #require(convertedIDs.last)+ let group = try #require(try await fixture.repository.characterGroups(workID: ids.work).first)+ #expect(group.members[ids.source] == nil)+ #expect(group.members[ids.target]?.count == 1)+ let transitions = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking converted character tombstone") { context in+ try context.fetch(FetchDescriptor<GroupTransition>()).compactMap(\.transitionValue)+ }+ #expect(transitions.contains { $0.characterID == ids.source && $0.action == .remove })+ let placePair = AssociationPair(workID: ids.work, entryID: ids.chapter,+ kind: .place, recordID: placeID)+ let detached = try await fixture.repository.detachedAssociationNotes().filter {+ $0.pair == placePair+ }+ #expect(detached.contains { $0.raw.text == noteText })++ let laterChapterID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding another member's historical chapter") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let chapter = Entry(id: laterChapterID, captureTitle: "Chapter 39",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch.addingTimeInterval(60),+ note: "The Team returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "39"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work, operations: [+ .fact(groupID: ids.group, expectedEventIDs: group.factEventIDs,+ operation: .addAlias("The Team"))+ ]) == .committed(groupIDs: []))+ let targetPair = AssociationPair(workID: ids.work, entryID: laterChapterID,+ kind: .character, recordID: ids.target)+ #expect(try await fixture.repository.chapterAssociations(entryID: laterChapterID)+ .contains { $0.pair == targetPair && !$0.activeAcceptanceIDs.isEmpty })+ try await fixture.repository.invalidateGroupHistoryAfterImport()+ let history = try await fixture.repository.reconcileGroupHistory()+ #expect(history.scannedChapterIDs.contains(laterChapterID))+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: [false, true], [false, true])+ func combiningCharactersRebindsMembershipToSurvivor(+ targetAlreadyJoined: Bool, lateOriginalCopy: Bool) async throws {+ let (fixture, ids) = try await fixture()+ if targetAlreadyJoined {+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.transition(rootID: UUID(), groupID: ids.group,+ characterID: ids.target, chapterID: ids.chapter,+ action: .join)]) == .committed(groupIDs: []))+ }+ let source = try await basis(fixture, ids.source)+ let target = try await basis(fixture, ids.target)+ #expect(try await fixture.repository.commitRecordEdits(workID: ids.work,+ operations: [.combine(source: source, target: target)]) ==+ .committed(recordIDs: [ids.target]))+ if lateOriginalCopy {+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "delivering late original transition") { context in+ let root = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.characterID == ids.source })+ context.insert(GroupTransition(raw: GroupRawTransition(root)))+ try context.save()+ }+ }+ let group = try #require(try await fixture.repository.characterGroups(workID: ids.work).first)+ #expect(group.members[ids.source] == nil)+ #expect(group.members[ids.target]?.count == 1)+ let events = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking group transition successor") { context in+ try context.fetch(FetchDescriptor<GroupTransition>()).compactMap(\.transitionValue)+ }+ #expect(events.contains { $0.characterID == ids.target && !$0.parentHeadIDs.isEmpty })+ withExtendedLifetime(fixture) {}+ }++ @Test func deletingGroupTombstonesItsTransitions() async throws {+ let (fixture, ids) = try await fixture()+ let heads = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "reading group fact heads") { context in+ try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.groupID == ids.group }.map(\.id)+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.fact(groupID: ids.group, expectedEventIDs: heads,+ operation: .delete)]) == .committed(groupIDs: []))+ #expect(try await fixture.repository.characterGroups(workID: ids.work).isEmpty)+ let tombstones = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "reading group transition tombstones") { context in+ try context.fetch(FetchDescriptor<GroupTransition>()).compactMap(\.transitionValue)+ }+ #expect(tombstones.contains { $0.groupID == ids.group && $0.action == .remove })+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupRosterTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupRosterTests.swiftnew file mode 100644index 00000000..99a3c802--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupRosterTests.swift@@ -0,0 +1,243 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Named group causal roster")+struct NamedGroupRosterTests {+ private let work = UUID(uuidString: "00000000-0000-0000-0000-000000000001")!+ private let group = UUID(uuidString: "00000000-0000-0000-0000-000000000002")!+ private let secondGroup = UUID(uuidString: "00000000-0000-0000-0000-000000000003")!+ private let bjorn = UUID(uuidString: "00000000-0000-0000-0000-000000000004")!+ private let misha = UUID(uuidString: "00000000-0000-0000-0000-000000000005")!+ private var chapters: [GroupChapter] {+ (1...14).map { number in+ GroupChapter(id: UUID(uuidString: String(format: "00000000-0000-0000-0000-%012d", number + 100))!,+ label: String(number))+ }+ }+ private func id(_ number: Int) -> UUID {+ UUID(uuidString: String(format: "10000000-0000-0000-0000-%012d", number))!+ }+ private func fact(_ number: Int, _ operation: GroupFactOperation,+ parents: [UUID] = [], groupID: UUID? = nil) -> GroupFact {+ GroupFact(id: id(number), groupID: groupID ?? group, workID: work,+ parentHeadIDs: parents, operation: operation)+ }+ private func transition(_ number: Int, _ action: GroupTransitionAction,+ chapter: Int, characterID: UUID? = nil, groupID: UUID? = nil,+ rootID: UUID? = nil, parents: [UUID] = []) -> GroupTransitionFact {+ GroupTransitionFact(id: id(number), rootID: rootID ?? id(number), workID: work,+ groupID: groupID ?? group, characterID: characterID ?? bjorn,+ chapterID: chapters[chapter - 1].id, parentHeadIDs: parents,+ action: action)+ }+ private func project(_ facts: [GroupFact], _ transitions: [GroupTransitionFact]) -> GroupProjection {+ GroupRoster.project(workID: work, chapters: chapters, facts: facts,+ transitions: transitions)+ }++ @Test("Name and alias claims follow causal heads and deletion wins over late predecessors")+ func nameAliasAndDelete() {+ let create = fact(1, .create(name: "Team Loser"))+ let alias = fact(2, .addAlias("The Losers"), parents: [create.id])+ let remove = fact(3, .removeAlias("The Losers"), parents: [alias.id])+ let rename = fact(4, .setName("Team Jake"), parents: [remove.id])+ let result = project([rename, alias, create, remove], [])+ #expect(result.groups.map(\.name) == ["Team Jake"])+ #expect(result.groups.first?.aliases == [])++ let otherRename = fact(5, .setName("Team J"), parents: [remove.id])+ #expect(project([create, alias, remove, rename, otherRename], []).groups.first?.name == nil)+ let resolve = fact(6, .setName("Team Jake"), parents: [rename.id, otherRename.id])+ #expect(project([create, alias, remove, rename, otherRename, resolve], []).groups.first?.name == "Team Jake")+ let deleted = fact(7, .delete, parents: [resolve.id])+ #expect(project([create, alias, remove, rename, otherRename, resolve, deleted], []).groups.isEmpty)+ }++ @Test("Concurrent aliases and conflicting physical event IDs withhold disputed claims")+ func conflictingClaims() {+ let create = fact(1, .create(name: "Team Loser"))+ let add = fact(2, .addAlias("Losers"), parents: [create.id])+ let remove = fact(3, .removeAlias("Losers"), parents: [create.id])+ #expect(project([create, add, remove], []).groups.first?.aliases == [])+ let resolve = fact(4, .addAlias("Losers"), parents: [add.id, remove.id])+ #expect(project([create, add, remove, resolve], []).groups.first?.aliases == ["Losers"])+ let conflictingCopy = fact(2, .addAlias("Team"), parents: [create.id])+ #expect(project([create, add, conflictingCopy], []).groups.first?.aliases == [])+ }++ @Test("Inclusive joins and last leaves form distinct reciprocal intervals")+ func inclusiveIntervals() {+ let facts = [fact(1, .create(name: "Team Loser")),+ fact(2, .create(name: "Second"), groupID: secondGroup)]+ let events = [transition(10, .join, chapter: 5),+ transition(11, .join, chapter: 7),+ transition(12, .leave, chapter: 10),+ transition(13, .leave, chapter: 12),+ transition(14, .join, chapter: 14),+ transition(15, .join, chapter: 5, characterID: misha),+ transition(16, .leave, chapter: 5, characterID: misha),+ transition(17, .join, chapter: 6, groupID: secondGroup)]+ let result = project(facts, events)+ #expect(result.members(groupID: group, chapterID: chapters[3].id).isEmpty)+ #expect(result.members(groupID: group, chapterID: chapters[4].id) == [bjorn, misha])+ #expect(result.members(groupID: group, chapterID: chapters[5].id) == [bjorn])+ #expect(result.members(groupID: group, chapterID: chapters[11].id) == [bjorn])+ #expect(result.members(groupID: group, chapterID: chapters[12].id).isEmpty)+ #expect(result.members(groupID: group, chapterID: chapters[13].id) == [bjorn])+ let bjornRanges = result.ranges(groupID: group, characterID: bjorn)+ #expect(bjornRanges.count == 2)+ #expect(bjornRanges[0].startLabel == "5" && bjornRanges[0].endLabel == "12")+ #expect(bjornRanges[1].startLabel == "14" && bjornRanges[1].endLabel == nil)+ let mishaRanges = result.ranges(groupID: group, characterID: misha)+ #expect(mishaRanges.count == 1)+ #expect(mishaRanges[0].startLabel == "5" && mishaRanges[0].endLabel == "5")+ #expect(result.ranges(groupID: secondGroup, characterID: bjorn).map(\.startLabel) == ["6"])+ #expect(result.groupsForCharacter(bjorn).map(\.groupID) == [group, secondGroup])+ }++ @Test("Transition support checks the addressed member across chapter intervals")+ func addressedMemberTransitionSupport() {+ let events = [transition(30, .join, chapter: 5),+ transition(31, .leave, chapter: 7),+ transition(32, .join, chapter: 10),+ transition(33, .join, chapter: 6, characterID: misha),+ transition(34, .leave, chapter: 6, characterID: misha)]+ let result = project([fact(1, .create(name: "Team Loser"))], events)+ #expect(result.transitionEventIDs(groupID: group, characterID: bjorn,+ chapterID: chapters[3].id).isEmpty)+ #expect(Set(result.transitionEventIDs(groupID: group, characterID: bjorn,+ chapterID: chapters[4].id)) == [id(30), id(31), id(32)])+ #expect(Set(result.transitionEventIDs(groupID: group, characterID: bjorn,+ chapterID: chapters[6].id)) == [id(30), id(31), id(32)])+ #expect(result.transitionEventIDs(groupID: group, characterID: bjorn,+ chapterID: chapters[7].id).isEmpty)+ #expect(Set(result.transitionEventIDs(groupID: group, characterID: bjorn,+ chapterID: chapters[9].id)) == [id(30), id(31), id(32)])+ #expect(Set(result.transitionEventIDs(groupID: group, characterID: misha,+ chapterID: chapters[5].id)) == [id(33), id(34)])+ #expect(result.transitionEventIDs(groupID: group, characterID: misha,+ chapterID: chapters[6].id).isEmpty)+ }++ @Test("Edited and removed transitions never mutate original facts; divergent heads withhold membership")+ func transitionCorrections() {+ let create = fact(1, .create(name: "Team Loser"))+ let join = transition(10, .join, chapter: 5)+ let edited = transition(11, .join, chapter: 7, rootID: join.id, parents: [join.id])+ let divergent = transition(12, .join, chapter: 8, rootID: join.id, parents: [join.id])+ #expect(project([create], [join, edited]).members(groupID: group, chapterID: chapters[4].id).isEmpty)+ #expect(project([create], [join, edited]).members(groupID: group, chapterID: chapters[6].id) == [bjorn])+ #expect(project([create], [join, edited, divergent]).members(groupID: group,+ chapterID: chapters[8].id).isEmpty)+ let equivalent = transition(20, .join, chapter: 7, rootID: join.id, parents: [join.id])+ #expect(project([create], [join, edited, equivalent]).members(groupID: group,+ chapterID: chapters[6].id) == [bjorn])+ let resolution = transition(13, .join, chapter: 6, rootID: join.id,+ parents: [edited.id, divergent.id])+ #expect(project([create], [join, edited, divergent, resolution]).members(groupID: group,+ chapterID: chapters[5].id) == [bjorn])+ let removed = transition(14, .remove, chapter: 6, rootID: join.id, parents: [resolution.id])+ #expect(project([create], [join, edited, divergent, resolution, removed]).members(+ groupID: group, chapterID: chapters[8].id).isEmpty)+ let unlinked = transition(21, .join, chapter: 8, rootID: join.id)+ #expect(project([create], [join, unlinked]).members(groupID: group,+ chapterID: chapters[6].id) == [bjorn])+ }++ @Test("Seeded physical order, duplicate and pair permutations preserve the roster")+ func generatedPhysicalPermutations() {+ let create = fact(1, .create(name: "Team Loser"))+ let events = [transition(10, .join, chapter: 5), transition(11, .leave, chapter: 12),+ transition(12, .join, chapter: 5, characterID: misha)]+ var generator = SeededGroupGenerator(seed: 0x2491)+ for _ in 0..<128 {+ var shuffled = events.shuffled(using: &generator)+ if generator.next() & 1 == 0 { shuffled.append(shuffled[0]) }+ let roster = project([create], shuffled)+ #expect(roster.members(groupID: group, chapterID: chapters[4].id) == [bjorn, misha])+ #expect(roster.members(groupID: group, chapterID: chapters[12].id) == [misha])+ }+ }++ @Test("Immutable successor events carry a merged identity without rewriting historical parents")+ func successorRebind() {+ let oldWork = UUID(), oldGroup = UUID(), oldCharacter = UUID()+ let oldCreate = GroupFact(id: id(70), groupID: oldGroup, workID: oldWork,+ operation: .create(name: "Team Loser"))+ let successorCreate = GroupFact(id: id(71), groupID: group, workID: work,+ parentHeadIDs: [oldCreate.id],+ operation: .create(name: "Team Loser"))+ let oldJoin = GroupTransitionFact(id: id(72), rootID: id(72), workID: oldWork,+ groupID: oldGroup, characterID: oldCharacter, chapterID: UUID(), action: .join)+ let successorJoin = GroupTransitionFact(id: id(73), rootID: oldJoin.id, workID: work,+ groupID: group, characterID: bjorn, chapterID: chapters[4].id,+ parentHeadIDs: [oldJoin.id], action: .join)+ let roster = project([oldCreate, successorCreate], [oldJoin, successorJoin])+ #expect(roster.groups.map(\.groupID) == [group])+ #expect(roster.members(groupID: group, chapterID: chapters[4].id) == [bjorn])+ #expect(oldCreate.groupID == oldGroup && oldJoin.characterID == oldCharacter)+ }++ @Test("A duplicate or missing chapter anchor withholds that claim without crashing")+ func incoherentAnchors() {+ let create = fact(1, .create(name: "Team Loser"))+ let join = transition(10, .join, chapter: 5)+ let duplicate = chapters[4]+ let result = GroupRoster.project(workID: work, chapters: chapters + [duplicate],+ facts: [create], transitions: [join])+ #expect(result.members(groupID: group, chapterID: duplicate.id).isEmpty)+ #expect(result.ranges(groupID: group, characterID: bjorn).isEmpty)+ }++ @Test("A disputed leave withholds the affected member instead of leaving an open join")+ func disputedLeave() {+ let create = fact(1, .create(name: "Team Loser"))+ let join = transition(10, .join, chapter: 5)+ let leave = transition(11, .leave, chapter: 10)+ let earlier = transition(12, .leave, chapter: 10, rootID: leave.id,+ parents: [leave.id])+ let later = transition(13, .leave, chapter: 12, rootID: leave.id,+ parents: [leave.id])+ let result = project([create], [join, leave, earlier, later])+ #expect(result.members(groupID: group, chapterID: chapters[12].id).isEmpty)+ }++ @Test("Concurrent successor destinations are disputed globally, not unique per destination")+ func concurrentSuccessorDestinations() {+ let sourceGroup = UUID(), sourceWork = UUID()+ let facts = [fact(1, .create(name: "Team Loser")),+ fact(2, .create(name: "Second"), groupID: secondGroup)]+ let root = GroupTransitionFact(id: id(30), rootID: id(30), workID: sourceWork,+ groupID: sourceGroup, characterID: bjorn, chapterID: UUID(), action: .join)+ let first = transition(31, .join, chapter: 5, rootID: root.id, parents: [root.id])+ let second = transition(32, .join, chapter: 5, groupID: secondGroup,+ rootID: root.id, parents: [root.id])+ let result = project(facts, [root, first, second])+ #expect(result.members(groupID: group, chapterID: chapters[4].id).isEmpty)+ #expect(result.members(groupID: secondGroup, chapterID: chapters[4].id).isEmpty)+ }++ @Test("Removing a transition tombstones later descendants of its original root")+ func removedRootCannotImplicitlyReturn() {+ let create = fact(1, .create(name: "Team Loser"))+ let join = transition(10, .join, chapter: 5)+ let removed = transition(11, .remove, chapter: 5, rootID: join.id,+ parents: [join.id])+ let lateJoin = transition(12, .join, chapter: 6, rootID: join.id,+ parents: [join.id])+ let descendant = transition(13, .join, chapter: 7, rootID: join.id,+ parents: [removed.id, lateJoin.id])+ let result = project([create], [join, removed, lateJoin, descendant])+ #expect(result.members(groupID: group, chapterID: chapters[7].id).isEmpty)+ }+}++private struct SeededGroupGenerator: RandomNumberGenerator {+ var state: UInt64+ init(seed: UInt64) { state = seed }+ mutating func next() -> UInt64 {+ state = state &* 6364136223846793005 &+ 1442695040888963407+ return state+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSaveLinkTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSaveLinkTests.swiftnew file mode 100644index 00000000..c6a1de89--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSaveLinkTests.swift@@ -0,0 +1,1141 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group saved chapter links", .serialized)+struct NamedGroupSaveLinkTests {+ private struct IDs {+ let work = UUID(), group = UUID(), character = UUID(), entry = UUID()+ }++ private func fixture(note: String = "Team Loser returns.", seedGroup: Bool = true,+ seedTransition: 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 named group chapter") { context in+ let work = Work(id: ids.work, displayTitle: "Saved book", timestamp: M5Fixture.epoch)+ context.insert(work)+ context.insert(CharacterRecord(id: ids.character, name: "Bjorn", nameKey: "bjorn", work: work))+ let chapter = Entry(id: ids.entry, captureTitle: "Chapter 38", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: note)+ try chapter.authorTarget(.init(kind: .chapter, designation: "38"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ if seedGroup {+ context.insert(NamedCharacterGroup(id: ids.group, workID: ids.work))+ context.insert(try GroupFactEvent(fact: .init(groupID: ids.group, workID: ids.work,+ operation: .create(name: "Team Loser")), recordedAt: M5Fixture.epoch))+ if seedTransition {+ let transitionID = UUID()+ context.insert(try GroupTransition(fact: .init(id: transitionID, rootID: transitionID,+ workID: ids.work, groupID: ids.group, characterID: ids.character,+ chapterID: ids.entry, action: .join), recordedAt: M5Fixture.epoch))+ }+ }+ try context.save()+ }+ return (fixture, ids)+ }++ @Test func editorCommitsNameAndAliasesFromOneSnapshot() async throws {+ let (fixture, ids) = try await fixture()+ let group = try #require(try await fixture.repository.characterGroups(workID: ids.work).first)+ let outcome = try await fixture.repository.commitGroupEdits(workID: ids.work, operations: [+ .fact(groupID: ids.group, expectedEventIDs: group.factEventIDs, operation: .setName("New Team")),+ .fact(groupID: ids.group, expectedEventIDs: group.factEventIDs, operation: .addAlias("Old Team")),+ .fact(groupID: ids.group, expectedEventIDs: group.factEventIDs, operation: .addAlias("The Team"))])+ #expect(outcome == .committed(groupIDs: []))+ let updated = try #require(try await fixture.repository.characterGroups(workID: ids.work).first)+ let detail = try await fixture.repository.workDetail(id: ids.work)+ #expect(detail.characterGroups == [updated])+ #expect(detail.characters.contains { $0.id == ids.character })+ #expect(updated.name == "New Team")+ #expect(Set(updated.aliases) == ["Old Team", "The Team"])+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work, operations: [+ .fact(groupID: ids.group, expectedEventIDs: group.factEventIDs, operation: .setName("Stale"))]) == .refused(.stale))+ withExtendedLifetime(fixture) {}+ }++ @Test func finalSavedGroupNameLinksCurrentMemberAndReplaysIdempotently() async throws {+ let (fixture, ids) = try await fixture()+ 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 first = try await fixture.repository.chapterAssociations(entryID: ids.entry)+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: ids.character)+ #expect(first.first { $0.pair == pair }?.activeAcceptanceIDs.count == 1)+ let fresh = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry,+ basis: .init(entry: fresh), note: fresh.note, rating: fresh.rating) == .committed)+ let second = try await fixture.repository.chapterAssociations(entryID: ids.entry)+ #expect(second.first { $0.pair == pair }?.activeAcceptanceIDs == first.first { $0.pair == pair }?.activeAcceptanceIDs)+ withExtendedLifetime(fixture) {}+ }++ @Test func ordinaryRemovalSuppressesCapturedGroupSupportAndExplicitRestoreReactivatesIt() async throws {+ let (fixture, ids) = try await fixture(note: "Team Loser returns.")+ 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 pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: ids.character)+ let before = try #require(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair })+ #expect(!before.activeAcceptanceIDs.isEmpty)+ let noteBasis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(try await fixture.repository.saveAssociationNote(basis: noteBasis,+ text: "Retained association note") == .committed)+ #expect(try await fixture.repository.removeChapterAssociation(pair: pair))+ let removed = try #require(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair })+ #expect(removed.isRemoved)+ #expect(removed.activeAcceptanceIDs.isEmpty)+ #expect(!removed.rawNotes.isEmpty, "Removal keeps the authored association note recoverable")++ let refreshed = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry,+ basis: .init(entry: refreshed), note: refreshed.note, rating: refreshed.rating) == .committed)+ let stillRemoved = try #require(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair })+ #expect(stillRemoved.activeAcceptanceIDs.isEmpty, "An unchanged group support stays removed after Save")+ let archived = try await fixture.repository.backupV21Snapshot()+ let bytes = try BackupV21Codec.encode(payload: archived,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let imported = try await M5Fixture()+ _ = try await imported.repository.confirmImport(plan: BackupImporter.plan(from: bytes))+ let importedPair = try #require(try await imported.repository.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair })+ #expect(importedPair.isRemoved && importedPair.activeAcceptanceIDs.isEmpty)+ #expect(importedPair.rawNotes.contains { $0.value?.text == "Retained association note" })+ let restarted = try await LibraryRepository.openForApp(+ LibraryConfiguration(rootDirectory: imported.directory),+ clock: FixedRepositoryClock(M5Fixture.epoch)).repository+ let restartedPair = try #require(try await restarted.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair })+ #expect(restartedPair.isRemoved && restartedPair.activeAcceptanceIDs.isEmpty)+ #expect(try await restarted.restoreChapterAssociation(pair: pair))+ let archiveRestored = try #require(try await restarted.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair })+ #expect(!archiveRestored.isRemoved && !archiveRestored.activeAcceptanceIDs.isEmpty)++ let group = try #require(try await fixture.repository.characterGroups(workID: ids.work).first)+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work, operations: [+ .fact(groupID: ids.group, expectedEventIDs: group.factEventIDs, operation: .addAlias("The Losers"))+ ]) == .committed(groupIDs: []))+ let changed = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: changed),+ note: "The Losers return.", rating: changed.rating) == .committed)+ let newEvidence = try #require(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair })+ #expect(!newEvidence.isRemoved && !newEvidence.activeAcceptanceIDs.isEmpty,+ "A genuinely new group spelling is independent support for the pair")+ #expect(try await fixture.repository.removeChapterAssociation(pair: pair))+ #expect(try await fixture.repository.restoreChapterAssociation(pair: pair))+ let restored = try #require(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair })+ #expect(!restored.isRemoved)+ #expect(!restored.activeAcceptanceIDs.isEmpty)+ withExtendedLifetime((fixture, imported, restarted)) {}+ }++ @Test func groupMentionDoesNotCreateLinkBeforeTheJoinChapter() async throws {+ let (fixture, ids) = try await fixture()+ let earlier = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding earlier chapter") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let chapter = Entry(id: earlier, captureTitle: "Chapter 37", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch.addingTimeInterval(-60),+ note: "Team Loser returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "37"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ let entry = try await fixture.repository.entry(id: earlier)+ #expect(try await fixture.repository.updateEntry(id: earlier,+ basis: .init(entry: entry), note: entry.note, rating: entry.rating) == .committed)+ #expect(try await fixture.repository.chapterAssociations(entryID: earlier).isEmpty)+ withExtendedLifetime(fixture) {}+ }++ @Test func directAndGroupSupportOneLinkAndRetireIndependently() async throws {+ let (fixture, ids) = try await fixture(note: "Bjorn and Team Loser return.")+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: ids.character)+ func activeIDs() async throws -> Set<UUID> {+ try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair }?.activeAcceptanceIDs ?? []+ }+ var 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: nil) == .committed)+ #expect(try await activeIDs().count == 2)++ entry = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry,+ basis: .init(entry: entry), note: "Team Loser returns.", rating: nil) == .committed)+ #expect(try await activeIDs().count == 1)++ entry = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry,+ basis: .init(entry: entry), note: "Bjorn returns.", rating: nil) == .committed)+ #expect(try await activeIDs().count == 1)++ entry = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry,+ basis: .init(entry: entry), note: "Nobody named here.", rating: nil) == .committed)+ #expect(try await activeIDs().isEmpty)+ withExtendedLifetime(fixture) {}+ }++ @Test func creatingGroupAndJoiningSavedChapterCommitsItsLinkTogether() async throws {+ let (fixture, ids) = try await fixture(note: "Team Loser returns.", seedGroup: false)+ let created = UUID()+ let outcome = try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [+ .create(groupID: created, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: created, characterID: ids.character,+ chapterID: ids.entry, action: .join)+ ])+ #expect(outcome == .committed(groupIDs: [created]))+ let link = try await fixture.repository.chapterAssociations(entryID: ids.entry)+ #expect(link.first { $0.pair.recordID == ids.character }?.activeAcceptanceIDs.count == 1)+ let detail = try await fixture.repository.workDetail(id: ids.work)+ let presentedGroup = try #require(detail.characterGroups.first { $0.groupID == created })+ let memberRange = try #require(presentedGroup.members[ids.character]?.first)+ #expect(memberRange.startChapterID == ids.entry)+ #expect(memberRange.endChapterID == nil)+ let share = try await fixture.repository.shareWorkContext(workID: ids.work,+ currentChapterSequence: nil, currentChapterTitle: "Chapter 999")+ let sharedGroup = try #require(share.groups.first { $0.id == created })+ #expect(sharedGroup.memberships == ["Bjorn (38–)"])+ withExtendedLifetime(fixture) {}+ }++ @Test func deletingAFormerMemberDoesNotBlockLaterRosterReconciliation() async throws {+ let (fixture, ids) = try await fixture(note: "Team Loser returns.")+ let oldRows = try await fixture.repository.m5RecordRows(.character, id: ids.character)+ let oldContent = try #require(oldRows.first)+ #expect(try await fixture.repository.commitRecordEdits(workID: ids.work,+ operations: [.delete(basis: .init(kind: .character, recordID: ids.character,+ content: oldContent))]) == .committed(recordIDs: [ids.character]))++ let replacementID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "adding unrelated live group member after deletion") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ context.insert(CharacterRecord(id: replacementID, name: "Sigrid",+ nameKey: "sigrid", work: work))+ let transitionID = UUID()+ context.insert(try GroupTransition(fact: .init(id: transitionID,+ rootID: transitionID, workID: ids.work, groupID: ids.group,+ characterID: replacementID, chapterID: ids.entry, action: .join),+ recordedAt: M5Fixture.epoch))+ try context.save()+ }++ let report = try await fixture.repository.reconcileGroupHistory()+ #expect(report.scannedChapterIDs == [ids.entry])+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: replacementID)+ let link = try #require(try await fixture.repository.chapterAssociations(+ entryID: ids.entry).first { $0.pair == pair })+ #expect(!link.activeAcceptanceIDs.isEmpty)+ withExtendedLifetime(fixture) {}+ }++ @Test func mergedMemberDoesNotBlockGroupRenameReconciliation() async throws {+ let (fixture, ids) = try await fixture(note: "Team Loser returns.")+ 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 survivorID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "adding group merge survivor") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ context.insert(CharacterRecord(id: survivorID, name: "Kari",+ nameKey: "kari", work: work))+ try context.save()+ }+ let source = try #require(try await fixture.repository.m5RecordRows(+ .character, id: ids.character).first)+ let target = try #require(try await fixture.repository.m5RecordRows(+ .character, id: survivorID).first)+ #expect(try await fixture.repository.commitRecordEdits(workID: ids.work,+ operations: [.combine(+ source: .init(kind: .character, recordID: ids.character, content: source),+ target: .init(kind: .character, recordID: survivorID, content: target))])+ == .committed(recordIDs: [survivorID]))++ let groupID = ids.group+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "receiving remote group rename after merge") { context in+ let parents = try context.fetch(FetchDescriptor<GroupFactEvent>(+ predicate: #Predicate { $0.groupID == groupID })).map(\.id)+ context.insert(try GroupFactEvent(fact: .init(groupID: ids.group,+ workID: ids.work, parentHeadIDs: parents,+ operation: .setName("New Team")), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let report = try await fixture.repository.reconcileGroupHistory()+ #expect(report.scannedChapterIDs == [ids.entry])+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: survivorID)+ let link = try #require(try await fixture.repository.chapterAssociations(+ entryID: ids.entry).first { $0.pair == pair })+ #expect(link.activeAcceptanceIDs.isEmpty,+ "Renaming the group retires the historical link from the old group name")+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["group", "fact", "transition"])+ func crossWorkPhysicalTwinCannotAuthorizeGroupLink(kind: String) async throws {+ let (fixture, ids) = try await fixture()+ let otherWorkID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding cross-Work physical twin") { context in+ context.insert(Work(id: otherWorkID, displayTitle: "Other book", timestamp: M5Fixture.epoch))+ switch kind {+ case "group":+ context.insert(NamedCharacterGroup(id: ids.group, workID: otherWorkID))+ case "fact":+ let original = try #require(context.fetch(FetchDescriptor<GroupFactEvent>()).first)+ context.insert(GroupFactEvent(id: original.id, workID: otherWorkID,+ groupID: ids.group, payloadData: original.payloadData,+ parentHeadIDsData: original.parentHeadIDsData, recordedAt: original.recordedAt))+ default:+ let original = try #require(context.fetch(FetchDescriptor<GroupTransition>()).first)+ context.insert(GroupTransition(id: original.id, workID: otherWorkID,+ groupID: ids.group, characterID: ids.character, entryID: ids.entry,+ payloadData: original.payloadData,+ parentHeadIDsData: original.parentHeadIDsData, recordedAt: original.recordedAt))+ }+ 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: nil) == .committed)+ let links = try await fixture.repository.chapterAssociations(entryID: ids.entry)+ #expect(links.allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ withExtendedLifetime(fixture) {}+ }++ @Test func renameAliasAndDeleteRevalidateExistingLink() async throws {+ let (fixture, ids) = try await fixture()+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: ids.character)+ func active() async throws -> Bool {+ try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first { $0.pair == pair }?.activeAcceptanceIDs.isEmpty == false+ }+ func eventIDs() async throws -> [UUID] {+ try await fixture.repository.withLockedContext(mode: .shared,+ operation: "reading group edit basis") { context in+ try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.groupID == ids.group }.map(\.id)+ }+ }+ 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: nil)+ #expect(try await active())+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.fact(groupID: ids.group, expectedEventIDs: eventIDs(),+ operation: .setName("New Team"))], currentChapterID: ids.entry) == .committed(groupIDs: []))+ #expect(try await !active())+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.fact(groupID: ids.group, expectedEventIDs: eventIDs(),+ operation: .addAlias("Team Loser"))], currentChapterID: ids.entry) == .committed(groupIDs: []))+ #expect(try await active())+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.fact(groupID: ids.group, expectedEventIDs: eventIDs(),+ operation: .delete)], currentChapterID: ids.entry) == .committed(groupIDs: []))+ #expect(try await !active())+ withExtendedLifetime(fixture) {}+ }++ @Test func transitionRemoveAndStaleEditDoNotRestoreMembership() async throws {+ let (fixture, ids) = try await fixture()+ let rootID = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "reading transition edit basis") { context in+ try #require(context.fetch(FetchDescriptor<GroupTransition>()).first?.id)+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.reviseTransition(rootID: rootID, expectedEventIDs: [rootID],+ chapterID: ids.entry, action: .remove)]) == .committed(groupIDs: []))+ 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: nil)+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.reviseTransition(rootID: rootID, expectedEventIDs: [rootID],+ chapterID: ids.entry, action: .join)]) == .refused(.stale))+ withExtendedLifetime(fixture) {}+ }++ @Test func failedGroupSaveRollsBackFactsAndChapterLinkThenRetryCommitsOnce() async throws {+ let saves = InstrumentedSaveStrategy()+ let (fixture, ids) = try await fixture(seedGroup: false, save: saves)+ let groupID = UUID()+ let actions: [GroupEditOperation] = [+ .create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: groupID, characterID: ids.character,+ chapterID: ids.entry, action: .join)+ ]+ saves.shouldFail = true+ do {+ _ = try await fixture.repository.commitGroupEdits(workID: ids.work, operations: actions)+ Issue.record("Injected save should fail")+ } catch {}+ #expect(saves.attemptCount == 1 && saves.successCount == 0)+ #expect(try await fixture.repository.characterGroups(workID: ids.work).isEmpty)+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry).isEmpty)+ saves.shouldFail = false+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: actions) == .committed(groupIDs: [groupID]))+ #expect(saves.attemptCount == 2 && saves.successCount == 1)+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first?.activeAcceptanceIDs.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test func crossWorkTransitionRefusesWholeSessionWithoutSaving() async throws {+ let saves = InstrumentedSaveStrategy()+ let (fixture, ids) = try await fixture(seedGroup: false, save: saves)+ let groupID = UUID(), stranger = UUID()+ let outcome = try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [+ .create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: groupID,+ characterID: stranger, chapterID: ids.entry, action: .join)+ ])+ #expect(outcome == .refused(.characterGone))+ #expect(saves.attemptCount == 0)+ #expect(try await fixture.repository.characterGroups(workID: ids.work).isEmpty)+ withExtendedLifetime(fixture) {}+ }++ private func teachSite(_ fixture: M5Fixture, workID: UUID) async throws {+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "teaching group capture site") { 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 == workID })+ 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: ["manual", "capture", "reparse", "reShare", "replay", "correction"])+ func savedNoteTerminalsExpandGroupAgainstChapterRoster(terminal: String) async throws {+ let (fixture, ids) = try await fixture()+ let linkedEntryID: UUID+ switch terminal {+ case "manual":+ let projection = try await fixture.repository.projectManualEntry(workID: ids.work)+ let outcome = try await fixture.repository.commitManualEntry(+ projection: projection, draft: .init(target: .init(kind: .chapter,+ designation: "39"), note: "Team Loser returns.", confirmedNewChapter: true))+ guard case .committed(let entry) = outcome else {+ Issue.record("Manual chapter Save did not commit: \(outcome)"); return+ }+ linkedEntryID = entry.id+ case "capture", "reparse":+ try await teachSite(fixture, workID: ids.work)+ if terminal == "capture" {+ let projection = try await fixture.repository.projectChapterCapture(+ rawURL: "https://example.com/39", captureTitle: "Saved book - 39",+ workID: ids.work)+ let outcome = try await fixture.repository.commitChapterCapture(.init(+ projection: projection,+ capture: .init(captureTitle: "Saved book - 39",+ captureTitleSource: .manual, rawURLString: "https://example.com/39",+ note: "Team Loser returns."),+ intent: .newChapter(.init(kind: .chapter, designation: "39"),+ confirmedNew: true)))+ guard case .committed(let entry) = outcome else {+ Issue.record("Capture did not commit: \(outcome)"); return+ }+ linkedEntryID = entry.id+ } else {+ let entry = try await fixture.repository.capture(.init(captureTitle: "Saved book - 39",+ captureTitleSource: .manual, rawURLString: "https://example.com/39",+ note: "Team Loser returns."))+ let contract = try await fixture.repository.projectReparse(entryID: entry.id)+ #expect(try await fixture.repository.commitReparse(contract) == .committed)+ linkedEntryID = entry.id+ }+ case "reShare":+ let entry = try await fixture.repository.entry(id: ids.entry)+ let basis = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "reading group 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)+ linkedEntryID = ids.entry+ case "replay":+ let entry = try await fixture.repository.entry(id: ids.entry)+ 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)+ linkedEntryID = ids.entry+ default:+ let contract = try await fixture.repository.projectEntryCorrection(entryID: ids.entry)+ #expect(try await fixture.repository.commitEntryCorrection(contract,+ target: .init(kind: .chapter)) == .committed(entryID: ids.entry))+ linkedEntryID = ids.entry+ }+ let links = try await fixture.repository.chapterAssociations(entryID: linkedEntryID)+ #expect(links.first { $0.pair.recordID == ids.character }?.activeAcceptanceIDs.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test func removingGroupAliasRetiresOnlyItsGroupEvidence() async throws {+ let (fixture, ids) = try await fixture(note: "The Survivors return.")+ func factIDs() async throws -> [UUID] {+ try await fixture.repository.withLockedContext(mode: .shared,+ operation: "reading alias event basis") { context in+ try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.groupID == ids.group }.map(\.id)+ }+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.fact(groupID: ids.group, expectedEventIDs: factIDs(),+ operation: .addAlias("The Survivors"))],+ currentChapterID: ids.entry) == .committed(groupIDs: []))+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first?.activeAcceptanceIDs.count == 1)+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.fact(groupID: ids.group, expectedEventIDs: factIDs(),+ operation: .removeAlias("The Survivors"))],+ currentChapterID: ids.entry) == .committed(groupIDs: []))+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ withExtendedLifetime(fixture) {}+ }++ @Test func movingJoinAnchorRecomputesBothChapterMemberships() async throws {+ let (fixture, ids) = try await fixture()+ let later = UUID()+ let rootID = try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding later group chapter") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let row = Entry(id: later, captureTitle: "Chapter 39", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "",+ timestamp: M5Fixture.epoch.addingTimeInterval(60), note: "Team Loser returns.")+ try row.authorTarget(.init(kind: .chapter, designation: "39"))+ context.insert(row); row.work = work+ LibraryRepository.applyManualAssignment(to: row, at: M5Fixture.epoch)+ let id = try #require(context.fetch(FetchDescriptor<GroupTransition>()).first?.id)+ try context.save()+ return id+ }+ for chapterID in [ids.entry, later] {+ let entry = try await fixture.repository.entry(id: chapterID)+ _ = try await fixture.repository.updateEntry(id: chapterID,+ basis: .init(entry: entry), note: entry.note, rating: nil)+ #expect(try await fixture.repository.chapterAssociations(entryID: chapterID)+ .first?.activeAcceptanceIDs.count == 1)+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.reviseTransition(rootID: rootID,+ expectedEventIDs: [rootID], chapterID: later,+ action: .join)], currentChapterID: later) == .committed(groupIDs: []))+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ #expect(try await fixture.repository.chapterAssociations(entryID: later)+ .first?.activeAcceptanceIDs.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["group", "fact", "transition"])+ func crossWorkPhysicalTwinRefusesGroupMutation(kind: String) async throws {+ let (fixture, ids) = try await fixture()+ let otherWorkID = UUID()+ let (rootID, factIDs) = try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding conflicting group edit basis") { context in+ context.insert(Work(id: otherWorkID, displayTitle: "Other book",+ timestamp: M5Fixture.epoch))+ let root = try #require(context.fetch(FetchDescriptor<GroupTransition>()).first)+ switch kind {+ case "group":+ context.insert(NamedCharacterGroup(id: ids.group, workID: otherWorkID))+ case "fact":+ let fact = try #require(context.fetch(FetchDescriptor<GroupFactEvent>()).first)+ context.insert(GroupFactEvent(id: fact.id, workID: otherWorkID,+ groupID: ids.group, payloadData: fact.payloadData,+ parentHeadIDsData: fact.parentHeadIDsData, recordedAt: fact.recordedAt))+ default:+ context.insert(GroupTransition(id: root.id, workID: otherWorkID,+ groupID: ids.group, characterID: ids.character, entryID: ids.entry,+ payloadData: root.payloadData,+ parentHeadIDsData: root.parentHeadIDsData, recordedAt: root.recordedAt))+ }+ try context.save()+ return (root.id, try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.groupID == ids.group && $0.workID == ids.work }.map(\.id))+ }+ let operation: GroupEditOperation = kind == "transition"+ ? .reviseTransition(rootID: rootID, expectedEventIDs: [rootID],+ chapterID: ids.entry, action: .leave)+ : .fact(groupID: ids.group, expectedEventIDs: factIDs,+ operation: .setName("New Team"))+ let outcome = try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [operation], currentChapterID: ids.entry)+ if case .refused = outcome {} else { Issue.record("Conflicting physical twin was edited: \(outcome)") }+ withExtendedLifetime(fixture) {}+ }++ @Test func groupEditorCannotUseAnotherWorksCurrentChapter() async throws {+ let saves = InstrumentedSaveStrategy()+ let (fixture, ids) = try await fixture(seedGroup: false, save: saves)+ let otherChapter = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding another Works chapter") { context in+ let other = Work(displayTitle: "Other book", timestamp: M5Fixture.epoch)+ context.insert(other)+ let row = Entry(id: otherChapter, captureTitle: "Chapter 1",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Team Loser")+ try row.authorTarget(.init(kind: .chapter, designation: "1"))+ context.insert(row); row.work = other+ LibraryRepository.applyManualAssignment(to: row, at: M5Fixture.epoch)+ try context.save()+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.create(groupID: UUID(), name: "Team Loser")],+ currentChapterID: otherChapter) == .refused(.crossWork))+ #expect(saves.attemptCount == 0)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["fact", "transition"])+ func identicalCloudKitEventCopyDoesNotMakeGroupEditStale(kind: String) async throws {+ let (fixture, ids) = try await fixture()+ let eventID = try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding identical group event copy") { context in+ if kind == "fact" {+ let row = try #require(context.fetch(FetchDescriptor<GroupFactEvent>()).first)+ context.insert(GroupFactEvent(id: row.id, workID: row.workID,+ groupID: row.groupID, payloadData: row.payloadData,+ parentHeadIDsData: row.parentHeadIDsData, recordedAt: row.recordedAt))+ try context.save(); return row.id+ }+ let row = try #require(context.fetch(FetchDescriptor<GroupTransition>()).first)+ context.insert(GroupTransition(id: row.id, workID: row.workID,+ groupID: row.groupID, characterID: row.characterID, entryID: row.entryID,+ payloadData: row.payloadData, parentHeadIDsData: row.parentHeadIDsData,+ recordedAt: row.recordedAt))+ try context.save(); return row.id+ }+ let operation: GroupEditOperation = kind == "fact"+ ? .fact(groupID: ids.group, expectedEventIDs: [eventID],+ operation: .setName("New Team"))+ : .reviseTransition(rootID: eventID, expectedEventIDs: [eventID],+ chapterID: ids.entry, action: .leave)+ #expect(try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [operation], currentChapterID: ids.entry) == .committed(groupIDs: []))+ withExtendedLifetime(fixture) {}+ }++ @Test func malformedPhysicalCopyOfTransitionRefusesRevision() async throws {+ let (fixture, ids) = try await fixture()+ let rootID = try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding malformed transition twin") { context in+ let row = try #require(context.fetch(FetchDescriptor<GroupTransition>()).first)+ context.insert(GroupTransition(id: row.id, workID: row.workID,+ groupID: row.groupID, characterID: row.characterID, entryID: row.entryID,+ payloadData: Data([0x7b]), parentHeadIDsData: row.parentHeadIDsData,+ recordedAt: row.recordedAt))+ try context.save(); return row.id+ }+ let outcome = try await fixture.repository.commitGroupEdits(workID: ids.work,+ operations: [.reviseTransition(rootID: rootID,+ expectedEventIDs: [rootID], chapterID: ids.entry, action: .leave)])+ #expect(outcome == .refused(.stale))+ withExtendedLifetime(fixture) {}+ }++ @Test func remoteOnlyJoinReprocessesPreviouslySavedGroupMention() async throws {+ let (fixture, ids) = try await fixture(seedTransition: false)+ 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: nil)+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry).isEmpty)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "receiving remote-only group join") { context in+ let id = UUID()+ context.insert(try GroupTransition(fact: .init(id: id, rootID: id,+ workID: ids.work, groupID: ids.group, characterID: ids.character,+ chapterID: ids.entry, action: .join), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ _ = try await fixture.repository.reconcileAfterSync(tier: .arrival)+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first?.activeAcceptanceIDs.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["rename", "aliasRemoval"])+ func remoteFactChangeRevalidatesOldSavedGroupMentions(mode: String) async throws {+ let note = mode == "rename" ? "New Team returns." : "The Survivors return."+ let (fixture, ids) = try await fixture(note: note)+ if mode == "aliasRemoval" {+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding old group alias") { context in+ let create = try #require(context.fetch(FetchDescriptor<GroupFactEvent>()).first)+ context.insert(try GroupFactEvent(fact: .init(groupID: ids.group,+ workID: ids.work, parentHeadIDs: [create.id],+ operation: .addAlias("The Survivors")), 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: entry.note, rating: nil)+ _ = try await fixture.repository.reconcileGroupHistory()+ let initiallyActive = try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first?.activeAcceptanceIDs.isEmpty == false+ let oldRoot = try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first?.activeAcceptanceIDs.first+ #expect(initiallyActive == (mode == "aliasRemoval"))+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "receiving remote group fact change") { context in+ let parents = try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.groupID == ids.group }.map(\.id)+ let operation: GroupFactOperation = mode == "rename"+ ? .setName("New Team") : .removeAlias("The Survivors")+ context.insert(try GroupFactEvent(fact: .init(groupID: ids.group,+ workID: ids.work, parentHeadIDs: parents, operation: operation),+ recordedAt: M5Fixture.epoch))+ try context.save()+ }+ _ = try await fixture.repository.reconcileAfterSync(tier: .arrival)+ let active = try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first?.activeAcceptanceIDs.isEmpty == false+ #expect(active == (mode == "rename"))+ if mode == "aliasRemoval", let oldRoot {+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: ids.character)+ let retired = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking group root retirement") { context in+ try !AssociationStorageInventory.read(context: context, workIDs: [ids.work],+ includeNotes: false).ledger.canRevalidateAcceptance(oldRoot, pair: pair)+ }+ #expect(retired)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "restoring remote alias without history pass") { context in+ let parents = try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.groupID == ids.group }.map(\.id)+ context.insert(try GroupFactEvent(fact: .init(groupID: ids.group,+ workID: ids.work, parentHeadIDs: parents,+ operation: .addAlias("The Survivors")), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ _ = try await fixture.repository.reconcileGroupHistory()+ let newRoot = try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first?.activeAcceptanceIDs.first+ #expect(newRoot != nil && newRoot != oldRoot)+ }+ let repeated = try await fixture.repository.reconcileGroupHistory()+ #expect(repeated.batchSizes.isEmpty && repeated.associationSaves == 0)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: [false, true])+ func interruptedHistoryResumesAfterCommittedBatchWithoutRepeatingIt(insertEarlier: Bool) async throws {+ let saves = InstrumentedSaveStrategy()+ let (fixture, ids) = try await fixture(seedTransition: false, save: saves)+ var chapterIDs = [ids.entry]+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding 260 changed-Work chapters") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ for number in 39..<298 {+ let id = UUID()+ let row = Entry(id: id, captureTitle: "Chapter \(number)",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch.addingTimeInterval(Double(number)),+ note: "Team Loser returns.")+ try row.authorTarget(.init(kind: .chapter, designation: String(number)))+ context.insert(row); row.work = work+ LibraryRepository.applyManualAssignment(to: row, at: M5Fixture.epoch)+ chapterIDs.append(id)+ }+ try context.save()+ }+ let baseline = try await fixture.repository.reconcileGroupHistory()+ #expect(baseline.batchSizes == [128, 128, 4] && baseline.associationSaves == 0)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "receiving remote group join before interrupted sweep") { context in+ let id = UUID()+ context.insert(try GroupTransition(fact: .init(id: id, rootID: id,+ workID: ids.work, groupID: ids.group, characterID: ids.character,+ chapterID: ids.entry, action: .join), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ saves.failAfter = 1+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await fixture.repository.reconcileGroupHistory()+ }+ #expect(saves.attemptCount == 2 && saves.successCount == 1)+ var inserted: UUID?+ if insertEarlier {+ let id = UUID(); inserted = id; chapterIDs.append(id)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "hydrating an earlier chapter during group retry") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let row = Entry(id: id, captureTitle: "Chapter 39.5", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "",+ timestamp: M5Fixture.epoch.addingTimeInterval(-60),+ note: "Team Loser returns.")+ try row.authorTarget(.init(kind: .chapter, designation: "39.5"))+ context.insert(row); row.work = work+ LibraryRepository.applyManualAssignment(to: row, at: M5Fixture.epoch)+ try context.save()+ }+ }+ await fixture.repository.shutdown()+ let reopened = try await LibraryRepository.openForApp(+ .init(rootDirectory: fixture.directory)).repository+ let resumed = try await reopened.reconcileGroupHistory()+ #expect(resumed.batchSizes == (insertEarlier ? [128, 128, 5] : [128, 4]))+ #expect(resumed.associationSaves == (insertEarlier ? 3 : 2))+ #expect(Set(resumed.scannedChapterIDs).isSubset(of: Set(chapterIDs)))+ #expect(try await reopened.reconcileGroupHistory().batchSizes.isEmpty)+ for chapterID in [ids.entry, chapterIDs[128], chapterIDs[259]] {+ #expect(try await reopened.chapterAssociations(entryID: chapterID)+ .first?.activeAcceptanceIDs.count == 1)+ }+ if let inserted {+ #expect(try await reopened.chapterAssociations(entryID: inserted)+ .first?.activeAcceptanceIDs.count == 1)+ }+ await reopened.shutdown()+ withExtendedLifetime(fixture) {}+ }++ @Test func groupFactsArrivingBeforeWorkHydrationRetryAfterChapterAppears() async throws {+ let fixture = try await M5Fixture()+ let workID = UUID(), groupID = UUID(), characterID = UUID(), chapterID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding group facts before Work hydration") { context in+ context.insert(NamedCharacterGroup(id: groupID, workID: workID))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: workID, operation: .create(name: "Team Loser")),+ recordedAt: M5Fixture.epoch))+ let id = UUID()+ context.insert(try GroupTransition(fact: .init(id: id, rootID: id,+ workID: workID, groupID: groupID, characterID: characterID,+ chapterID: chapterID, action: .join), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let early = try await fixture.repository.reconcileGroupHistory()+ #expect(early.scannedChapterIDs.isEmpty)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "hydrating saved group chapter") { context in+ let work = Work(id: workID, displayTitle: "Saved book",+ timestamp: M5Fixture.epoch)+ context.insert(work)+ let chapter = Entry(id: chapterID, captureTitle: "Chapter 1",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Team Loser returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "1"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ let beforeCharacter = try await fixture.repository.reconcileGroupHistory()+ #expect(beforeCharacter.scannedChapterIDs.isEmpty)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "hydrating group member character after chapter") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == workID })+ context.insert(CharacterRecord(id: characterID, name: "Bjorn",+ nameKey: "bjorn", work: work))+ try context.save()+ }+ let resumed = try await fixture.repository.reconcileGroupHistory()+ #expect(resumed.batchSizes == [1])+ #expect(try await fixture.repository.chapterAssociations(entryID: chapterID)+ .first?.activeAcceptanceIDs.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: [false, true])+ func temporaryTornTransitionHidesButDoesNotRetireGroupRoot(+ independentLeave: Bool) async throws {+ let (fixture, ids) = try await fixture()+ 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: nil)+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry,+ kind: .character, recordID: ids.character)+ let root = try #require(try await fixture.repository.chapterAssociations(+ entryID: ids.entry).first?.activeAcceptanceIDs.first)+ let noteText = "Exact note on original group acceptance"+ let noteBasis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(try await fixture.repository.saveAssociationNote(basis: noteBasis,+ text: noteText) == .committed)+ let brokenIDs = try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding torn transition delivery") { context in+ let original = try #require(context.fetch(FetchDescriptor<GroupTransition>()).first)+ let valid: GroupTransition+ if independentLeave {+ let id = UUID()+ valid = try GroupTransition(fact: .init(id: id, rootID: id,+ workID: ids.work, groupID: ids.group,+ characterID: ids.character, chapterID: ids.entry,+ action: .leave), recordedAt: M5Fixture.epoch)+ context.insert(valid)+ } else {+ valid = original+ }+ let twin = GroupTransition(id: valid.id, workID: valid.workID,+ groupID: original.groupID, characterID: original.characterID,+ entryID: original.entryID, payloadData: Data([0x7b]),+ parentHeadIDsData: valid.parentHeadIDsData,+ recordedAt: valid.recordedAt)+ context.insert(twin); try context.save()+ return independentLeave ? [valid.persistentModelID, twin.persistentModelID]+ : [twin.persistentModelID]+ }+ _ = try await fixture.repository.reconcileGroupHistory()+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ let stillRecoverable = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking temporarily hidden root") { context in+ try AssociationStorageInventory.read(context: context, workIDs: [ids.work],+ includeNotes: false).ledger.canRevalidateAcceptance(root, pair: pair)+ }+ #expect(stillRecoverable)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "repairing torn transition delivery") { context in+ let rows = try context.fetch(FetchDescriptor<GroupTransition>())+ .filter { brokenIDs.contains($0.persistentModelID) }+ #expect(rows.count == brokenIDs.count)+ for row in rows { context.delete(row) }+ try context.save()+ }+ _ = try await fixture.repository.reconcileGroupHistory()+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .first?.activeAcceptanceIDs == [root])+ #expect(try #require(try await fixture.repository.associationNoteBasis(+ pair: pair)).heads.map(\.text) == [noteText])+ withExtendedLifetime(fixture) {}+ }++ @Test func missingLeaveAnchorWithholdsLaterLinkButKeepsEarlierNoteRecoverable() async throws {+ let fixture = try await M5Fixture()+ let workID = UUID(), groupID = UUID(), bjornID = UUID(), evaID = UUID()+ let joinID = UUID(), earlierID = UUID(), leaveID = UUID(), laterID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding join, leave and two group-note chapters") { context in+ let work = Work(id: workID, displayTitle: "Saved book",+ timestamp: M5Fixture.epoch)+ context.insert(work)+ context.insert(CharacterRecord(id: bjornID, name: "Bjorn",+ nameKey: "bjorn", work: work))+ context.insert(CharacterRecord(id: evaID, name: "Eva",+ nameKey: "eva", work: work))+ for (id, number, note) in [+ (joinID, 5, ""), (earlierID, 8, "Team Loser returns."),+ (leaveID, 10, ""), (laterID, 11, "Team Loser returns.")+ ] {+ let chapter = Entry(id: id, captureTitle: "Chapter \(number)",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch+ .addingTimeInterval(Double(number)), note: note)+ try chapter.authorTarget(.init(kind: .chapter,+ designation: String(number)))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter,+ at: M5Fixture.epoch)+ }+ context.insert(NamedCharacterGroup(id: groupID, workID: workID))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: workID, operation: .create(name: "Team Loser")),+ recordedAt: M5Fixture.epoch))+ for (characterID, rootID, chapterID, action) in [+ (bjornID, UUID(), joinID, GroupTransitionAction.join),+ (evaID, UUID(), joinID, .join)+ ] {+ context.insert(try GroupTransition(fact: .init(id: rootID,+ rootID: rootID, workID: workID, groupID: groupID,+ characterID: characterID, chapterID: chapterID,+ action: action), recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ let earlier = try await fixture.repository.entry(id: earlierID)+ #expect(try await fixture.repository.updateEntry(id: earlierID,+ basis: .init(entry: earlier), note: earlier.note,+ rating: nil) == .committed)+ let earlierPair = AssociationPair(workID: workID, entryID: earlierID,+ kind: .character, recordID: bjornID)+ let earlierRoot = try #require(try await fixture.repository.chapterAssociations(+ entryID: earlierID).first(where: { $0.pair == earlierPair })?+ .activeAcceptanceIDs.first)+ let noteText = "Bjorn's exact earlier observation"+ let noteBasis = try #require(try await fixture.repository.associationNoteBasis(+ pair: earlierPair))+ #expect(try await fixture.repository.saveAssociationNote(basis: noteBasis,+ text: noteText) == .committed)++ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "receiving independent leave while its anchor is unavailable") { context in+ let rootID = UUID()+ context.insert(try GroupTransition(fact: .init(id: rootID,+ rootID: rootID, workID: workID, groupID: groupID,+ characterID: bjornID, chapterID: leaveID,+ action: .leave), recordedAt: M5Fixture.epoch))+ let leave = try #require(context.fetch(FetchDescriptor<Entry>())+ .first { $0.id == leaveID && $0.work?.id == workID })+ leave.work = nil+ try context.save()+ }+ let later = try await fixture.repository.entry(id: laterID)+ #expect(try await fixture.repository.updateEntry(id: laterID,+ basis: .init(entry: later), note: later.note,+ rating: nil) == .committed)+ let laterPairs = try await fixture.repository.chapterAssociations(entryID: laterID)+ #expect(laterPairs.first(where: { $0.pair.recordID == bjornID })?+ .activeAcceptanceIDs.isEmpty != false)+ #expect(laterPairs.first(where: { $0.pair.recordID == evaID })?+ .activeAcceptanceIDs.isEmpty == false)+ _ = try await fixture.repository.reconcileGroupHistory()+ let hiddenEarlier = try #require(try await fixture.repository.chapterAssociations(+ entryID: earlierID).first(where: { $0.pair == earlierPair }))+ #expect(hiddenEarlier.activeAcceptanceIDs.isEmpty)+ #expect(!hiddenEarlier.rawNotes.isEmpty)+ let recoverable = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking earlier group root remains recoverable") { context in+ try AssociationStorageInventory.read(context: context,+ workIDs: [workID], includeNotes: false).ledger+ .canRevalidateAcceptance(earlierRoot, pair: earlierPair)+ }+ #expect(recoverable)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "rehydrating leave anchor") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == workID })+ let leave = try #require(context.fetch(FetchDescriptor<Entry>())+ .first { $0.id == leaveID && $0.work == nil })+ leave.work = work+ try context.save()+ }+ _ = try await fixture.repository.reconcileGroupHistory()+ let rehydrated = try #require(try await fixture.repository.chapterAssociations(+ entryID: earlierID).first(where: { $0.pair == earlierPair }))+ #expect(!rehydrated.activeAcceptanceIDs.isEmpty)+ #expect(rehydrated.rawNotes.contains { $0.text == noteText })+ let stillRecoverable = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking original acceptance after leave hydration") { context in+ try AssociationStorageInventory.read(context: context,+ workIDs: [workID], includeNotes: false).ledger+ .canRevalidateAcceptance(earlierRoot, pair: earlierPair)+ }+ #expect(stillRecoverable)+ let detached = try await fixture.repository.detachedAssociationNotes()+ let recoverableNote = try #require(detached.first {+ $0.pair == earlierPair && $0.raw.text == noteText && $0.canRecover+ })+ let recoveryBasis = try #require(try await fixture.repository.associationNoteBasis(+ pair: earlierPair))+ #expect(try await fixture.repository.recoverAssociationNotes(+ basis: recoveryBasis, selectedHeads: [try #require(recoverableNote.head)],+ text: noteText) == .committed)+ #expect(try await fixture.repository.chapterAssociations(entryID: earlierID)+ .first(where: { $0.pair == earlierPair })?+ .noteHeads.contains { $0.text == noteText } == true)+ #expect(try await fixture.repository.chapterAssociations(entryID: laterID)+ .first(where: { $0.pair.recordID == bjornID })?+ .activeAcceptanceIDs.isEmpty != false)+ withExtendedLifetime(fixture) {}+ }++ @Test func importInvalidationForcesCompletedHistoryToRecheck() async throws {+ let (fixture, ids) = try await fixture()+ let first = try await fixture.repository.reconcileGroupHistory()+ #expect(first.scannedChapterIDs == [ids.entry])+ #expect(try await fixture.repository.reconcileGroupHistory().scannedChapterIDs.isEmpty)+ try await fixture.repository.invalidateGroupHistoryAfterImport()+ let resumed = try await fixture.repository.reconcileGroupHistory()+ #expect(resumed.scannedChapterIDs == [ids.entry])+ #expect(resumed.associationSaves == 0)+ withExtendedLifetime(fixture) {}+ }++ @Test(.enabled(if: ProcessInfo.processInfo.environment["ASTERISM_RUN_GROUP_SCALE"] == "1"))+ func groupHistoryScaleScopesOneThousandChaptersAwayFromFiveThousandOthers() async throws {+ let fixture = try await M5Fixture()+ let changedWorkID = UUID(), unrelatedWorkID = UUID(), groupID = UUID(), characterID = UUID()+ let firstChapterID = UUID()+ var changedIDs: Set<UUID> = [], unrelatedIDs: Set<UUID> = []+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding 1000 changed and 5000 unrelated chapters") { context in+ let changed = Work(id: changedWorkID, displayTitle: "Changed book", timestamp: M5Fixture.epoch)+ let unrelated = Work(id: unrelatedWorkID, displayTitle: "Other book", timestamp: M5Fixture.epoch)+ context.insert(changed); context.insert(unrelated)+ context.insert(CharacterRecord(id: characterID, name: "Bjorn", nameKey: "bjorn", work: changed))+ context.insert(NamedCharacterGroup(id: groupID, workID: changedWorkID))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: changedWorkID, operation: .create(name: "Team Loser")),+ recordedAt: M5Fixture.epoch))+ let transitionID = UUID()+ context.insert(try GroupTransition(fact: .init(id: transitionID,+ rootID: transitionID, workID: changedWorkID, groupID: groupID,+ characterID: characterID, chapterID: firstChapterID,+ action: .join), recordedAt: M5Fixture.epoch))+ for number in 1...6_000 {+ let isChanged = number <= 1_000+ let id = number == 1 ? firstChapterID : UUID()+ let chapterNumber = isChanged ? number : number - 1_000+ let row = Entry(id: id, captureTitle: "Chapter \(chapterNumber)",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch.addingTimeInterval(Double(number)),+ note: isChanged ? "Team Loser returns." : "No matching name.")+ try row.authorTarget(.init(kind: .chapter,+ designation: String(chapterNumber)))+ context.insert(row); row.work = isChanged ? changed : unrelated+ LibraryRepository.applyManualAssignment(to: row, at: M5Fixture.epoch)+ if isChanged { changedIDs.insert(id) } else { unrelatedIDs.insert(id) }+ if number.isMultiple(of: 250) { try context.save() }+ }+ try context.save()+ }+ let scopedIDs = try await fixture.repository.withLockedContext(mode: .shared,+ operation: "checking current Save chapter scope") { context in+ let rows = try context.fetch(FetchDescriptor<Work>(+ predicate: #Predicate { $0.id == changedWorkID }))+ let work = try #require(LibraryRepository.workGroup(id: changedWorkID,+ rows: rows, types: LibraryRepository.workTypeDirectory(context: context)))+ return try Set(GroupSupportInventory.chapters(work: work, context: context).map(\.id))+ }+ #expect(scopedIDs == changedIDs && scopedIDs.isDisjoint(with: unrelatedIDs))+ let clock = ContinuousClock()+ let started = clock.now+ let report = try await fixture.repository.reconcileGroupHistory()+ let elapsed = clock.now - started+ print("T-2491 group-history M4-class 1000+5000 elapsed: \(elapsed)")+ #expect(report.selectedWorkIDs == [changedWorkID])+ #expect(report.scannedChapterIDs.count == 1_000)+ #expect(Set(report.scannedChapterIDs) == changedIDs)+ #expect(Set(report.scannedChapterIDs).isDisjoint(with: unrelatedIDs))+ #expect(report.batchSizes == Array(repeating: 128, count: 7) + [104])+ #expect(report.associationSaves == 8)+ #expect(try await fixture.repository.reconcileGroupHistory().batchSizes.isEmpty)+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupStorageTests.swiftnew file mode 100644index 00000000..6df640a2--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupStorageTests.swift@@ -0,0 +1,100 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group physical storage", .serialized)+struct NamedGroupStorageTests {+ private func context() throws -> (ModelContainer, ModelContext) {+ let schema = Schema(versionedSchema: AsterismSchemaV22.self)+ let container = try ModelContainer(for: schema, configurations: [+ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)])+ return (container, ModelContext(container))+ }++ @Test("V22 rows persist and restore a chapter roster")+ func roundTrip() throws {+ let (container, context) = try context()+ let work = UUID(), group = UUID(), person = UUID(), chapter = UUID()+ let create = GroupFact(groupID: group, workID: work,+ operation: .create(name: "Team Loser"))+ let joinID = UUID()+ let join = GroupTransitionFact(id: joinID, rootID: joinID, workID: work, groupID: group,+ characterID: person, chapterID: chapter, action: .join)+ context.insert(NamedCharacterGroup(id: group, workID: work))+ context.insert(try GroupFactEvent(fact: create, recordedAt: .distantPast))+ context.insert(try GroupTransition(fact: join, recordedAt: .distantPast))+ try context.save()+ let projection = GroupRoster.project(workID: work,+ chapters: [.init(id: chapter, label: "38")],+ groupRows: try context.fetch(FetchDescriptor<NamedCharacterGroup>()),+ factRows: try context.fetch(FetchDescriptor<GroupFactEvent>()),+ transitionRows: try context.fetch(FetchDescriptor<GroupTransition>()))+ #expect(projection.groups.first?.name == "Team Loser")+ #expect(projection.members(groupID: group, chapterID: chapter) == [person])+ #expect(projection.ranges(groupID: group, characterID: person).first?.startLabel == "38")+ withExtendedLifetime(container) {}+ }++ @Test("Divergent physical copies quarantine a fact and a transition")+ func conflictingTwins() throws {+ let (container, context) = try context()+ let work = UUID(), group = UUID(), person = UUID(), chapter = UUID()+ let create = GroupFact(groupID: group, workID: work,+ operation: .create(name: "Team Loser"))+ let alias = GroupFact(groupID: group, workID: work, parentHeadIDs: [create.id],+ operation: .addAlias("Losers"))+ let joinID = UUID()+ let join = GroupTransitionFact(id: joinID, rootID: joinID, workID: work,+ groupID: group, characterID: person,+ chapterID: chapter, action: .join)+ context.insert(NamedCharacterGroup(id: group, workID: work))+ context.insert(try GroupFactEvent(fact: create, recordedAt: .distantPast))+ let goodAlias = try GroupFactEvent(fact: alias, recordedAt: .distantPast)+ let badAlias = try GroupFactEvent(fact: alias, recordedAt: .distantPast)+ badAlias.payloadData = Data("wrong alias".utf8)+ context.insert(goodAlias); context.insert(badAlias)+ let goodJoin = try GroupTransition(fact: join, recordedAt: .distantPast)+ let badJoin = try GroupTransition(fact: join, recordedAt: .distantPast)+ badJoin.entryID = UUID()+ context.insert(goodJoin); context.insert(badJoin)+ try context.save()+ let projection = GroupRoster.project(workID: work,+ chapters: [.init(id: chapter, label: "38")],+ groupRows: try context.fetch(FetchDescriptor<NamedCharacterGroup>()),+ factRows: try context.fetch(FetchDescriptor<GroupFactEvent>()),+ transitionRows: try context.fetch(FetchDescriptor<GroupTransition>()))+ #expect(projection.groups.first?.name == "Team Loser")+ #expect(projection.groups.first?.aliases == [])+ #expect(projection.members(groupID: group, chapterID: chapter).isEmpty)+ withExtendedLifetime(container) {}+ }++ @Test("A disputed physical leave cannot leave an earlier independent join open")+ func disputedPhysicalLeave() throws {+ let (container, context) = try context()+ let work = UUID(), group = UUID(), person = UUID()+ let chapters = (1...13).map { GroupChapter(id: UUID(), label: String($0)) }+ let create = GroupFact(groupID: group, workID: work,+ operation: .create(name: "Team Loser"))+ let joinID = UUID(), leaveID = UUID()+ let join = GroupTransitionFact(id: joinID, rootID: joinID, workID: work,+ groupID: group, characterID: person, chapterID: chapters[4].id, action: .join)+ let leave = GroupTransitionFact(id: leaveID, rootID: leaveID, workID: work,+ groupID: group, characterID: person, chapterID: chapters[9].id, action: .leave)+ context.insert(NamedCharacterGroup(id: group, workID: work))+ context.insert(try GroupFactEvent(fact: create, recordedAt: .distantPast))+ context.insert(try GroupTransition(fact: join, recordedAt: .distantPast))+ let goodLeave = try GroupTransition(fact: leave, recordedAt: .distantPast)+ let competingLeave = try GroupTransition(fact: leave, recordedAt: .distantPast)+ competingLeave.entryID = chapters[11].id+ context.insert(goodLeave); context.insert(competingLeave)+ try context.save()+ let projection = GroupRoster.project(workID: work, chapters: chapters,+ groupRows: try context.fetch(FetchDescriptor<NamedCharacterGroup>()),+ factRows: try context.fetch(FetchDescriptor<GroupFactEvent>()),+ transitionRows: try context.fetch(FetchDescriptor<GroupTransition>()))+ #expect(projection.members(groupID: group, chapterID: chapters[12].id).isEmpty)+ withExtendedLifetime(container) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSuggestionApprovalTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSuggestionApprovalTests.swiftnew file mode 100644index 00000000..53f45b92--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSuggestionApprovalTests.swift@@ -0,0 +1,219 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group suggestion approval", .serialized)+struct NamedGroupSuggestionApprovalTests {+ private func fixture() async throws -> (M5Fixture, UUID, UUID, UUID) {+ let fixture = try await M5Fixture()+ let workID = UUID(), chapterID = UUID(), characterID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding group suggestion") { context in+ let work = Work(id: workID, displayTitle: "Book", timestamp: M5Fixture.epoch)+ context.insert(work)+ context.insert(CharacterRecord(id: characterID, name: "Missha",+ nameKey: "missha", work: work))+ let chapter = Entry(id: chapterID, captureTitle: "Chapter 38",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Missha joins Team Loser.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "38"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ return (fixture, workID, chapterID, characterID)+ }++ private func leaveFixture() async throws -> (M5Fixture, UUID, [UUID], UUID, UUID) {+ let fixture = try await M5Fixture()+ let workID = UUID(), characterID = UUID(), groupID = UUID()+ let chapters = (1...3).map { _ in UUID() }+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding group leave journey") { context in+ let work = Work(id: workID, displayTitle: "Book", timestamp: M5Fixture.epoch)+ context.insert(work)+ context.insert(CharacterRecord(id: characterID, name: "Ainar",+ nameKey: "ainar", work: work))+ for (offset, chapterID) in chapters.enumerated() {+ let number = offset + 1+ let note = number == 2+ ? "Ainar leaves Team Loser after the match."+ : "Chapter \(number)."+ let chapter = Entry(id: chapterID, captureTitle: "Chapter \(number)",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: Date(timeIntervalSince1970:+ M5Fixture.epoch.timeIntervalSince1970 + Double(number)), note: note)+ try chapter.authorTarget(.init(kind: .chapter, designation: "\(number)"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ }+ try context.save()+ }+ let (first, _) = (chapters[0], chapters[1])+ let joinID = UUID()+ let setup = try await fixture.repository.commitGroupEdits(workID: workID, operations: [+ .create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: joinID, groupID: groupID, characterID: characterID,+ chapterID: first, action: .join),+ ], currentChapterID: first)+ guard case .committed = setup else { throw NamedGroupSuggestionFixtureError.setupFailed }+ let created = try #require(try await fixture.repository.characterGroups(workID: workID).first)+ let alias = try await fixture.repository.commitGroupEdits(workID: workID, operations: [+ .fact(groupID: groupID, expectedEventIDs: created.factEventIDs,+ operation: .addAlias("Losers")),+ ], currentChapterID: first)+ guard case .committed = alias else { throw NamedGroupSuggestionFixtureError.setupFailed }+ return (fixture, workID, chapters, characterID, groupID)+ }++ @Test("Approved group and join publish the current character link")+ func approvalIsImmediate() async throws {+ let (fixture, workID, chapterID, characterID) = try await fixture()+ let fingerprint = CharacterCoverageFingerprint.of("Missha joins Team Loser.")+ let groupID = UUID(), joinID = UUID()+ let approval = GroupSuggestionApproval(chapterID: chapterID,+ sourceFingerprint: fingerprint, groupName: "Team Loser",+ characterName: "Missha", quote: "Missha joins Team Loser",+ plannedGroupID: groupID, plannedTransitionID: joinID)+ #expect(try await fixture.repository.groupSuggestionMembershipIsEffective(workID: workID,+ chapterID: chapterID, groupName: "Team Loser", characterName: "Missha") == false)+ #expect(try await fixture.repository.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(approval)], currentChapterID: chapterID) ==+ .committed(groupIDs: [groupID]))+ let group = try #require(try await fixture.repository.characterGroups(workID: workID).first)+ #expect(group.members[characterID]?.count == 1)+ #expect(try await fixture.repository.groupSuggestionMembershipIsEffective(workID: workID,+ chapterID: chapterID, groupName: "Team Loser", characterName: "Missha"))+ let pair = AssociationPair(workID: workID, entryID: chapterID,+ kind: .character, recordID: characterID)+ #expect(try await fixture.repository.chapterAssociations(entryID: chapterID)+ .contains { $0.pair == pair && !$0.activeAcceptanceIDs.isEmpty })+ }++ @Test("A changed note or invented join quote refuses without partial rows")+ func staleApprovalRefuses() async throws {+ let (fixture, workID, chapterID, _) = try await fixture()+ let before = try await fixture.repository.backupV21Snapshot()+ for (fingerprint, quote) in [("old-note", "Missha joins Team Loser"),+ (CharacterCoverageFingerprint.of("Missha joins Team Loser."),+ "Bjorn joins Team Loser")] {+ let approval = GroupSuggestionApproval(chapterID: chapterID,+ sourceFingerprint: fingerprint, groupName: "Team Loser",+ characterName: "Missha", quote: quote,+ plannedGroupID: UUID(), plannedTransitionID: UUID())+ #expect(try await fixture.repository.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(approval)], currentChapterID: chapterID) ==+ .refused(.stale))+ }+ #expect(try await fixture.repository.backupV21Snapshot() == before)+ }++ @Test("An already effective membership cannot be approved a second time")+ func duplicateJoinRefuses() async throws {+ let (fixture, workID, chapterID, _) = try await fixture()+ let fingerprint = CharacterCoverageFingerprint.of("Missha joins Team Loser.")+ let first = GroupSuggestionApproval(chapterID: chapterID,+ sourceFingerprint: fingerprint, groupName: "Team Loser",+ characterName: "Missha", quote: "Missha joins Team Loser",+ plannedGroupID: UUID(), plannedTransitionID: UUID())+ guard case .committed = try await fixture.repository.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(first)], currentChapterID: chapterID) else {+ Issue.record("First approval should commit")+ return+ }+ let before = try await fixture.repository.backupV21Snapshot()+ let repeated = GroupSuggestionApproval(chapterID: chapterID,+ sourceFingerprint: fingerprint, groupName: "Team Loser",+ characterName: "Missha", quote: "Missha joins Team Loser",+ plannedGroupID: UUID(), plannedTransitionID: UUID())+ #expect(try await fixture.repository.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(repeated)], currentChapterID: chapterID) ==+ .refused(.stale))+ #expect(try await fixture.repository.backupV21Snapshot() == before)+ }++ @Test("Reviewed leave is recorded at its chapter and keeps the inclusive end boundary")+ func approvedLeaveHasInclusiveChapterBoundary() async throws {+ let (fixture, workID, chapters, characterID, groupID) = try await leaveFixture()+ let chapterID = chapters[1]+ let note = "Ainar leaves Team Loser after the match."+ let approval = GroupSuggestionApproval(chapterID: chapterID,+ sourceFingerprint: CharacterCoverageFingerprint.of(note), groupName: "Team Loser",+ characterName: "Ainar", quote: "Ainar leaves Team Loser", action: .leave,+ plannedGroupID: groupID, plannedTransitionID: UUID())++ #expect(try await fixture.repository.groupSuggestionMembershipIsEffective(workID: workID,+ chapterID: chapterID, groupName: "Team Loser", characterName: "Ainar"))+ let initialLeaveOutcome = try await fixture.repository.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(approval)], currentChapterID: chapterID)+ #expect(initialLeaveOutcome == .committed(groupIDs: []))+ #expect(try await fixture.repository.groupSuggestionMembershipIsEffective(workID: workID,+ chapterID: chapterID, groupName: "Team Loser", characterName: "Ainar"))+ #expect(try await fixture.repository.groupSuggestionMembershipIsEffective(workID: workID,+ chapterID: chapters[2], groupName: "Team Loser", characterName: "Ainar") == false)+ let group = try #require(try await fixture.repository.characterGroups(workID: workID)+ .first { $0.groupID == groupID })+ #expect(group.transitions.contains { $0.chapterID == chapterID &&+ $0.characterID == characterID && $0.action == .leave })+ #expect(group.members[characterID]?.first?.endChapterID == chapterID)+ #expect(try await fixture.repository.groupSuggestionLeaveIsApplicable(+ workID: workID, chapterID: chapterID,+ groupName: "Losers", characterName: "Ainar") == false)++ let beforeDuplicate = try await fixture.repository.backupV21Snapshot()+ let duplicate = GroupSuggestionApproval(chapterID: chapterID,+ sourceFingerprint: CharacterCoverageFingerprint.of(note), groupName: "Team Loser",+ characterName: "Ainar", quote: "Ainar leaves Team Loser", action: .leave,+ plannedGroupID: groupID, plannedTransitionID: UUID())+ #expect(try await fixture.repository.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(duplicate)], currentChapterID: chapterID) ==+ .refused(.stale))+ #expect(try await fixture.repository.backupV21Snapshot() == beforeDuplicate)++ let extensionChapter = chapters[2]+ let extensionNote = "Ainar leaves Losers again after chapter 41."+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "updating later leave evidence") { context in+ let entry = try #require(context.fetch(FetchDescriptor<Entry>())+ .first { $0.id == extensionChapter })+ entry.note = extensionNote+ try context.save()+ }+ #expect(try await fixture.repository.groupSuggestionLeaveIsApplicable(+ workID: workID, chapterID: extensionChapter,+ groupName: "Losers", characterName: "Ainar"))+ let extensionApproval = GroupSuggestionApproval(chapterID: extensionChapter,+ sourceFingerprint: CharacterCoverageFingerprint.of(extensionNote),+ groupName: "Losers", characterName: "Ainar",+ quote: "Ainar leaves Losers again", action: .leave,+ plannedGroupID: groupID, plannedTransitionID: UUID())+ let extensionOutcome = try await fixture.repository.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(extensionApproval)], currentChapterID: extensionChapter)+ #expect(extensionOutcome == .committed(groupIDs: []))+ let extended = try #require(try await fixture.repository.characterGroups(workID: workID)+ .first { $0.groupID == groupID })+ #expect(extended.members[characterID]?.first?.endChapterID == extensionChapter)+ }++ @Test("A leave approval with an old chapter revision is stale")+ func staleLeaveApprovalRefuses() async throws {+ let (fixture, workID, chapters, _, groupID) = try await leaveFixture()+ let chapterID = chapters[1]+ let approval = GroupSuggestionApproval(chapterID: chapterID,+ sourceFingerprint: "old-revision", groupName: "Team Loser",+ characterName: "Ainar", quote: "Ainar leaves Team Loser", action: .leave,+ plannedGroupID: groupID, plannedTransitionID: UUID())+ let before = try await fixture.repository.backupV21Snapshot()++ #expect(try await fixture.repository.commitGroupEdits(workID: workID,+ operations: [.approveSuggestion(approval)], currentChapterID: chapterID) ==+ .refused(.stale))+ #expect(try await fixture.repository.backupV21Snapshot() == before)+ }+}++private enum NamedGroupSuggestionFixtureError: Error {+ case setupFailed+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSuggestionSkipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSuggestionSkipTests.swiftnew file mode 100644index 00000000..8b86ddd4--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupSuggestionSkipTests.swift@@ -0,0 +1,75 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group suggestion skip", .serialized)+struct NamedGroupSuggestionSkipTests {+ @Test("A skipped leave validates and survives a repository restart")+ func durableLeaveSkip() async throws {+ let fixture = try await M5Fixture()+ let workID = UUID(), chapterID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding group leave skip") { context in+ let work = Work(id: workID, displayTitle: "Book", timestamp: M5Fixture.epoch)+ context.insert(work)+ let note = "Ainar leaves Team Loser after the match."+ let chapter = Entry(id: chapterID, captureTitle: "Chapter 38",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch, note: note)+ try chapter.authorTarget(.init(kind: .chapter, designation: "38"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ let skip = GroupSuggestionSkip(workID: workID, chapterID: chapterID,+ kind: .leave, groupKey: "team loser", characterKey: "ainar",+ evidenceKey: "Ainar leaves Team Loser")+ let fingerprint = CharacterCoverageFingerprint.of("Ainar leaves Team Loser after the match.")+ #expect(try await fixture.repository.skipGroupSuggestion(skip,+ sourceFingerprint: fingerprint) == .committed(groupIDs: []))+ #expect(try await fixture.repository.groupSuggestionSkips(workID: workID).contains(skip))+ await fixture.repository.shutdown()+ let reopened = try await LibraryRepository.openForApp(+ .init(rootDirectory: fixture.directory)).repository+ #expect(try await reopened.groupSuggestionSkips(workID: workID).contains(skip))+ }++ @Test("A skipped join stays scoped to equivalent evidence across unrelated note edits and restart")+ func durableEvidenceScopedSkip() async throws {+ let fixture = try await M5Fixture()+ let workID = UUID(), chapterID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding group suggestion skip") { context in+ let work = Work(id: workID, displayTitle: "Book", timestamp: M5Fixture.epoch)+ context.insert(work)+ let chapter = Entry(id: chapterID, captureTitle: "Chapter 38",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Missha joins Team Loser.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "38"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ let skip = GroupSuggestionSkip(workID: workID, chapterID: chapterID,+ kind: .join, groupKey: "team loser", characterKey: "missha",+ evidenceKey: "Missha joins Team Loser")+ #expect(try await fixture.repository.skipGroupSuggestion(skip,+ sourceFingerprint: CharacterCoverageFingerprint.of("Missha joins Team Loser.")) ==+ .committed(groupIDs: []))+ #expect(try await fixture.repository.groupSuggestionSkips(workID: workID).contains(skip))+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "adding unrelated sentence") { context in+ let entry = try #require(context.fetch(FetchDescriptor<Entry>())+ .first { $0.id == chapterID })+ entry.note = "Missha joins Team Loser. The moon rises."+ try context.save()+ }+ #expect(try await fixture.repository.groupSuggestionSkips(workID: workID).contains(skip))+ await fixture.repository.shutdown()+ let reopened = try await LibraryRepository.openForApp(+ .init(rootDirectory: fixture.directory)).repository+ #expect(try await reopened.groupSuggestionSkips(workID: workID).contains(skip))+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupWorkMergeEditTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupWorkMergeEditTests.swiftnew file mode 100644index 00000000..b0f54cf8--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupWorkMergeEditTests.swift@@ -0,0 +1,1037 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group edits after Work merge", .serialized)+struct NamedGroupWorkMergeEditTests {+ private struct Merged {+ let fixture: M5Fixture+ let repository: LibraryRepository+ let targetID: UUID+ let characterID: UUID+ let chapterID: UUID+ let group: GroupSummary+ let inheritedRootID: UUID+ let originalRoot: GroupTransitionFact+ let originalFact: GroupFact+ let sourceHeadIDs: [UUID]+ }++ private func mergedGroup(saveStrategy: any RepositorySaveStrategy = ModelContextSaveStrategy(),+ siblingActions: [GroupTransitionAction] = [])+ async throws -> Merged {+ let fixture = try await M5Fixture(saveStrategy: saveStrategy)+ let repository = fixture.repository+ let source = try await repository.createWork(+ .init(displayTitle: "Source book", hostname: "merge.example"))+ let target = try await repository.createWork(+ .init(displayTitle: "Target book", hostname: "merge.example"))+ let characterID = UUID(), chapterID = UUID(), sourceGroupID = UUID(), rootID = UUID()+ try await repository.withLockedContext(mode: .exclusive,+ operation: "seeding source group before Work merge") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == source.id })+ context.insert(CharacterRecord(id: characterID, name: "Bjorn",+ nameKey: "bjorn", work: work))+ let chapter = Entry(id: chapterID, captureTitle: "Chapter 1",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Team Loser returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "1"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ #expect(try await repository.commitGroupEdits(workID: source.id, operations: [+ .create(groupID: sourceGroupID, name: "Team Loser"),+ .transition(rootID: rootID, groupID: sourceGroupID,+ characterID: characterID, chapterID: chapterID, action: .join)+ ]) == .committed(groupIDs: [sourceGroupID]))+ let sourceHeadIDs = siblingActions.map { _ in UUID() }+ if !sourceHeadIDs.isEmpty {+ try await repository.withLockedContext(mode: .exclusive,+ operation: "seeding concurrent source membership heads") { context in+ for (id, action) in zip(sourceHeadIDs, siblingActions) {+ context.insert(try GroupTransition(fact: .init(id: id,+ rootID: rootID, workID: source.id, groupID: sourceGroupID,+ characterID: characterID, chapterID: chapterID,+ parentHeadIDs: [rootID], action: action),+ recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ }+ let original = try await repository.withLockedContext(mode: .shared,+ operation: "reading immutable source group events") { context in+ let root = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.id == rootID }?.transitionValue)+ let fact = try #require(context.fetch(FetchDescriptor<GroupFactEvent>())+ .first { $0.groupID == sourceGroupID }?.factValue)+ return (root, fact)+ }+ #expect(try await repository.commitMerge(+ try await repository.projectMerge(sourceWorkID: source.id, targetWorkID: target.id))+ == .committed(targetID: target.id))+ let group = try #require(try await repository.characterGroups(workID: target.id).first)+ #expect(group.groupID != sourceGroupID)+ #expect(group.name == "Team Loser")+ if Set(siblingActions).count <= 1 {+ #expect(group.transitions.contains { $0.rootID == rootID && $0.workID == target.id })+ } else {+ #expect(group.conflictedTransitions.contains { $0.rootID == rootID })+ }+ return Merged(fixture: fixture, repository: repository, targetID: target.id,+ characterID: characterID, chapterID: chapterID, group: group,+ inheritedRootID: rootID, originalRoot: original.0, originalFact: original.1,+ sourceHeadIDs: sourceHeadIDs)+ }++ @Test("Work merge preserves equivalent concurrent membership heads as one editable successor")+ func equivalentSourceHeadsSurviveMerge() async throws {+ let merged = try await mergedGroup(siblingActions: [.join, .join])+ let group = merged.group, rootID = merged.inheritedRootID+ #expect(group.members[merged.characterID]?.count == 1)+ let successor = try #require(group.transitions.first {+ $0.rootID == rootID && $0.workID == merged.targetID+ })+ #expect(Set(successor.parentHeadIDs) == Set(merged.sourceHeadIDs))+ #expect(group.transitionEventIDs[rootID] == [successor.id])+ let originalID = merged.sourceHeadIDs[0]+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "delivering late equivalent source head copy") { context in+ let original = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.id == originalID })+ context.insert(GroupTransition(raw: GroupRawTransition(original)))+ try context.save()+ }+ #expect(try await merged.repository.characterGroups(workID: merged.targetID)+ .first?.members[merged.characterID]?.count == 1)+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Work merge keeps divergent source heads editable on the surviving Work")+ func divergentSourceHeadsSurviveMerge() async throws {+ let merged = try await mergedGroup(siblingActions: [.join, .leave])+ let group = merged.group, rootID = merged.inheritedRootID+ #expect(group.members[merged.characterID] == nil)+ let conflict = try #require(group.conflictedTransitions.first { $0.rootID == rootID })+ #expect(conflict.characterID == merged.characterID)+ #expect(conflict.heads.count == 2)+ #expect(Set(conflict.heads.flatMap(\.parentHeadIDs)) == Set(merged.sourceHeadIDs))+ #expect(Set(conflict.expectedEventIDs) == Set(conflict.heads.map(\.id)))+ let lateID = merged.sourceHeadIDs[1]+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "delivering late divergent source head copy") { context in+ let original = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.id == lateID })+ context.insert(GroupTransition(raw: GroupRawTransition(original)))+ try context.save()+ }+ #expect(try await merged.repository.characterGroups(workID: merged.targetID)+ .first?.conflictedTransitions.first?.expectedEventIDs == conflict.expectedEventIDs)+ #expect(try await merged.repository.commitGroupEdits(workID: merged.targetID,+ operations: [.reviseTransition(rootID: rootID,+ expectedEventIDs: conflict.expectedEventIDs,+ chapterID: merged.chapterID, action: .join)]) == .committed(groupIDs: []))+ let resolved = try #require(try await merged.repository.characterGroups(+ workID: merged.targetID).first)+ #expect(resolved.conflictedTransitions.isEmpty)+ #expect(resolved.members[merged.characterID]?.count == 1)+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Work merge refuses an unresolved source group name without deleting its authored facts")+ func unresolvedSourceNameRefusesMerge() async throws {+ let fixture = try await M5Fixture()+ let repository = fixture.repository+ let source = try await repository.createWork(+ .init(displayTitle: "Source book", hostname: "merge.example"))+ let target = try await repository.createWork(+ .init(displayTitle: "Target book", hostname: "merge.example"))+ let groupID = UUID()+ #expect(try await repository.commitGroupEdits(workID: source.id,+ operations: [.create(groupID: groupID, name: "Original Team")]) ==+ .committed(groupIDs: [groupID]))+ let rootID = try #require(try await repository.characterGroups(workID: source.id)+ .first?.factEventIDs.first)+ try await repository.withLockedContext(mode: .exclusive,+ operation: "seeding unresolved source group names") { context in+ for name in ["Northern Team", "Southern Team"] {+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: source.id, parentHeadIDs: [rootID],+ operation: .setName(name)), recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ #expect(try await repository.characterGroups(workID: source.id).first?.name == nil)+ let outcome = try await repository.commitMerge(+ try await repository.projectMerge(sourceWorkID: source.id,+ targetWorkID: target.id))+ guard case .invalidated = outcome else {+ Issue.record("Unresolved authored name must refuse the destructive Work merge: \(outcome)")+ return+ }+ #expect(try await repository.workDetail(id: source.id).work.id == source.id)+ #expect(try await repository.characterGroups(workID: source.id)+ .first?.factEventIDs.count == 3)+ #expect(try await repository.characterGroups(workID: target.id).isEmpty)+ withExtendedLifetime(fixture) {}+ }++ @Test("Unresolved source alias refuses Work merge until an ordinary alias edit resolves it")+ func unresolvedSourceAliasRefusesMerge() async throws {+ let fixture = try await M5Fixture()+ let repository = fixture.repository+ let source = try await repository.createWork(+ .init(displayTitle: "Source book", hostname: "merge.example"))+ let target = try await repository.createWork(+ .init(displayTitle: "Target book", hostname: "merge.example"))+ let groupID = UUID()+ #expect(try await repository.commitGroupEdits(workID: source.id,+ operations: [.create(groupID: groupID, name: "Healthy Team")]) ==+ .committed(groupIDs: [groupID]))+ let createID = try #require(try await repository.characterGroups(workID: source.id)+ .first?.factEventIDs.first)+ let aliasID = UUID(), removeA = UUID(), removeB = UUID(), readdB = UUID()+ try await repository.withLockedContext(mode: .exclusive,+ operation: "seeding concurrent remove and re-add alias histories") { context in+ for fact in [+ GroupFact(id: aliasID, groupID: groupID, workID: source.id,+ parentHeadIDs: [createID], operation: .addAlias("The Crew")),+ GroupFact(id: removeA, groupID: groupID, workID: source.id,+ parentHeadIDs: [aliasID], operation: .removeAlias("The Crew")),+ GroupFact(id: removeB, groupID: groupID, workID: source.id,+ parentHeadIDs: [aliasID], operation: .removeAlias("The Crew")),+ GroupFact(id: readdB, groupID: groupID, workID: source.id,+ parentHeadIDs: [removeB], operation: .addAlias("The Crew"))+ ] {+ context.insert(try GroupFactEvent(fact: fact,+ recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ let conflicted = try #require(try await repository.characterGroups(+ workID: source.id).first)+ #expect(conflicted.name == "Healthy Team")+ #expect(!conflicted.aliases.contains("The Crew"))+ let beforeFacts = try await repository.withLockedContext(mode: .shared,+ operation: "reading authored alias facts before refused merge") { context in+ Set(try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.groupID == groupID }.map(GroupRawFact.init))+ }+ let sourceBefore = try await repository.workDetail(id: source.id).work+ let targetBefore = try await repository.workDetail(id: target.id).work+ let outcome = try await repository.commitMerge(+ try await repository.projectMerge(sourceWorkID: source.id,+ targetWorkID: target.id))+ guard case .invalidated = outcome else {+ Issue.record("Disputed alias must refuse destructive Work merge: \(outcome)")+ return+ }+ #expect(try await repository.workDetail(id: source.id).work == sourceBefore)+ #expect(try await repository.workDetail(id: target.id).work == targetBefore)+ #expect(try await repository.characterGroups(workID: target.id).isEmpty)+ let afterFacts = try await repository.withLockedContext(mode: .shared,+ operation: "checking refused merge preserved alias facts") { context in+ Set(try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.groupID == groupID }.map(GroupRawFact.init))+ }+ #expect(afterFacts == beforeFacts)++ // The existing alias editor observes the complete current fact basis;+ // its explicit add resolves the two live heads without a new workflow.+ #expect(try await repository.commitGroupEdits(workID: source.id,+ operations: [.fact(groupID: groupID,+ expectedEventIDs: conflicted.factEventIDs,+ operation: .addAlias("The Crew"))]) == .committed(groupIDs: []))+ #expect(try await repository.characterGroups(workID: source.id)+ .first?.aliases.contains("The Crew") == true)+ #expect(try await repository.commitMerge(+ try await repository.projectMerge(sourceWorkID: source.id,+ targetWorkID: target.id)) == .committed(targetID: target.id))+ #expect(try await repository.characterGroups(workID: target.id)+ .first?.aliases.contains("The Crew") == true)+ withExtendedLifetime(fixture) {}+ }++ @Test("An ordinarily deleted source group does not block merge or revive")+ func deletedSourceGroupDoesNotBlockMerge() async throws {+ let fixture = try await M5Fixture()+ let repository = fixture.repository+ let source = try await repository.createWork(+ .init(displayTitle: "Source book", hostname: "merge.example"))+ let target = try await repository.createWork(+ .init(displayTitle: "Target book", hostname: "merge.example"))+ let deletedID = UUID(), healthyID = UUID()+ #expect(try await repository.commitGroupEdits(workID: source.id,+ operations: [.create(groupID: deletedID, name: "Old Team"),+ .create(groupID: healthyID, name: "Healthy Team")]) ==+ .committed(groupIDs: [deletedID, healthyID]))+ let deleted = try #require(try await repository.characterGroups(workID: source.id)+ .first { $0.groupID == deletedID })+ #expect(try await repository.commitGroupEdits(workID: source.id,+ operations: [.fact(groupID: deletedID,+ expectedEventIDs: deleted.factEventIDs, operation: .delete)]) ==+ .committed(groupIDs: []))+ #expect(try await repository.commitMerge(+ try await repository.projectMerge(sourceWorkID: source.id,+ targetWorkID: target.id)) == .committed(targetID: target.id))+ let surviving = try await repository.characterGroups(workID: target.id)+ #expect(surviving.map(\.name) == ["Healthy Team"])+ #expect(!surviving.contains { $0.groupID == deletedID })+ withExtendedLifetime(fixture) {}+ }++ @Test("Failed Work merge leaves compatible source heads and their Work intact")+ func failedMergeRollsBackConcurrentRebind() async throws {+ let strategy = ArmableFailingSaveStrategy()+ let fixture = try await M5Fixture(saveStrategy: strategy)+ let repository = fixture.repository+ let source = try await repository.createWork(+ .init(displayTitle: "Source book", hostname: "merge.example"))+ let target = try await repository.createWork(+ .init(displayTitle: "Target book", hostname: "merge.example"))+ let characterID = UUID(), chapterID = UUID(), groupID = UUID(), rootID = UUID()+ try await repository.withLockedContext(mode: .exclusive,+ operation: "seeding Work merge rollback member and chapter") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == source.id })+ context.insert(CharacterRecord(id: characterID, name: "Bjorn",+ nameKey: "bjorn", work: work))+ let chapter = Entry(id: chapterID, captureTitle: "Chapter 1",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Team Loser returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "1"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ #expect(try await repository.commitGroupEdits(workID: source.id,+ operations: [.create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: rootID, groupID: groupID,+ characterID: characterID, chapterID: chapterID,+ action: .join)]) == .committed(groupIDs: [groupID]))+ let siblingIDs = [UUID(), UUID()]+ try await repository.withLockedContext(mode: .exclusive,+ operation: "seeding equivalent heads before failed merge") { context in+ for id in siblingIDs {+ context.insert(try GroupTransition(fact: .init(id: id,+ rootID: rootID, workID: source.id, groupID: groupID,+ characterID: characterID, chapterID: chapterID,+ parentHeadIDs: [rootID], action: .join),+ recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ let beforeIDs = try await repository.withLockedContext(mode: .shared,+ operation: "reading transition IDs before failed merge") { context in+ Set(try context.fetch(FetchDescriptor<GroupTransition>()).map(\.id))+ }+ strategy.resetCount()+ strategy.failFrom = 1+ do {+ _ = try await repository.commitMerge(try await repository.projectMerge(+ sourceWorkID: source.id, targetWorkID: target.id))+ Issue.record("Injected Work merge save must fail")+ } catch { }+ strategy.failFrom = nil+ #expect(strategy.saveCount == 1)+ #expect(try await repository.workDetail(id: source.id).work.id == source.id)+ #expect(try await repository.characterGroups(workID: source.id)+ .first?.members[characterID]?.count == 1)+ #expect(try await repository.characterGroups(workID: target.id).isEmpty)+ let afterIDs = try await repository.withLockedContext(mode: .shared,+ operation: "checking failed merge wrote no successor") { context in+ Set(try context.fetch(FetchDescriptor<GroupTransition>()).map(\.id))+ }+ #expect(afterIDs == beforeIDs)+ #expect(try await repository.commitMerge(try await repository.projectMerge(+ sourceWorkID: source.id, targetWorkID: target.id)) ==+ .committed(targetID: target.id))+ #expect(try await repository.characterGroups(workID: target.id)+ .first?.members[characterID]?.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test("Late inherited fact hydration restarts completed target history with unchanged member set")+ func lateInheritedFactRestartsHistory() async throws {+ let merged = try await mergedGroup()+ let repository = merged.repository, targetID = merged.targetID+ let otherGroupID = UUID(), laterID = UUID()+ #expect(try await repository.commitGroupEdits(workID: targetID,+ operations: [.create(groupID: otherGroupID, name: "Alpha Team"),+ .transition(rootID: UUID(), groupID: otherGroupID,+ characterID: merged.characterID, chapterID: merged.chapterID,+ action: .join)]) == .committed(groupIDs: [otherGroupID]))+ let ancestorID = merged.originalFact.id+ let rawAncestor = try await repository.withLockedContext(mode: .exclusive,+ operation: "withholding one inherited fact ancestor") { context in+ let row = try #require(context.fetch(FetchDescriptor<GroupFactEvent>())+ .first { $0.id == ancestorID })+ let raw = GroupRawFact(row)+ context.delete(row)+ try context.save()+ return raw+ }+ try await repository.withLockedContext(mode: .exclusive,+ operation: "seeding later chapter that names only the withheld group") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == targetID })+ let chapter = Entry(id: laterID, captureTitle: "Chapter 2",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch.addingTimeInterval(60),+ note: "Team Loser returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "2"))+ context.insert(chapter); chapter.work = work+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ try await repository.invalidateGroupHistoryAfterImport()+ let first = try await repository.reconcileGroupHistory()+ #expect(first.scannedChapterIDs.contains(laterID))+ let pair = AssociationPair(workID: targetID, entryID: laterID,+ kind: .character, recordID: merged.characterID)+ #expect(try await repository.chapterAssociations(entryID: laterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs.isEmpty != false)+ #expect(try await repository.characterGroups(workID: targetID)+ .contains { $0.groupID == otherGroupID &&+ $0.members[merged.characterID]?.count == 1 })+ try await repository.withLockedContext(mode: .exclusive,+ operation: "hydrating the exact inherited fact ancestor") { context in+ context.insert(GroupFactEvent(raw: rawAncestor))+ try context.save()+ }+ let resumed = try await repository.reconcileGroupHistory()+ #expect(resumed.selectedWorkIDs.contains(targetID))+ #expect(resumed.scannedChapterIDs.contains(laterID))+ #expect(try await repository.chapterAssociations(entryID: laterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs.isEmpty == false)+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Merged group accepts current edits while preserving source ancestry and stale guards")+ func editMergedGroup() async throws {+ let merged = try await mergedGroup()+ let repository = merged.repository, targetID = merged.targetID+ let groupID = merged.group.groupID+ let renamed = try await repository.commitGroupEdits(workID: targetID, operations: [+ .fact(groupID: groupID, expectedEventIDs: merged.group.factEventIDs,+ operation: .setName("New Team"))])+ guard renamed == .committed(groupIDs: []) else {+ Issue.record("Merged group rename refused: \(renamed)")+ return+ }+ #expect(try await repository.commitGroupEdits(workID: targetID, operations: [+ .fact(groupID: groupID, expectedEventIDs: merged.group.factEventIDs,+ operation: .addAlias("Stale"))]) == .refused(.stale))++ var current = try #require(try await repository.characterGroups(workID: targetID).first)+ #expect(try await repository.commitGroupEdits(workID: targetID, operations: [+ .fact(groupID: groupID, expectedEventIDs: current.factEventIDs,+ operation: .addAlias("The Team"))]) == .committed(groupIDs: []))+ current = try #require(try await repository.characterGroups(workID: targetID).first)+ #expect(current.name == "New Team")+ #expect(current.aliases.contains("The Team"))+ let addedRootID = UUID()+ #expect(try await repository.commitGroupEdits(workID: targetID, operations: [+ .transition(rootID: addedRootID, groupID: groupID,+ characterID: merged.characterID, chapterID: merged.chapterID,+ action: .join)]) == .committed(groupIDs: []))++ current = try #require(try await repository.characterGroups(workID: targetID).first)+ let inheritedBasis = try #require(current.transitionEventIDs[merged.inheritedRootID])+ #expect(try await repository.commitGroupEdits(workID: targetID, operations: [+ .reviseTransition(rootID: merged.inheritedRootID,+ expectedEventIDs: inheritedBasis, chapterID: merged.chapterID,+ action: .leave)]) == .committed(groupIDs: []))+ #expect(try await repository.commitGroupEdits(workID: targetID, operations: [+ .reviseTransition(rootID: merged.inheritedRootID,+ expectedEventIDs: inheritedBasis, chapterID: merged.chapterID,+ action: .join)]) == .refused(.stale))+ current = try #require(try await repository.characterGroups(workID: targetID).first)+ #expect(try await repository.commitGroupEdits(workID: targetID, operations: [+ .fact(groupID: groupID, expectedEventIDs: current.factEventIDs,+ operation: .delete)]) == .committed(groupIDs: []))+ #expect(try await repository.characterGroups(workID: targetID).isEmpty)++ let inheritedRootID = merged.inheritedRootID+ let originalFactID = merged.originalFact.id+ let immutable = try await repository.withLockedContext(mode: .shared,+ operation: "checking source ancestry after destination edits") { context in+ let root = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.id == inheritedRootID }?.transitionValue)+ let fact = try #require(context.fetch(FetchDescriptor<GroupFactEvent>())+ .first { $0.id == originalFactID }?.factValue)+ return (root, fact)+ }+ #expect(immutable.0 == merged.originalRoot)+ #expect(immutable.1 == merged.originalFact)+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Repeated Work merge retains editable current heads over bounded source ancestry")+ func editAfterSecondMerge() async throws {+ let merged = try await mergedGroup()+ let third = try await merged.repository.createWork(+ .init(displayTitle: "Third book", hostname: "merge.example"))+ #expect(try await merged.repository.commitMerge(+ try await merged.repository.projectMerge(sourceWorkID: merged.targetID,+ targetWorkID: third.id)) == .committed(targetID: third.id))+ let current = try #require(try await merged.repository.characterGroups(workID: third.id).first)+ #expect(current.groupID != merged.group.groupID)+ #expect(current.name == "Team Loser")+ let currentBasis = try #require(current.transitionEventIDs[merged.inheritedRootID])+ #expect(try await merged.repository.commitGroupEdits(workID: third.id, operations: [+ .fact(groupID: current.groupID, expectedEventIDs: current.factEventIDs,+ operation: .setName("Third Team")),+ .reviseTransition(rootID: merged.inheritedRootID,+ expectedEventIDs: currentBasis, chapterID: merged.chapterID,+ action: .leave)]) == .committed(groupIDs: []))+ #expect(try await merged.repository.commitGroupEdits(workID: third.id, operations: [+ .reviseTransition(rootID: merged.inheritedRootID,+ expectedEventIDs: currentBasis, chapterID: merged.chapterID,+ action: .join)]) == .refused(.stale))+ #expect(try await merged.repository.characterGroups(workID: third.id).first?.name == "Third Team")+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Failed merged-group edit rolls back fact and transition together")+ func failedEditRollsBack() async throws {+ let strategy = ArmableFailingSaveStrategy()+ let merged = try await mergedGroup(saveStrategy: strategy)+ let basis = try #require(merged.group.transitionEventIDs[merged.inheritedRootID])+ let operations: [GroupEditOperation] = [+ .fact(groupID: merged.group.groupID,+ expectedEventIDs: merged.group.factEventIDs,+ operation: .setName("Unsaved Team")),+ .reviseTransition(rootID: merged.inheritedRootID,+ expectedEventIDs: basis, chapterID: merged.chapterID,+ action: .leave)]+ strategy.resetCount()+ strategy.failFrom = 1+ do {+ _ = try await merged.repository.commitGroupEdits(workID: merged.targetID,+ operations: operations)+ Issue.record("Injected merged-group save must fail")+ } catch { }+ strategy.failFrom = nil+ #expect(strategy.saveCount == 1)+ #expect(try await merged.repository.characterGroups(workID: merged.targetID)+ == [merged.group])+ #expect(try await merged.repository.commitGroupEdits(workID: merged.targetID,+ operations: operations) == .committed(groupIDs: []))+ #expect(try await merged.repository.characterGroups(workID: merged.targetID)+ .first?.name == "Unsaved Team")+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("A cross-Work physical twin cannot authorize an inherited transition revision")+ func conflictingTwinRefusesRevision() async throws {+ let merged = try await mergedGroup()+ let basis = try #require(merged.group.transitionEventIDs[merged.inheritedRootID])+ let successorID = try #require(basis.first)+ let targetID = merged.targetID+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "seeding conflicting merged transition twin") { context in+ let original = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.id == successorID && $0.workID == targetID })+ context.insert(GroupTransition(id: original.id, workID: UUID(),+ groupID: original.groupID, characterID: original.characterID,+ entryID: original.entryID, payloadData: original.payloadData,+ parentHeadIDsData: original.parentHeadIDsData,+ recordedAt: original.recordedAt))+ try context.save()+ }+ #expect(try await merged.repository.commitGroupEdits(workID: merged.targetID,+ operations: [.reviseTransition(rootID: merged.inheritedRootID,+ expectedEventIDs: basis, chapterID: merged.chapterID,+ action: .leave)]) == .refused(.stale))+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("A loaded alias basis refuses a later foreign-Work physical twin")+ func aliasTwinAfterBasisRefusesRename() async throws {+ let merged = try await mergedGroup()+ let groupID = merged.group.groupID, targetID = merged.targetID+ #expect(try await merged.repository.commitGroupEdits(workID: targetID,+ operations: [.fact(groupID: groupID,+ expectedEventIDs: merged.group.factEventIDs,+ operation: .addAlias("Known Alias"))]) == .committed(groupIDs: []))+ let loaded = try #require(try await merged.repository.characterGroups(workID: targetID).first)+ #expect(loaded.aliases.contains("Known Alias"))+ let aliasID = try #require(Set(loaded.factEventIDs)+ .subtracting(merged.group.factEventIDs).first)+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "seeding foreign-Work alias twin after editor load") { context in+ let alias = try #require(context.fetch(FetchDescriptor<GroupFactEvent>())+ .first { $0.id == aliasID && $0.workID == targetID })+ context.insert(GroupFactEvent(id: alias.id, workID: UUID(),+ groupID: alias.groupID, payloadData: alias.payloadData,+ parentHeadIDsData: alias.parentHeadIDsData,+ recordedAt: alias.recordedAt))+ try context.save()+ }+ let outcome = try await merged.repository.commitGroupEdits(workID: targetID,+ operations: [.fact(groupID: groupID,+ expectedEventIDs: loaded.factEventIDs,+ operation: .setName("Must Not Commit"))])+ #expect(outcome == .refused(.groupTorn))+ let factIDs = try await merged.repository.withLockedContext(mode: .shared,+ operation: "checking refused alias-twin rename") { context in+ try context.fetch(FetchDescriptor<GroupFactEvent>())+ .filter { $0.workID == targetID && $0.groupID == groupID }+ .map(\.id)+ }+ #expect(Set(factIDs) == Set(loaded.factEventIDs))+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Divergent inherited heads require a complete explicit resolution basis")+ func divergentHeadsRefuseRevision() async throws {+ let merged = try await mergedGroup()+ let rootID = merged.inheritedRootID, targetID = merged.targetID+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "seeding divergent merged transition heads") { context in+ let successor = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.workID == targetID && $0.transitionValue?.rootID == rootID })+ let head = try #require(successor.transitionValue)+ context.insert(try GroupTransition(fact: .init(rootID: rootID,+ workID: targetID, groupID: head.groupID,+ characterID: head.characterID, chapterID: head.chapterID,+ parentHeadIDs: head.parentHeadIDs, action: .leave),+ recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let disputed = try #require(try await merged.repository.characterGroups(+ workID: targetID).first)+ let currentBasis = try #require(disputed.transitionEventIDs[rootID])+ #expect(currentBasis.count == 2)+ #expect(disputed.transitions.allSatisfy { $0.rootID != rootID })+ #expect(disputed.conflictedTransitions.first?.expectedEventIDs.count == 2)+ #expect(try await merged.repository.commitGroupEdits(workID: targetID,+ operations: [.reviseTransition(rootID: rootID,+ expectedEventIDs: [currentBasis[0]], chapterID: merged.chapterID,+ action: .join)]) == .refused(.stale))+ let explicitResolution = try await merged.repository.commitGroupEdits(workID: targetID,+ operations: [.reviseTransition(rootID: rootID,+ expectedEventIDs: currentBasis, chapterID: merged.chapterID,+ action: .join)])+ #expect(explicitResolution == .committed(groupIDs: []))+ let resolved = try #require(try await merged.repository.characterGroups(workID: targetID).first)+ #expect(resolved.transitions.contains { $0.rootID == rootID && $0.action == .join })+ #expect(resolved.members[merged.characterID]?.isEmpty == false)+ #expect(try await merged.repository.commitGroupEdits(workID: targetID,+ operations: [.reviseTransition(rootID: rootID,+ expectedEventIDs: currentBasis, chapterID: merged.chapterID,+ action: .leave)]) == .refused(.stale))+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("An incomplete current-Work event cannot be silently included in a revision basis")+ func incompleteCurrentTransitionRefusesRevision() async throws {+ let merged = try await mergedGroup()+ let rootID = merged.inheritedRootID, targetID = merged.targetID+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "seeding an unhydrated current transition parent") { context in+ let current = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.workID == targetID && $0.transitionValue?.rootID == rootID }?+ .transitionValue)+ context.insert(try GroupTransition(fact: .init(rootID: rootID,+ workID: targetID, groupID: current.groupID,+ characterID: current.characterID, chapterID: current.chapterID,+ parentHeadIDs: [UUID()], action: .leave),+ recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let group = try #require(try await merged.repository.characterGroups(workID: targetID).first)+ let completeBasis = try #require(group.transitionEventIDs[rootID])+ #expect(completeBasis.count == 2)+ #expect(group.transitions.contains { $0.rootID == rootID })+ #expect(try await merged.repository.commitGroupEdits(workID: targetID,+ operations: [.reviseTransition(rootID: rootID,+ expectedEventIDs: completeBasis, chapterID: merged.chapterID,+ action: .join)]) == .refused(.stale))+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Late source removal after merge invalidates destination roster and completed history")+ func lateSourceRemovalTombstonesMergedMembership() async throws {+ let merged = try await mergedGroup()+ let targetID = merged.targetID, characterID = merged.characterID+ let chapterID = merged.chapterID, root = merged.originalRoot+ let sourceGroupID = merged.originalFact.groupID+ #expect(merged.group.members[characterID]?.isEmpty == false)+ try await merged.repository.invalidateGroupHistoryAfterImport()+ let completed = try await merged.repository.reconcileGroupHistory()+ #expect(completed.scannedChapterIDs.contains(chapterID))+ #expect(try await merged.repository.reconcileGroupHistory()+ .scannedChapterIDs.isEmpty)++ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "receiving late source removal after destination history completed") { context in+ context.insert(try GroupTransition(fact: .init(rootID: root.id,+ workID: root.workID, groupID: sourceGroupID,+ characterID: root.characterID, chapterID: root.chapterID,+ parentHeadIDs: [root.id], action: .remove),+ recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let events = try await merged.repository.withLockedContext(mode: .shared,+ operation: "comparing complete transition fold to repository inventory") { context in+ let facts = try context.fetch(FetchDescriptor<GroupFactEvent>())+ .compactMap(\.factValue)+ let transitions = try context.fetch(FetchDescriptor<GroupTransition>())+ .compactMap(\.transitionValue)+ return (facts, transitions)+ }+ let complete = GroupRoster.project(workID: targetID,+ chapters: [GroupChapter(id: chapterID, label: "Chapter 1")],+ facts: events.0, transitions: events.1)+ #expect(complete.groups.first?.members[characterID]?.isEmpty != false)+ let repositoryGroup = try #require(try await merged.repository.characterGroups(+ workID: targetID).first)+ #expect(repositoryGroup.members[characterID]?.isEmpty != false)+ let resumed = try await merged.repository.reconcileGroupHistory()+ #expect(resumed.selectedWorkIDs.contains(targetID))+ #expect(resumed.scannedChapterIDs.contains(chapterID))+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Connected transition inventory retains foreign twins but excludes unrelated roots")+ func connectedInventoryIncludesPhysicalVariants() async throws {+ let merged = try await mergedGroup()+ let root = merged.originalRoot, targetID = merged.targetID+ let foreignID = UUID(), unrelatedID = UUID()+ let unaffectedCharacterID = UUID(), unaffectedRootID = UUID()+ let sourceGroupID = merged.originalFact.groupID+ let targetGroupID = merged.group.groupID+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "seeding foreign transition variants and unrelated root") { context in+ let target = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == targetID })+ context.insert(CharacterRecord(id: unaffectedCharacterID,+ name: "Other member", nameKey: "other member", work: target))+ context.insert(try GroupTransition(fact: .init(id: unaffectedRootID,+ rootID: unaffectedRootID, workID: targetID,+ groupID: targetGroupID, characterID: unaffectedCharacterID,+ chapterID: root.chapterID, action: .join),+ recordedAt: M5Fixture.epoch))+ let successor = GroupTransitionFact(id: foreignID, rootID: root.id,+ workID: root.workID, groupID: sourceGroupID,+ characterID: root.characterID, chapterID: root.chapterID,+ parentHeadIDs: [root.id], action: .remove)+ let valid = try GroupTransition(fact: successor,+ recordedAt: M5Fixture.epoch)+ context.insert(valid)+ context.insert(GroupTransition(id: foreignID, workID: root.workID,+ groupID: sourceGroupID, characterID: root.characterID,+ entryID: root.chapterID, payloadData: Data("invalid".utf8),+ parentHeadIDsData: valid.parentHeadIDsData,+ recordedAt: valid.recordedAt))+ context.insert(try GroupTransition(fact: .init(id: unrelatedID,+ rootID: unrelatedID, workID: root.workID,+ groupID: sourceGroupID, characterID: root.characterID,+ chapterID: root.chapterID, action: .join),+ recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let selected = try await merged.repository.withLockedContext(mode: .shared,+ operation: "checking connected transition IDs") { context in+ try GroupSupportInventory.transitionRows(workID: targetID,+ context: context).map(\.id)+ }+ #expect(selected.filter { $0 == foreignID }.count == 2)+ #expect(!selected.contains(unrelatedID))+ #expect(selected.contains(root.id))+ let group = try #require(try await merged.repository.characterGroups(+ workID: targetID).first)+ #expect(group.members[merged.characterID]?.isEmpty != false)+ #expect(group.members[unaffectedCharacterID]?.isEmpty == false)+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Torn source ancestor hides merged support without retiring its recoverable root",+ arguments: ["transition", "fact"])+ func tornSourceAncestorKeepsAssociationRecoverable(kind: String) async throws {+ let merged = try await mergedGroup()+ let targetID = merged.targetID, chapterID = merged.chapterID+ let root = merged.originalRoot, sourceFact = merged.originalFact+ let entry = try await merged.repository.entry(id: chapterID)+ _ = try await merged.repository.updateEntry(id: chapterID,+ basis: .init(entry: entry), note: entry.note, rating: nil)+ _ = try await merged.repository.reconcileGroupHistory()+ let pair = AssociationPair(workID: targetID, entryID: chapterID,+ kind: .character, recordID: merged.characterID)+ let acceptanceID = try #require(try await merged.repository.chapterAssociations(+ entryID: chapterID).first(where: { $0.pair == pair })?+ .activeAcceptanceIDs.first)++ let brokenID = try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "seeding torn source ancestor after merge") { context in+ if kind == "transition" {+ let original = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.id == root.id && $0.workID == root.workID })+ let twin = GroupTransition(id: original.id, workID: original.workID,+ groupID: original.groupID, characterID: original.characterID,+ entryID: original.entryID, payloadData: Data("invalid".utf8),+ parentHeadIDsData: original.parentHeadIDsData,+ recordedAt: original.recordedAt)+ context.insert(twin); try context.save()+ return twin.persistentModelID+ }+ let original = try #require(context.fetch(FetchDescriptor<GroupFactEvent>())+ .first { $0.id == sourceFact.id && $0.workID == sourceFact.workID })+ let twin = GroupFactEvent(id: original.id, workID: original.workID,+ groupID: original.groupID, payloadData: Data("invalid".utf8),+ parentHeadIDsData: original.parentHeadIDsData,+ recordedAt: original.recordedAt)+ context.insert(twin); try context.save()+ return twin.persistentModelID+ }+ #expect(try await merged.repository.characterGroups(workID: targetID)+ .first?.members[merged.characterID]?.isEmpty != false)+ _ = try await merged.repository.reconcileGroupHistory()+ #expect(try await merged.repository.chapterAssociations(entryID: chapterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs.isEmpty == true)+ let recoverable = try await merged.repository.withLockedContext(mode: .shared,+ operation: "checking merged support remains recoverable") { context in+ try AssociationStorageInventory.read(context: context,+ workIDs: [targetID], includeNotes: false).ledger+ .canRevalidateAcceptance(acceptanceID, pair: pair)+ }+ #expect(recoverable)+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "repairing torn source ancestor after merge") { context in+ if kind == "transition" {+ let twin = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.persistentModelID == brokenID })+ context.delete(twin)+ } else {+ let twin = try #require(context.fetch(FetchDescriptor<GroupFactEvent>())+ .first { $0.persistentModelID == brokenID })+ context.delete(twin)+ }+ try context.save()+ }+ _ = try await merged.repository.reconcileGroupHistory()+ #expect(try await merged.repository.chapterAssociations(entryID: chapterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs == [acceptanceID])+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Missing source ancestor keeps merged acceptance recoverable until hydration",+ arguments: ["transition", "fact"])+ func missingSourceAncestorKeepsAssociationRecoverable(kind: String) async throws {+ let merged = try await mergedGroup()+ let targetID = merged.targetID, chapterID = merged.chapterID+ let root = merged.originalRoot, sourceFact = merged.originalFact+ let entry = try await merged.repository.entry(id: chapterID)+ _ = try await merged.repository.updateEntry(id: chapterID,+ basis: .init(entry: entry), note: entry.note, rating: nil)+ _ = try await merged.repository.reconcileGroupHistory()+ let pair = AssociationPair(workID: targetID, entryID: chapterID,+ kind: .character, recordID: merged.characterID)+ let acceptanceID = try #require(try await merged.repository.chapterAssociations(+ entryID: chapterID).first(where: { $0.pair == pair })?+ .activeAcceptanceIDs.first)+ let originalBytes = try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "temporarily omitting immutable source ancestor") { context in+ if kind == "transition" {+ let row = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.id == root.id && $0.workID == root.workID })+ let bytes = (row.payloadData, row.parentHeadIDsData, row.recordedAt)+ context.delete(row); try context.save()+ return bytes+ }+ let row = try #require(context.fetch(FetchDescriptor<GroupFactEvent>())+ .first { $0.id == sourceFact.id && $0.workID == sourceFact.workID })+ let bytes = (row.payloadData, row.parentHeadIDsData, row.recordedAt)+ context.delete(row); try context.save()+ return bytes+ }+ _ = try await merged.repository.reconcileGroupHistory()+ #expect(try await merged.repository.chapterAssociations(entryID: chapterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs.isEmpty == true)+ let recoverable = try await merged.repository.withLockedContext(mode: .shared,+ operation: "checking absent source ancestry did not retire support") { context in+ try AssociationStorageInventory.read(context: context,+ workIDs: [targetID], includeNotes: false).ledger+ .canRevalidateAcceptance(acceptanceID, pair: pair)+ }+ #expect(recoverable)+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "hydrating exact immutable source ancestor") { context in+ if kind == "transition" {+ context.insert(GroupTransition(id: root.id, workID: root.workID,+ groupID: root.groupID, characterID: root.characterID,+ entryID: root.chapterID, payloadData: originalBytes.0,+ parentHeadIDsData: originalBytes.1,+ recordedAt: originalBytes.2))+ } else {+ context.insert(GroupFactEvent(id: sourceFact.id,+ workID: sourceFact.workID, groupID: sourceFact.groupID,+ payloadData: originalBytes.0,+ parentHeadIDsData: originalBytes.1,+ recordedAt: originalBytes.2))+ }+ try context.save()+ }+ _ = try await merged.repository.reconcileGroupHistory()+ #expect(try await merged.repository.chapterAssociations(entryID: chapterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs == [acceptanceID])+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Unhydrated earlier join chapter does not retire later merged acceptance")+ func missingJoinAnchorKeepsLaterAcceptanceRecoverable() async throws {+ let merged = try await mergedGroup()+ let targetID = merged.targetID, anchorID = merged.chapterID+ let laterID = UUID()+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "seeding later chapter with merged group mention") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == targetID })+ let later = Entry(id: laterID, captureTitle: "Chapter 2",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch.addingTimeInterval(1),+ note: "Team Loser returns.")+ try later.authorTarget(.init(kind: .chapter, designation: "2"))+ context.insert(later); later.work = work+ LibraryRepository.applyManualAssignment(to: later, at: M5Fixture.epoch)+ try context.save()+ }+ let later = try await merged.repository.entry(id: laterID)+ _ = try await merged.repository.updateEntry(id: laterID,+ basis: .init(entry: later), note: later.note, rating: nil)+ _ = try await merged.repository.reconcileGroupHistory()+ let pair = AssociationPair(workID: targetID, entryID: laterID,+ kind: .character, recordID: merged.characterID)+ let acceptanceID = try #require(try await merged.repository.chapterAssociations(+ entryID: laterID).first(where: { $0.pair == pair })?+ .activeAcceptanceIDs.first)++ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "temporarily unassigning earlier join anchor") { context in+ let anchor = try #require(context.fetch(FetchDescriptor<Entry>())+ .first { $0.id == anchorID && $0.work?.id == targetID })+ anchor.work = nil+ try context.save()+ }+ _ = try await merged.repository.reconcileGroupHistory()+ #expect(try await merged.repository.chapterAssociations(entryID: laterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs.isEmpty == true)+ let recoverable = try await merged.repository.withLockedContext(mode: .shared,+ operation: "checking absent join anchor did not retire support") { context in+ try AssociationStorageInventory.read(context: context,+ workIDs: [targetID], includeNotes: false).ledger+ .canRevalidateAcceptance(acceptanceID, pair: pair)+ }+ #expect(recoverable)+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "rehydrating earlier join anchor") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == targetID })+ let anchor = try #require(context.fetch(FetchDescriptor<Entry>())+ .first { $0.id == anchorID && $0.work == nil })+ anchor.work = work+ try context.save()+ }+ _ = try await merged.repository.reconcileGroupHistory()+ #expect(try await merged.repository.chapterAssociations(entryID: laterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs == [acceptanceID])+ withExtendedLifetime(merged.fixture) {}+ }++ @Test("Conflicting merged claims keep the original acceptance recoverable",+ arguments: ["transition", "name", "alias"])+ func conflictingMergedClaimsKeepAcceptanceRecoverable(kind: String) async throws {+ let merged = try await mergedGroup()+ let targetID = merged.targetID, chapterID = merged.chapterID+ let groupID = merged.group.groupID, root = merged.originalRoot+ let characterID = merged.characterID+ if kind == "alias" {+ #expect(try await merged.repository.commitGroupEdits(workID: targetID,+ operations: [+ .fact(groupID: groupID, expectedEventIDs: merged.group.factEventIDs,+ operation: .setName("Other Team")),+ .fact(groupID: groupID, expectedEventIDs: merged.group.factEventIDs,+ operation: .addAlias("Team Loser"))+ ]) == .committed(groupIDs: []))+ }+ let entry = try await merged.repository.entry(id: chapterID)+ _ = try await merged.repository.updateEntry(id: chapterID,+ basis: .init(entry: entry), note: entry.note, rating: nil)+ _ = try await merged.repository.reconcileGroupHistory()+ let pair = AssociationPair(workID: targetID, entryID: chapterID,+ kind: .character, recordID: characterID)+ let acceptanceID = try #require(try await merged.repository.chapterAssociations(+ entryID: chapterID).first(where: { $0.pair == pair })?+ .activeAcceptanceIDs.first)+ let noteText = "Exact note on the accepted group member"+ let noteBasis = try #require(try await merged.repository.associationNoteBasis(pair: pair))+ #expect(try await merged.repository.saveAssociationNote(basis: noteBasis,+ text: noteText) == .committed)+ let factBasis = try #require(try await merged.repository.characterGroups(+ workID: targetID).first).factEventIDs+ let disputedID = UUID()+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "seeding unresolved merged group claim") { context in+ switch kind {+ case "transition":+ context.insert(try GroupTransition(fact: .init(id: disputedID,+ rootID: root.id, workID: targetID, groupID: groupID,+ characterID: characterID, chapterID: chapterID,+ parentHeadIDs: [root.id], action: .leave),+ recordedAt: M5Fixture.epoch))+ case "name":+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: targetID, parentHeadIDs: factBasis,+ operation: .setName("Team Loser")), recordedAt: M5Fixture.epoch))+ context.insert(try GroupFactEvent(fact: .init(id: disputedID,+ groupID: groupID, workID: targetID,+ parentHeadIDs: factBasis, operation: .setName("Other Team")),+ recordedAt: M5Fixture.epoch))+ default:+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: targetID, parentHeadIDs: factBasis,+ operation: .addAlias("Team Loser")), recordedAt: M5Fixture.epoch))+ context.insert(try GroupFactEvent(fact: .init(id: disputedID,+ groupID: groupID, workID: targetID,+ parentHeadIDs: factBasis, operation: .removeAlias("Team Loser")),+ recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ _ = try await merged.repository.reconcileGroupHistory()+ #expect(try await merged.repository.chapterAssociations(entryID: chapterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs.isEmpty == true)+ let recoverable = try await merged.repository.withLockedContext(mode: .shared,+ operation: "checking unresolved claim did not retire support") { context in+ try AssociationStorageInventory.read(context: context,+ workIDs: [targetID], includeNotes: false).ledger+ .canRevalidateAcceptance(acceptanceID, pair: pair)+ }+ #expect(recoverable)+ try await merged.repository.withLockedContext(mode: .exclusive,+ operation: "resolving merged group claim") { context in+ if kind == "transition" {+ let row = try #require(context.fetch(FetchDescriptor<GroupTransition>())+ .first { $0.id == disputedID })+ context.delete(row)+ } else {+ let row = try #require(context.fetch(FetchDescriptor<GroupFactEvent>())+ .first { $0.id == disputedID })+ context.delete(row)+ }+ try context.save()+ }+ _ = try await merged.repository.reconcileGroupHistory()+ #expect(try await merged.repository.chapterAssociations(entryID: chapterID)+ .first(where: { $0.pair == pair })?.activeAcceptanceIDs == [acceptanceID])+ #expect(try #require(try await merged.repository.associationNoteBasis(+ pair: pair)).heads.map(\.text) == [noteText])+ withExtendedLifetime(merged.fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swiftindex 21f779f8..efec1a51 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swift@@ -13,7 +13,7 @@ struct NoEpisodeImportHistorySessionTests { return value } private func store() throws -> (ModelContainer, ModelContext) {- let schema = Schema(versionedSchema: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swiftindex d5ab7af7..e0f17c57 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let container = try ModelContainer( for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)]) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RecognisedCharacterLinkTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RecognisedCharacterLinkTests.swiftindex 3efe6510..9abd521f 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RecognisedCharacterLinkTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RecognisedCharacterLinkTests.swift@@ -16,17 +16,19 @@ struct RecognisedCharacterLinkTests { try context.save() } }- private func fixture(tier: Int = 0, chapter: Bool = true, save: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws -> (M5Fixture, IDs) {+ private func fixture(tier: Int = 0, chapter: Bool = true, save: any RepositorySaveStrategy = ModelContextSaveStrategy(),+ name: String = "Ada", note: String = "Ada enters.") 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.")+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: note) 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))+ context.insert(CharacterRecord(id: ids.character, name: tier == 0 ? name : "Adaline",+ nameKey: tier == 1 ? "ada" : (tier == 0 && name == "Ada" ? "adaline" : RecordNameKey.normalize(tier == 0 ? name : "Adaline")),+ aliases: tier == 0 ? [] : ["Ada"], work: work)) try context.save() } return (fixture, ids)@@ -34,15 +36,79 @@ struct RecognisedCharacterLinkTests { 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 {+ private func request(_ fixture: M5Fixture, _ ids: IDs, originalKind: RecordKind = .character,+ name: String = "Ada") 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],+ let key = RecordNameKey.normalize(name)+ return .init(workID: ids.work, action: .accept, displayedKeys: [key], displayedTargetID: ids.character,+ proposedName: name, 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"]),+ spellingKeys: [key], observedRejectionIDs: candidate.mentionIndex.rejectionIDs(entryID: ids.entry, kind: .character, recordID: ids.character, spellingKeys: [key]), sourceGuard: candidate.mentionIndex.sourceGuards[ids.entry])] : [],- reviewedKey: .init(kind: originalKind, nameKey: "ada"), requiresCurrentSources: true)+ reviewedKey: .init(kind: originalKind, nameKey: key), requiresCurrentSources: true)+ }++ @Test("Automatic character recognition respects saved group name arbitration",+ arguments: [("Team Jake returns.", "Team Jake", false),+ ("Jake returns.", "Jake", false),+ ("Team Jake meets Jake.", "Team Jake", true)])+ func recognisedGroupCollisions(note: String, groupName: String, shouldLink: Bool) async throws {+ let (fixture, ids) = try await fixture(name: "Jake", note: note)+ let groupID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding a recognised-name group collision") { context in+ context.insert(NamedCharacterGroup(id: groupID, workID: ids.work))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID, workID: ids.work,+ operation: .create(name: groupName)), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let input = try await request(fixture, ids, name: "Jake")+ let before = try await fixture.repository.backupV20Snapshot()+ let outcome = try await fixture.repository.commitRecognisedCharacter(input)+ if shouldLink {+ #expect(outcome == .committed(recordID: ids.character))+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .contains { $0.pair.recordID == ids.character && !$0.activeAcceptanceIDs.isEmpty })+ } else {+ if case .refused = outcome {} else { Issue.record("Masked or disputed character was automatically linked") }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ }+ withExtendedLifetime(fixture) {}+ }++ @Test("A same-name place disputes unattended character recognition")+ func recognisedPlaceCollision() async throws {+ let (fixture, ids) = try await fixture(name: "Jake", note: "Jake returns.")+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding an opposite-kind name claim") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first)+ context.insert(Place(id: UUID(), name: "Jake", nameKey: "jake", workID: work.id))+ try context.save()+ }+ let before = try await fixture.repository.backupV20Snapshot()+ let outcome = try await fixture.repository.commitRecognisedCharacter(+ try await request(fixture, ids, name: "Jake"))+ if case .refused = outcome {} else { Issue.record("Same-name place allowed a character link") }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test("An explicit place-to-character kind choice retains its reviewed authority")+ func explicitKindChoiceCanResolveOppositeKindName() async throws {+ let (fixture, ids) = try await fixture()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding a known opposite-kind choice") { context in+ context.insert(Place(id: UUID(), name: "Ada", nameKey: "ada",+ workID: ids.work))+ try context.save()+ }+ let choice = try await request(fixture, ids, originalKind: .place)+ #expect(try await fixture.repository.commitReclassifiedRecognisedCharacter(choice)+ == .committed(recordID: ids.character))+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry)+ .contains { $0.pair.recordID == ids.character && !$0.activeAcceptanceIDs.isEmpty })+ withExtendedLifetime(fixture) {} } @Test("Current name, retained key and accepted alias save one link without enrichment", arguments: [0, 1, 2])
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swiftindex d7c82c26..6e69535d 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) return try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swiftindex 47998510..fc0a58cf 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.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 7cd1e965..bb308b33 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swiftindex b3f194c8..79cc5f0f 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) == ["21.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["22.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 2ce52aed..90dc93c8 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift@@ -81,7 +81,7 @@ struct ThumbnailBytesReachTests { "AsterismSchemaV17Models.swift", "AsterismSchemaV18Models.swift", "AsterismSchemaV19Models.swift", // Frozen V20 declares the same stored relationship/blob, with no live accessor.- "AsterismSchemaV20Models.swift",+ "AsterismSchemaV20Models.swift", "AsterismSchemaV21Models.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 33be4c6b..8cd3d8c2 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: AsterismSchemaV21.self).entities.map(\.name))+ let live = Set(Schema(versionedSchema: AsterismSchemaV22.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 58a1749d..e3e87d31 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) container = try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swiftindex cd772d16..8e21494b 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swiftindex 2d843aa8..bb886484 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() == ["21.0.0"])- #expect(try root.markerText() == "21")+ #expect(try root.recordedVersions() == ["22.0.0"])+ #expect(try root.markerText() == "22") #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() == "21")- #expect(try root.recordedVersions() == ["21.0.0"])+ #expect(try root.markerText() == "22")+ #expect(try root.recordedVersions() == ["22.0.0"]) withExtendedLifetime(root) {} } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swiftindex e0eb7b6b..3ff637eb 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) == "21\n")+ encoding: .utf8) == "22\n") #expect(try V4RecordedStoreFixture.recordedModelVersions(- at: configuration.storeURL) == ["21.0.0"])+ at: configuration.storeURL) == ["22.0.0"]) await repository.shutdown() }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swiftindex d7a5793d..e06f39aa 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) == "21\n")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["21.0.0"])+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "22\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["22.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", "21"])+ arguments: ["16", "17", "18", "19", "20", "21", "22"]) 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 == "21" ? .ready : .markerLagging(generation: marker)))- if marker != "21" {+ == (marker == "22" ? .ready : .markerLagging(generation: marker)))+ if marker != "22" { 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) == "21\n")+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "22\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.swiftindex 9c9f172f..c1a82a9f 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V20RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V20RecordedStoreTests.swift@@ -35,8 +35,8 @@ struct V20RecordedStoreTests { #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"])+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "22\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["22.0.0"]) } @Test func schemaAddsOnlyTwoRelationshipFreeTables() throws {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V21GroupMigrationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V21GroupMigrationTests.swiftnew file mode 100644index 00000000..d1295bbd--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V21GroupMigrationTests.swift@@ -0,0 +1,144 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("V21 named-group migration", .serialized)+struct V21GroupMigrationTests {+ @Test func populatedV21LedgerAndNotesSurviveV22WithoutGroupBackfill() async throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "GroupV21-\(UUID())")+ defer { try? FileManager.default.removeItem(at: root) }+ let configuration = LibraryConfiguration(rootDirectory: root)+ try FileManager.default.createDirectory(at: configuration.storeURL.deletingLastPathComponent(),+ withIntermediateDirectories: true)+ let pair = AssociationPair(workID: UUID(), entryID: UUID(), kind: .character, recordID: UUID())+ let history = try seedV21(at: configuration.storeURL, pair: pair)+ try Data("21\n".utf8).write(to: configuration.readinessMarkerURL)++ await #expect(throws: Error.self) { try await LibraryRepository.openForExtension(configuration) }+ let (_, repository) = try await LibraryRepository.openForApp(configuration)+ let links = try await repository.chapterAssociations(entryID: pair.entryID)+ let aliceLink = try #require(links.first { $0.pair == pair })+ #expect(aliceLink.activeAcceptanceIDs.count == 1)+ #expect(aliceLink.noteHeads.map(\.text) == ["Keep this annotation"])+ #expect(links.first { $0.pair == history.rejectedPair }?.activeAcceptanceIDs.isEmpty != false)+ let storedHistory = try await repository.withLockedContext(mode: .shared,+ operation: "checking migrated V21 ledger history") { context in+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [pair.workID])+ return (+ storage.ledger.invalidIDs.contains(history.conflictedID),+ storage.rawEvents.contains { $0.id == history.rejectionID &&+ $0.value?.payload == .reject(.init(pair: history.rejectedPair, spellingKeys: ["bob"])) },+ storage.rawEvents.contains { $0.id == history.rebindID &&+ $0.value?.payload == history.rebindPayload },+ storage.notes.heads(for: history.rejectedPair).contains {+ $0.text == "Detached V21 note" && $0.attachmentAcceptanceIDs == [history.detachedRootID]+ })+ }+ #expect(storedHistory.0 && storedHistory.1 && storedHistory.2 && storedHistory.3)+ let counts = try await repository.withLockedContext(mode: .shared, operation: "checking migrated group tables") { context in+ (try context.fetchCount(FetchDescriptor<NamedCharacterGroup>()),+ try context.fetchCount(FetchDescriptor<GroupFactEvent>()),+ try context.fetchCount(FetchDescriptor<GroupTransition>()))+ }+ #expect(counts.0 == 0 && counts.1 == 0 && counts.2 == 0)+ await repository.shutdown()+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "22\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["22.0.0"])+ }++ @Test func V22AddsOnlyThreeRelationshipFreeGroupTables() throws {+ let old = Schema(versionedSchema: AsterismSchemaV21.self)+ let live = Schema(versionedSchema: AsterismSchemaV22.self)+ let names = Set(live.entities.map(\.name)).subtracting(old.entities.map(\.name))+ #expect(names == ["CharacterGroup", "GroupFactEvent", "GroupTransition"])+ 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 names {+ let entity = try #require(live.entities.first { $0.name == name })+ #expect(entity.relationships.isEmpty)+ #expect(entity.attributes.allSatisfy { !$0.isUnique })+ }+ #expect(AsterismV22MigrationPlan.schemas.map { String(describing: $0) } == [+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19",+ "AsterismSchemaV20", "AsterismSchemaV21", "AsterismSchemaV22",+ ])+ #expect(AsterismV22MigrationPlan.stages.count == 6)+ }++ private struct SeededHistory: Sendable {+ let rejectedPair: AssociationPair+ let rejectionID: UUID+ let conflictedID: UUID+ let detachedRootID: UUID+ let rebindID: UUID+ let rebindPayload: AssociationEventPayload+ }++ private func seedV21(at url: URL, pair: AssociationPair) throws -> SeededHistory {+ let schema = Schema(versionedSchema: AsterismSchemaV21.self)+ let container = try ModelContainer(for: schema, configurations: [+ ModelConfiguration("AsterismV3", schema: schema, url: url, cloudKitDatabase: .none)])+ let context = ModelContext(container)+ let work = AsterismSchemaV21.Work(); work.id = pair.workID; work.displayTitle = "V21 group predecessor"+ let entry = AsterismSchemaV21.Entry(); entry.id = pair.entryID; entry.captureTitle = "Chapter"+ entry.note = "Alice arrived. Bob left."; entry.work = work+ let character = AsterismSchemaV21.Character(); character.id = pair.recordID+ character.name = "Alice"; character.nameKey = "alice"; character.work = work+ let bob = AsterismSchemaV21.Character(); bob.name = "Bob"; bob.nameKey = "bob"; bob.work = work+ let oldAlice = AsterismSchemaV21.Character(); oldAlice.name = "Old Alice"+ oldAlice.nameKey = "old alice"; oldAlice.work = work+ context.insert(work); context.insert(entry); context.insert(character)+ context.insert(bob); context.insert(oldAlice)+ let current = AssociationCurrentPair(pair: pair,+ sourceFingerprint: AssociationEndpointInventory.sourceFingerprint(+ id: pair.entryID, workID: pair.workID, eligible: true, note: entry.note),+ matchingFingerprint: AssociationEndpointInventory.targetFingerprint(+ kind: .character, id: pair.recordID, workID: pair.workID,+ name: "Alice", nameKey: "alice", aliases: []),+ evidence: RecordMentionGrounding.evidence(names: ["Alice", "alice"], in: entry.note))+ let accept = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["alice"])))+ let inventory = AssociationLedgerInventory(events: [accept])+ context.insert(try AsterismSchemaV21.AssociationEvent(event: accept.validated(by: inventory.receipt(for: current)),+ recordedAt: .distantPast))+ let note = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [accept.id],+ text: "Keep this annotation", originalContext: entry.note, authoredAt: .distantPast)+ context.insert(try AsterismSchemaV21.PairNoteVersion(note: note))+ let rejectedPair = AssociationPair(workID: pair.workID, entryID: pair.entryID,+ kind: .character, recordID: bob.id)+ let rejection = AssociationLedgerEvent(payload: .reject(.init(pair: rejectedPair,+ spellingKeys: ["bob"])))+ context.insert(try AsterismSchemaV21.AssociationEvent(event: rejection, recordedAt: .distantPast))+ let conflicted = AssociationLedgerEvent(payload: .accept(.init(pair: rejectedPair,+ spellingKeys: ["bob"])))+ let firstCopy = try AsterismSchemaV21.AssociationEvent(event: conflicted, recordedAt: .distantPast)+ let secondCopy = try AsterismSchemaV21.AssociationEvent(event: conflicted, recordedAt: .distantPast)+ secondCopy.eventData = Data("corrupted physical twin".utf8)+ context.insert(firstCopy); context.insert(secondCopy)+ let detachedRoot = AssociationLedgerEvent(payload: .accept(.init(pair: rejectedPair,+ spellingKeys: ["bob"])))+ context.insert(try AsterismSchemaV21.AssociationEvent(event: detachedRoot,+ recordedAt: .distantPast))+ context.insert(try AsterismSchemaV21.PairNoteVersion(note: .init(+ pair: rejectedPair, attachmentAcceptanceIDs: [detachedRoot.id],+ text: "Detached V21 note", originalContext: entry.note)))+ let oldPair = AssociationPair(workID: pair.workID, entryID: pair.entryID,+ kind: .character, recordID: oldAlice.id)+ let oldRoot = AssociationLedgerEvent(payload: .accept(.init(pair: oldPair,+ spellingKeys: ["old alice"])))+ context.insert(try AsterismSchemaV21.AssociationEvent(event: oldRoot, recordedAt: .distantPast))+ let rebindPayload = AssociationEventPayload.accept(.init(pair: pair, spellingKeys: ["alice"],+ rebind: .init(operation: .recordMerge(workID: pair.workID, kind: .character,+ fromRecordID: oldAlice.id, toRecordID: pair.recordID), predecessorIDs: [oldRoot.id])))+ let rebind = AssociationLedgerEvent(payload: rebindPayload)+ context.insert(try AsterismSchemaV21.AssociationEvent(event: rebind, recordedAt: .distantPast))+ try context.save()+ withExtendedLifetime(container) {}+ return SeededHistory(rejectedPair: rejectedPair, rejectionID: rejection.id,+ conflictedID: conflicted.id, detachedRootID: detachedRoot.id,+ rebindID: rebind.id,+ rebindPayload: rebindPayload)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkDetailEditTransactionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkDetailEditTransactionTests.swiftnew file mode 100644index 00000000..06b7c4e9--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkDetailEditTransactionTests.swift@@ -0,0 +1,152 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Work detail atomic edit", .serialized)+struct WorkDetailEditTransactionTests {+ private func metadata(_ work: WorkSnapshot, notes: String) -> WorkDetailMetadataEdit {+ .init(basis: .init(work: work), draft: .init(+ displayTitle: work.displayTitle, typeAssignment: work.typeDisplay.assignment,+ genreTags: work.genreTags, genericNotes: notes,+ publicationEdit: .unchanged, readingStatus: work.readingStatus,+ verdict: work.verdict, releaseDays: [], membership: work.membership,+ thumbnail: .keep), calendar: .current)+ }++ @Test("A Work, record and group land in one save")+ func combinedSave() async throws {+ let strategy = ArmableFailingSaveStrategy()+ let fixture = try await M5Fixture(saveStrategy: strategy)+ let work = try await fixture.repository.createWork(+ .init(displayTitle: "Book", hostname: "group.example"))+ let other = try await fixture.repository.createWork(+ .init(displayTitle: "Related", hostname: "group.example"))+ let chapterID = UUID(), characterID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding combined edit chapter") { context in+ let row = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == work.id })+ let chapter = Entry(id: chapterID, captureTitle: "Chapter 1",+ captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Team Loser returns.")+ try chapter.authorTarget(.init(kind: .chapter, designation: "1"))+ context.insert(chapter)+ chapter.work = row+ LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ try context.save()+ }+ strategy.resetCount()+ let groupID = UUID()+ let outcome = try await fixture.repository.commitWorkDetailEdit(.init(+ workID: work.id, metadata: metadata(work, notes: "Together"),+ recordOperations: [.createIdentified(id: characterID,+ draft: .init(kind: .character, name: "Bjorn"))],+ linkOperations: [.add(otherWorkID: other.id, type: "related")],+ groupOperations: [.create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: groupID, characterID: characterID,+ chapterID: chapterID, action: .join)]))+ guard case .committed(let receipt, let recordIDs, let groupIDs) = outcome else {+ Issue.record("Combined edit refused: \(outcome)")+ return+ }+ #expect(receipt.outcome == .committed)+ #expect(recordIDs == [characterID])+ #expect(groupIDs == [groupID])+ #expect(strategy.saveCount == 1)+ let detail = try await fixture.repository.workDetail(id: work.id)+ #expect(detail.work.genericNotes == "Together")+ #expect(detail.characters.contains { $0.name == "Bjorn" })+ #expect(detail.links.contains { $0.otherWorkID == other.id })+ #expect(detail.characterGroups.first?.name == "Team Loser")+ #expect(detail.characterGroups.first?.members[characterID]?.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test("Late group refusal rolls back metadata and record edits")+ func lateRefusal() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(+ .init(displayTitle: "Book", hostname: "group.example"))+ let outcome = try await fixture.repository.commitWorkDetailEdit(.init(+ workID: work.id, metadata: metadata(work, notes: "Must roll back"),+ recordOperations: [.create(.init(kind: .character, name: "Bjorn"))],+ groupOperations: [.create(groupID: UUID(), name: " ")]))+ #expect(outcome == .groupRefused(.invalidOperation))+ let detail = try await fixture.repository.workDetail(id: work.id)+ #expect(detail.work.genericNotes.isEmpty)+ #expect(detail.characters.isEmpty)+ #expect(detail.characterGroups.isEmpty)+ let reopened = try await LibraryRepository.openForApp(+ LibraryConfiguration(rootDirectory: fixture.directory),+ clock: FixedRepositoryClock(M5Fixture.epoch)).repository+ let disk = try await reopened.workDetail(id: work.id)+ #expect(disk.work.genericNotes.isEmpty)+ #expect(disk.characters.isEmpty)+ #expect(disk.characterGroups.isEmpty)+ withExtendedLifetime((fixture, reopened)) {}+ }++ @Test("A failed final save persists none of the combined edit")+ func failedSave() async throws {+ let strategy = ArmableFailingSaveStrategy()+ let fixture = try await M5Fixture(saveStrategy: strategy)+ let work = try await fixture.repository.createWork(+ .init(displayTitle: "Book", hostname: "group.example"))+ let url = try await fixture.repository.projectWorkURL(workID: work.id,+ hostname: "group.example",+ request: .replaceManual("https://group.example/book"))+ strategy.resetCount()+ strategy.failFrom = 1+ let groupID = UUID()+ do {+ _ = try await fixture.repository.commitWorkDetailEdit(.init(+ workID: work.id, metadata: metadata(work, notes: "Must roll back"),+ recordOperations: [.create(.init(kind: .character, name: "Bjorn"))],+ groupOperations: [.create(groupID: groupID, name: "Team Loser")],+ workURL: url))+ Issue.record("Final save unexpectedly succeeded")+ } catch { }+ strategy.failFrom = nil+ #expect(strategy.saveCount == 1)+ let detail = try await fixture.repository.workDetail(id: work.id)+ #expect(detail.work.genericNotes.isEmpty)+ #expect(detail.characters.isEmpty)+ #expect(detail.characterGroups.isEmpty)+ #expect(detail.work.memberships.first?.workURLString == nil)+ let reopened = try await LibraryRepository.openForApp(+ LibraryConfiguration(rootDirectory: fixture.directory),+ clock: FixedRepositoryClock(M5Fixture.epoch)).repository+ let disk = try await reopened.workDetail(id: work.id)+ #expect(disk.work.genericNotes.isEmpty)+ #expect(disk.characters.isEmpty)+ #expect(disk.characterGroups.isEmpty)+ #expect(disk.work.memberships.first?.workURLString == nil)+ withExtendedLifetime((fixture, reopened)) {}+ }++ @Test("A late site refusal leaves the combined edit off disk")+ func lateSiteRefusal() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(+ .init(displayTitle: "Book", hostname: "group.example"))+ do {+ _ = try await fixture.repository.commitWorkDetailEdit(.init(+ workID: work.id, metadata: metadata(work, notes: "Must roll back"),+ recordOperations: [.create(.init(kind: .character, name: "Bjorn"))],+ groupOperations: [.create(groupID: UUID(), name: "Team Loser")],+ membershipRemovalHostnames: ["group.example"]))+ Issue.record("Removing the last site unexpectedly succeeded")+ } catch { }+ let reopened = try await LibraryRepository.openForApp(+ LibraryConfiguration(rootDirectory: fixture.directory),+ clock: FixedRepositoryClock(M5Fixture.epoch)).repository+ let disk = try await reopened.workDetail(id: work.id)+ #expect(disk.work.genericNotes.isEmpty)+ #expect(disk.characters.isEmpty)+ #expect(disk.characterGroups.isEmpty)+ #expect(disk.work.memberships.map(\.hostname) == ["group.example"])+ withExtendedLifetime((fixture, reopened)) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swiftindex 3dc74411..98db0aa9 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift@@ -1,4 +1,5 @@ import Foundation+import SwiftData import Testing @testable import AsterismCore @@ -9,6 +10,128 @@ import Testing @Suite("Work Merge repository transactions", .serialized) struct WorkMergeRepositoryTests { + @Test("Merge transfers a named group and its chapter membership")+ func mergeTransfersNamedGroupMembership() async throws {+ let fixture = try await MergeFixture()+ let (sourceID, targetID) = try await fixture.makeSourceAndTarget()+ let characterID = UUID(), groupID = UUID()+ let sourceEntryID = try #require(try await fixture.repository.work(id: sourceID).entries.first?.id)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding source group member") { context in+ let source = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == sourceID })+ context.insert(CharacterRecord(id: characterID, name: "Bjorn",+ nameKey: "bjorn", work: source))+ try context.save()+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: sourceID,+ operations: [.create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: groupID,+ characterID: characterID, chapterID: sourceEntryID,+ action: .join)]) == .committed(groupIDs: [groupID]))+ let chapter = try await fixture.repository.entry(id: sourceEntryID)+ #expect(try await fixture.repository.updateEntry(id: sourceEntryID,+ basis: .init(entry: chapter), note: "Team Loser returns.",+ rating: chapter.rating) == .committed)+ let sourcePair = AssociationPair(workID: sourceID, entryID: sourceEntryID,+ kind: .character, recordID: characterID)+ let noteBasis = try #require(try await fixture.repository.associationNoteBasis(pair: sourcePair))+ #expect(try await fixture.repository.saveAssociationNote(basis: noteBasis,+ text: "Bjorn is still in the team") == .committed)+ let contract = try await fixture.repository.projectMerge(sourceWorkID: sourceID,+ targetWorkID: targetID)+ #expect(try await fixture.repository.commitMerge(contract) ==+ .committed(targetID: targetID))+ let transferred = try await fixture.repository.characterGroups(workID: targetID)+ #expect(transferred.contains { $0.name == "Team Loser" &&+ $0.members[characterID]?.count == 1 })+ let targetPair = AssociationPair(workID: targetID, entryID: sourceEntryID,+ kind: .character, recordID: characterID)+ let active = try await fixture.repository.chapterAssociations(entryID: sourceEntryID)+ #expect(active.contains { $0.pair == targetPair && !$0.activeAcceptanceIDs.isEmpty })+ let detached = try await fixture.repository.detachedAssociationNotes()+ #expect(detached.contains { $0.pair == targetPair &&+ $0.raw.text == "Bjorn is still in the team" && $0.canRecover })+ }++ @Test("A second Work merge follows the original transition root")+ func repeatedMergeRetainsNamedGroupMembership() async throws {+ let fixture = try await MergeFixture()+ let (sourceID, middleID) = try await fixture.makeSourceAndTarget()+ let finalID = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Final Work", hostname: "example.com")).id+ let characterID = UUID(), groupID = UUID()+ let sourceEntryID = try #require(try await fixture.repository.work(id: sourceID).entries.first?.id)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding repeated merge group") { context in+ let source = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == sourceID })+ context.insert(CharacterRecord(id: characterID, name: "Bjorn",+ nameKey: "bjorn", work: source))+ try context.save()+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: sourceID,+ operations: [.create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: groupID,+ characterID: characterID, chapterID: sourceEntryID,+ action: .join)]) == .committed(groupIDs: [groupID]))+ let first = try await fixture.repository.projectMerge(sourceWorkID: sourceID,+ targetWorkID: middleID)+ #expect(try await fixture.repository.commitMerge(first) == .committed(targetID: middleID))+ let second = try await fixture.repository.projectMerge(sourceWorkID: middleID,+ targetWorkID: finalID)+ #expect(try await fixture.repository.commitMerge(second) == .committed(targetID: finalID))+ #expect(try await fixture.repository.characterGroups(workID: finalID)+ .contains { $0.name == "Team Loser" && $0.members[characterID]?.count == 1 })+ }++ @Test("Character edits after Work merge advance the inherited transition root",+ arguments: [false, true])+ func editMergedGroupMember(combine: Bool) async throws {+ let fixture = try await MergeFixture()+ let (sourceID, targetID) = try await fixture.makeSourceAndTarget()+ let sourceCharacterID = UUID(), survivorID = UUID(), groupID = UUID()+ let chapterID = try #require(try await fixture.repository.work(id: sourceID).entries.first?.id)+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding inherited character edit") { context in+ let works = try context.fetch(FetchDescriptor<Work>())+ let source = try #require(works.first { $0.id == sourceID })+ let target = try #require(works.first { $0.id == targetID })+ context.insert(CharacterRecord(id: sourceCharacterID, name: "Bjorn",+ nameKey: "bjorn", work: source))+ context.insert(CharacterRecord(id: survivorID, name: "Missha",+ nameKey: "missha", work: target))+ try context.save()+ }+ #expect(try await fixture.repository.commitGroupEdits(workID: sourceID,+ operations: [.create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: groupID,+ characterID: sourceCharacterID, chapterID: chapterID,+ action: .join)]) == .committed(groupIDs: [groupID]))+ let merge = try await fixture.repository.projectMerge(sourceWorkID: sourceID,+ targetWorkID: targetID)+ #expect(try await fixture.repository.commitMerge(merge) == .committed(targetID: targetID))+ let sourceRow = try #require(try await fixture.repository.m5RecordRows(+ .character, id: sourceCharacterID).first)+ let sourceBasis = RecordEditBasis(kind: .character, recordID: sourceCharacterID,+ content: sourceRow)+ let operation: RecordEditOperation+ if combine {+ let survivorRow = try #require(try await fixture.repository.m5RecordRows(+ .character, id: survivorID).first)+ operation = .combine(source: sourceBasis,+ target: RecordEditBasis(kind: .character, recordID: survivorID,+ content: survivorRow))+ } else { operation = .delete(basis: sourceBasis) }+ _ = try await fixture.repository.commitRecordEdits(workID: targetID,+ operations: [operation])+ let groups = try await fixture.repository.characterGroups(workID: targetID)+ #expect(groups.allSatisfy { $0.members[sourceCharacterID] == nil })+ if combine {+ #expect(groups.contains { $0.members[survivorID]?.count == 1 })+ }+ }+ // MARK: - Happy path: one save @Test("Merge commits with exactly one save, moves Entries, deletes source, updates target metadata")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swiftindex 33598f7e..3418ea30 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift@@ -45,6 +45,31 @@ struct WorkRecordCopyRepositoryTests { ], includeNotes: includeNotes) } + @Test("Copying a character without chapters leaves group history at its source")+ func copyLeavesChapterAnchoredGroupsAtSource() async throws {+ let fixture = try await fixture()+ let chapterID = UUID(), groupID = UUID()+ try await fixture.repository.seedM5Rows(entries: [+ .init(id: chapterID, captureTitle: "Chapter 38", hostname: "copy.example",+ path: "chapter-38", note: "Team Loser returns", workID: source),+ ])+ #expect(try await fixture.repository.commitGroupEdits(workID: source,+ operations: [.create(groupID: groupID, name: "Team Loser"),+ .transition(rootID: UUID(), groupID: groupID, characterID: character,+ chapterID: chapterID, action: .join)]) == .committed(groupIDs: [groupID]))+ let preview = try await fixture.repository.previewRecordCopy(+ sourceWorkID: source, destinationWorkID: destination,+ selections: [.init(kind: .character, sourceID: character)], includeNotes: false)+ guard case .committed = try await fixture.repository.commitRecordCopy(preview) else {+ Issue.record("Expected record copy to commit")+ return+ }+ let sourceGroups = try await fixture.repository.characterGroups(workID: source)+ let destinationGroups = try await fixture.repository.characterGroups(workID: destination)+ #expect(sourceGroups.contains { $0.groupID == groupID && $0.members[character] != nil })+ #expect(destinationGroups.isEmpty)+ }+ @Test func mixedCopyIsIndependentAndLeavesMetadataAndEvidenceAlone() async throws { let fixture = try await fixture() let before = try await fixture.repository.backupV19Snapshot()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swiftindex fd259216..e3fbfea9 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swiftindex d485b2a8..6dcba9d6 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swiftindex 58801395..58b477d2 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swiftindex d8bf6f8d..9112243d 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.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) == "21",+ #expect(try markerContent(cfg) == "22", "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) == "21", "the import republishes nothing")+ #expect(try markerContent(cfg) == "22", "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) == "21")+ #expect(try markerContent(cfg) == "22") try expectEveryRelationshipPopulated(cfg) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swiftindex b97f7431..f673b50b 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: AsterismSchemaV21.self)+ let schema = Schema(versionedSchema: AsterismSchemaV22.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV21MigrationPlan.self,+ for: schema, migrationPlan: AsterismV22MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/CharacterExtractionAssemblerTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/CharacterExtractionAssemblerTests.swiftindex 73c22a6c..0438e8ee 100644--- a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/CharacterExtractionAssemblerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/CharacterExtractionAssemblerTests.swift@@ -139,6 +139,45 @@ struct CharacterExtractionAssemblerTests { .first?.target == .existing(Self.lowUUID)) } + @Test("A known group name or alias does not become a new character candidate")+ func knownGroupNamesArbitrateNewCharacterCandidates() {+ let context = CharacterExtractionContext(knownGroupNameKeys: ["team loser", "losers"])+ let proposals = CharacterExtractionAssembler.assembleNoteFirst([+ Self.candidate("Team Loser"), Self.candidate("Ainar")+ ], revisions: Self.revisions, context: context, pass: .manual)++ #expect(proposals.map(\.name) == ["Ainar"])+ }++ @Test("A matching character stays reviewable beside a same-name known group")+ func sameNameKnownCharacterRemainsReviewable() {+ let characterID = UUID(uuidString: "00000000-0000-0000-0000-0000000000C7")!+ let context = CharacterExtractionContext(+ characters: [Self.character("Team Loser", id: characterID)],+ knownGroupNameKeys: ["team loser"])+ let proposals = CharacterExtractionAssembler.assembleNoteFirst([+ Self.candidate("Team Loser")+ ], revisions: Self.revisions, context: context, pass: .manual)++ #expect(proposals.count == 1)+ #expect(proposals.first?.target == .existing(characterID))+ }++ @Test("Ambiguous same-name character records remain unresolved beside a known group")+ func ambiguousSameNameCharactersRemainUnresolved() {+ let context = CharacterExtractionContext(+ characters: [+ Self.character("Team Loser", id: Self.lowUUID),+ Self.character("Team Loser", id: Self.highUUID),+ ], knownGroupNameKeys: ["team loser"])+ let proposals = CharacterExtractionAssembler.assembleNoteFirst([+ Self.candidate("Team Loser")+ ], revisions: Self.revisions, context: context, pass: .manual)++ #expect(proposals.count == 1)+ #expect(proposals.first?.target == .unresolved)+ }+ @Test("Proposed aliases never take part in matching, so a split half shows as new (Q93)") func proposedAliasesDoNotMatch() { let context = CharacterExtractionContext(characters: [@@ -585,10 +624,12 @@ extension CharacterExtractionContext { init(characters: [ExistingCharacter] = [], acceptedFacts: Set<RecordFactIdentity> = [], suppressedNameKeys: Set<String> = [],- suppressedFacts: Set<RecordFactIdentity> = []) {+ suppressedFacts: Set<RecordFactIdentity> = [],+ knownGroupNameKeys: Set<String> = []) { self.init(records: [.character: characters], acceptedFacts: [.character: acceptedFacts], suppressedNameKeys: [.character: suppressedNameKeys],- suppressedFacts: [.character: suppressedFacts])+ suppressedFacts: [.character: suppressedFacts],+ knownGroupNameKeys: knownGroupNameKeys) } }
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swiftindex 2be04d43..55b1b59f 100644--- a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift@@ -103,6 +103,26 @@ struct FoundationCharacterExtractionModelClientTests { #expect(prompt.contains( "List the named story characters and the named places this note mentions"))+ #expect(prompt.contains("named groups"))+ #expect(prompt.contains("explicit joins and leaves with a verbatim"))+ let instructions = FoundationCharacterExtractionModelClient.instructions+ #expect(instructions.contains("Do not infer membership"))+ #expect(instructions.contains("Do not report transitions from general Work notes"))+ }++ @Test("The prompt includes known group names and asks for explicit leaves")+ func promptIncludesGroupRosterContextAndLeaves() {+ var source = Self.source+ source.knownGroupNames = ["Team Loser", "The Losers"]+ let prompt = FoundationCharacterExtractionModelClient.prompt(for: source)++ #expect(prompt.contains("Team Loser"))+ #expect(prompt.contains("The Losers"))+ #expect(prompt.contains("Do not report a known group as a character solely"))+ #expect(prompt.contains("explicit joins and"))+ #expect(prompt.contains("leaves with a verbatim quote"))+ #expect(FoundationCharacterExtractionModelClient.instructions.contains(+ "Do not report transitions from general Work notes")) } // MARK: - The request carries one source and the title, nothing else (Req 1.4)
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NamedGroupGroundingTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NamedGroupGroundingTests.swiftnew file mode 100644index 00000000..23123a3b--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NamedGroupGroundingTests.swift@@ -0,0 +1,92 @@+import AsterismCore+import Foundation+import Testing+@testable import AsterismIntelligence++@Suite("Named group extraction grounding")+struct NamedGroupGroundingTests {+ private let workID = UUID(uuidString: "00000000-0000-0000-0000-0000000000D1")!+ private let chapterID = UUID(uuidString: "00000000-0000-0000-0000-0000000000D2")!++ private func source(_ text: String, chapter: Bool = true) -> ExtractionSource {+ .init(workID: workID, workTitle: "A Serial Story", source: .entry(chapterID),+ text: text, fingerprint: "saved-revision", isChapter: chapter)+ }++ @Test("Group creation and join cite a saved chapter and exact join quote")+ func groundedCreationAndJoin() {+ let text = "Missha joins Team Loser after the battle."+ let result = ExtractionResult(groups: [.init(name: "Team Loser")],+ groupJoins: [.init(groupName: "Team Loser", characterName: "Missha",+ quote: "Missha joins Team Loser")])+ let grounded = GroupExtractionGrounding.ground(result, from: source(text))+ #expect(grounded.count == 2)+ #expect(grounded.contains { $0.kind == .create && $0.groupName == "Team Loser" &&+ $0.chapterID == chapterID && $0.sourceFingerprint == "saved-revision" })+ #expect(grounded.contains { $0.kind == .join && $0.characterName == "Missha" &&+ $0.quote == "Missha joins Team Loser" })+ }++ @Test("Ungrounded names, invented quotes and nonchapters cannot propose roster changes")+ func unsupportedClaimsAreDropped() {+ let result = ExtractionResult(groups: [.init(name: "Team Loser"), .init(name: "Team Z")],+ groupJoins: [.init(groupName: "Team Loser", characterName: "Missha",+ quote: "Missha joins Team Loser"),+ .init(groupName: "Team Loser", characterName: "Bjorn",+ quote: "Bjorn joins Team Loser")])+ #expect(GroupExtractionGrounding.ground(result,+ from: source("Team Loser and Missha appear together.")).map(\.kind) == [.create])+ #expect(GroupExtractionGrounding.ground(result,+ from: source("Missha joins Team Loser.", chapter: false)).isEmpty)+ }++ @Test("Equivalent repeated model claims collapse by group and member keys")+ func repeatedClaimsCollapse() {+ let result = ExtractionResult(groups: [.init(name: "Team Loser"), .init(name: "team loser")],+ groupJoins: [.init(groupName: "Team Loser", characterName: "Missha",+ quote: "Missha joins Team Loser"),+ .init(groupName: "team loser", characterName: "Missha",+ quote: "Missha joins Team Loser")])+ let grounded = GroupExtractionGrounding.ground(result,+ from: source("Missha joins Team Loser."))+ #expect(grounded.filter { $0.kind == .create }.count == 1)+ #expect(grounded.filter { $0.kind == .join }.count == 1)+ }++ @Test("An explicit leave is grounded to its exact chapter quote")+ func explicitLeaveIsGrounded() {+ let note = "Ainar leaves Team Loser after the match."+ let result = ExtractionResult(groupLeaves: [+ .init(groupName: "Team Loser", characterName: "Ainar",+ quote: "Ainar leaves Team Loser")+ ])++ let suggestions = GroupExtractionGrounding.ground(result, from: source(note))++ #expect(suggestions.count == 1)+ #expect(suggestions.first?.kind == .leave)+ #expect(suggestions.first?.characterName == "Ainar")+ #expect(suggestions.first?.groupName == "Team Loser")+ #expect(suggestions.first?.quote == "Ainar leaves Team Loser")+ #expect(suggestions.first?.chapterID == chapterID)+ }++ @Test("A paraphrased, incomplete, or generic-note leave cannot be proposed")+ func unsupportedLeaveIsDropped() {+ let incomplete = ExtractionResult(groupLeaves: [+ .init(groupName: "Team Loser", characterName: "Ainar", quote: "Ainar leaves")+ ])+ let invented = ExtractionResult(groupLeaves: [+ .init(groupName: "Team Loser", characterName: "Ainar",+ quote: "Ainar leaves Team Loser after the battle")+ ])+ #expect(GroupExtractionGrounding.ground(incomplete,+ from: source("Ainar leaves Team Loser after the match.")).isEmpty)+ #expect(GroupExtractionGrounding.ground(invented,+ from: source("Ainar leaves Team Loser after the match.")).isEmpty)+ #expect(GroupExtractionGrounding.ground(.init(groupLeaves: [+ .init(groupName: "Team Loser", characterName: "Ainar",+ quote: "Ainar leaves Team Loser")+ ]), from: source("Ainar leaves Team Loser", chapter: false)).isEmpty)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NoteFirstExtractionTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NoteFirstExtractionTests.swiftindex e8491b70..b9129881 100644--- a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NoteFirstExtractionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NoteFirstExtractionTests.swift@@ -24,13 +24,16 @@ struct NoteFirstExtractionTests { 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")+ @Test("Character and place fields remain names-only while group joins carry exact quote evidence") 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"))+ let nameSchema = String(describing: NamedExtractionEntity.generationSchema)+ #expect(!nameSchema.contains("statement")); #expect(!nameSchema.contains("quote"))+ let resultSchema = String(describing: NamedExtractionResult.generationSchema)+ #expect(resultSchema.contains("groupJoins"))+ #expect(resultSchema.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")) }
diff --git a/Packages/AsterismCore/Tests/ConstellationKitTests/ConstellationSelectionRecipesTests.swift b/Packages/AsterismCore/Tests/ConstellationKitTests/ConstellationSelectionRecipesTests.swiftindex 3f02913e..689f5af3 100644--- a/Packages/AsterismCore/Tests/ConstellationKitTests/ConstellationSelectionRecipesTests.swift+++ b/Packages/AsterismCore/Tests/ConstellationKitTests/ConstellationSelectionRecipesTests.swift@@ -107,6 +107,21 @@ struct ConstellationSelectionRecipesTests { AsterismColors.opaqueField != AsterismColors.fieldFill, "the opaque stand-in has to differ from the translucent fill") }++ @Test("segmented accessibility frames follow the visual order in RTL")+ func segmentedAccessibilityFramesFollowVisualDirection() {+ let ltrFirst = SegmentedAccessibilityFrameLayout.frame(+ index: 0, count: 2, width: 50, height: 44, isRightToLeft: false)+ let rtlFirst = SegmentedAccessibilityFrameLayout.frame(+ index: 0, count: 2, width: 50, height: 44, isRightToLeft: true)+ let rtlSecond = SegmentedAccessibilityFrameLayout.frame(+ index: 1, count: 2, width: 50, height: 44, isRightToLeft: true)++ #expect(ltrFirst.minX == 0)+ #expect(rtlFirst.minX == 50)+ #expect(rtlSecond.minX == 0)+ #expect(rtlFirst.height == 44)+ } } #if canImport(AppKit)
diff --git a/AGENTS.md b/AGENTS.mdindex 5497508d..c321897c 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 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+**The live store schema is V22** (`specs/named-character-groups/`), the readiness+marker generation is `"22"`, and the retained migration chain is V16 → V17 →+V18 → V19 → V20 → V21 → V22. V16–V21 are frozen snapshots; app markers 16–22 remain+accepted, while the extension opens only 22. The current archive generation is+**21/22**, with bounded conversion of predecessor 20/21, 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. @@ -254,9 +254,9 @@ before touching `Models.swift`. **Every model lives in `AsterismCore`, nested inside the live schema enum.** There are zero top-level `@Model` types; `Entry`, `Work`, `Site` and the rest-are typealiases onto `AsterismSchemaV17`. One frozen snapshot is kept beside-it, and the migration plan is always `[V(n-1), V(n)]` with one lightweight-stage. A custom migration stage is forbidden: it never fires between+are typealiases onto the live `AsterismSchemaV22`. Frozen V16–V21 snapshots+remain beside it. The migration plan retains V16 → V22 with six lightweight+stages until the owner's population proof permits retirement. A custom migration stage is forbidden: it never fires between structurally identical models and it would run inside the share extension, which must never migrate (`retire-migration-chain`, `multi-site-works` Decision 3). Nothing runs a data pass in production any more; the last one@@ -533,11 +533,12 @@ same way, under the device-run rule at the top of this file. **An edit view holds value-type drafts. The store is written once, by one repository call per table it touches, when the reader presses Save.** The work-editor's Save is five such calls — URL, metadata, records, links, site-removals — because each touches its own table and each has to be able to-refuse without the others rolling back-(`specs/bugfixes/edit-views-write-before-save/` Q3, Q8); collapsing them into-fewer calls is a separate decision this rule does not make. Cancel restores+editor ordinarily saves URL, metadata, records, links and site removals through+separate repository operations (`specs/bugfixes/edit-views-write-before-save/`+Q3, Q8). When the enclosing edit includes group drafts, its Save uses the single+composite Work transaction: all staged Work and group changes commit together,+or a refusal/failure rolls them all back (`specs/named-character-groups/`+Decision 10). Nested group Done/Delete only changes those drafts. Cancel restores the drafts from the loaded snapshot; there is nothing to roll back because nothing was written. A refused or failed commit keeps the reader in the editor, because the draft is the only copy of itself (`polish-and-export` Decision at the
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e48410c5..50f7a3b8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **Group editing (T-2491):** save or cancel group creation, roster changes and deletion with the enclosing Work edit. Use matching expandable pills, sheet actions and clear inclusive leave wording. Reconcile memberships after Work merges or character conversion, and preserve links and notes during incomplete sync.+ - **Physical benchmark preferences (T-2115):** isolate opted-in performance runs from the installed app's sort, navigation and release-note preferences using a disposable domain for each launch; preserve normal launch behaviour. - **Qualification index (T-2468):** align the association status with source-qualified Core/native/Mac and full phone/iPad results, while retaining failed performance gates and the pending release disposition.@@ -20,6 +22,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed +- **Named character groups (T-2491):** manage chapter-based memberships with inclusive joins/leaves, aliases, reciprocal app/share-sheet rosters, reviewed group/join/leave suggestions, historical link recalculation, and ordinary Remove/Restore links. Preserve membership history through archives and record merges.++- **Selection controls (T-2491):** share softer cyan selection styling across group membership, chapter sorting, Work and Reading status. Retain native Liquid Glass where labels fit and readable stacked choices on narrow screens, with accessible selection and touch targets.+ - **Settings layout (T-2483):** group Sites, Work types and Creator roles under Library on iOS/iPadOS, and expose each destination directly in a retained native Mac Settings window. Preserve page drafts, navigation, Back and Save/Cancel across tab changes and window reopening; routes back reopen the main window after restoring its state. Move Detached link notes and preserved captures into Maintenance, keeping their existing actions and confirmations. Avoid backup staging cleanup on Mac tabs that have no backup controls. - **Release qualification (T-2468):** record the owner-accepted duplicate/capture performance failures and missing current full-performance pass as release exceptions, retaining all measurements, assertions and source qualifications; further optimisation remains deferred.
diff --git a/docs/agent-notes/schema-migration.md b/docs/agent-notes/schema-migration.mdindex 424d79f5..affd4e85 100644--- a/docs/agent-notes/schema-migration.md+++ b/docs/agent-notes/schema-migration.md@@ -1,13 +1,13 @@ # Schema migration -Schema **V20** is live (`specs/url-optional-chapter-notes/`), with V16–V19+Schema **V22** is live (`specs/named-character-groups/`), with V16–V21 retained as frozen predecessors. The app accepts readiness markers `"16"`-through `"20"`; the extension accepts `"20"` only. V20 adds optional authored-entry/redirect/resolution metadata, an optional Work capture default and the-relationship-free `EntrySource` table. Converted V19 rows retain nil/default-values without a backfill. The current archive is **19/20**, with bounded-conversion of predecessor **18/19** archives; the envelope contract asserts the-live schema version directly.+through `"22"`; the extension accepts `"22"` only. V22 adds the relationship-free+`CharacterGroup`, `GroupFactEvent` and `GroupTransition` tables. Converted V21+stores retain existing library and association data and begin with empty group+tables. The current archive is **21/22**, with bounded conversion of predecessor+**20/21**, **19/20** and **18/19** archives; the envelope contract asserts the live+schema version directly. The app and extension still open through `openForApp` and `openForExtension` respectively, over the same fixed file layout. The detailed V16 account below@@ -15,12 +15,12 @@ is retained as the worked example for the next freeze. ## Current state -- The live classes are nested in `extension AsterismSchemaV20` in `Models.swift`+- The live classes are nested in `extension AsterismSchemaV22` in `Models.swift` and reached through top-level typealiases. `AsterismSchemaV16.swift` through- `AsterismSchemaV19.swift` hold frozen stored fields, relationship macros and+ `AsterismSchemaV21Models.swift` hold frozen stored fields, relationship macros and defaults only. `Work.thumbnailData` keeps `.externalStorage`, and referenced raw spellings and value types stay frozen by reference.-- `AsterismV20MigrationPlan` is `[V16, V17, V18, V19, V20]` with four lightweight+- `AsterismV22MigrationPlan` is `[V16, V17, V18, V19, V20, V21, V22]` with six lightweight stages. Keep reachable stages absent the owner's population proof. Each recorded-store fixture creates, seeds, saves and releases its container before opening the live schema; this order matters to SwiftData's global
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 82cc1998..b4802c3a 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -2,6 +2,7 @@ | Name | Creation Date | Status | Summary | |------|---------------|--------|---------|+| [Named Character Groups](named-character-groups/requirements.md) | 2026-10-26 | Done — 20/20 tasks; Core, quick, phone/iPad focused journeys green; Mac UI automation and extension-hosted UI coverage limits recorded | T-2491: chapter-based multi-group membership, reciprocal rosters, grounded suggestions, historical assignment and Remove/Restore links. | | [Settings Layout](settings-layout/requirements.md) | 2026-10-24 | Implemented — publication gates passed | T-2483. Group mobile configuration rows, provide direct Mac settings tabs, and collect detached notes/captures in Maintenance. | | [Benchmark Preferences Isolation](#benchmark-preferences-isolation) | 2026-10-24 | In Progress — eligible for draft publication with one owner-accepted phone exception; history/privacy checks pending | T-2115. Isolate opted-in benchmark preferences while preserving normal launches and benchmark semantics. | | [Character–Chapter Associations](#characterchapter-associations) | 2026-10-18 | In Progress — UI acceptance qualified; performance release exceptions accepted | T-2468. Persist grounded chapter-note links and exact pair annotations; shared known-character/place Save matching and duplicate-resolution continuity have focused verification. |@@ -1111,3 +1112,7 @@ The original duplicate observation/settling and capture-projection budgets remai - **Path:** `specs/benchmark-preferences-isolation/` - **Files:** [smolspec.md](benchmark-preferences-isolation/smolspec.md), [tasks.md](benchmark-preferences-isolation/tasks.md), [decision_log.md](benchmark-preferences-isolation/decision_log.md), [implementation.md](benchmark-preferences-isolation/implementation.md), [verification.md](benchmark-preferences-isolation/verification.md) - **Status:** All 33 expected iPad UI identifiers passed with 0 skips. The full phone result remains Failed (246 passed, 1 failed, 2 expected physical-only skips); the owner accepted only the named creator-controls failure as a publication exception and directed no further investigation or rerun. An approved retry passed all 6 expected production Mac Settings UI identifiers with 0 failures and 0 skips; the AppKit-hosted branch of the generic mounted rendering probe was not run separately. The change is eligible for draft publication with this one exception; history and privacy checks are separate publication prerequisites. Physical signpost evidence applies only to the preserved pre-integration safety snapshot; normal app restoration was a separate approved normal-build install and launch before this integration. No current-source physical run is claimed.++## Named Character Groups++See [requirements](named-character-groups/requirements.md), [design](named-character-groups/design.md), [tasks](named-character-groups/tasks.md), [decision log](named-character-groups/decision_log.md), and [verification run](named-character-groups/verification-run.md).
diff --git a/specs/named-character-groups/decision_log.md b/specs/named-character-groups/decision_log.mdnew file mode 100644index 00000000..1569e36b--- /dev/null+++ b/specs/named-character-groups/decision_log.md@@ -0,0 +1,415 @@+# Decision Log: Named Character Groups++## Quick Decisions++| ID | Date | Decision | Rationale |+|----|------|----------|-----------|+| Q1 | 2026-10-25 | Use the full Starwave spec workflow. | Owner approved the Phase 1 routing assessment; user-facing ambiguity and persisted-data consequences both apply. |+| Q2 | 2026-10-25 | Use `named-character-groups` as the spec folder name. | Owner approved the proposed name at the Phase 1 gate. This does not prescribe the final UI label. |+| Q3 | 2026-10-26 | Show group-to-character and character-to-group membership in the app and share sheet, using chapter ranges with open unknown endpoints. | Owner's annotated document, Sentinel_ab8d15a6d99881918e8cb912eb971bfc: “in a character overview we should be able to see which groups they belong to. Both in the sharesheet and app page” and the inverse, with examples `Team Loser: Bjorn (38-), Missha (38-41)`. |+| Q4 | 2026-10-26 | Allow group aliases; prefer the more complete overlapping name; a rename does not retain the old spelling unless the reader adds it as an alias. | Same owner annotation: “Yes, allow aliases. If there's overlap the most complete match should win. Say Team Jake should beat just Jake. Renames don't retain old spelling”. Equal-completeness ambiguity remains conservative. |+| Q5 | 2026-10-26 | Suggest group creation and joins from chapter notes for reader approval alongside character suggestions; manual members carry a chapter link. | Same owner annotation: “Groups are empty by default and members can be added manually at any time. With a link to the chapter. There should probably be some AI inference there as well ... And groups should probably be offered for creation the same way.” “Offered” grounds approval rather than silent creation. |+| Q6 | 2026-10-26 | Reprocess relevant past notes after changes to groups or memberships. | Same owner annotation: “Yes it should reprocess”. This answers the previously open retrospective processing question, not the mechanics of conflicting authored edits. |+| Q7 | 2026-10-26 | Remove memberships for a mistaken deleted character; transfer and deduplicate memberships on character merge. | Same owner annotation: “Deletion, just complete removal as the character was there by accident. Merging transfers memberships to the real character, resolving duplicate memberships if needed.” The reason identifies character deletion; group deletion and Work operations remain open. |+| Q8 | 2026-10-26 | Defer a separate workflow for rare chapter order, reorder and tie anomalies. | Same owner annotation: “Let's skip this for now as it's an unlikely event.” This is scope deferral, not approval to invent an order or discard data on a conflict. |+| Q9 | 2026-10-26 | Approve the revised requirements at `a01fcae2` and the three defaults in its review packet. | Parent asked: “Approve these defaults and the revised requirements so I can move into design?” Owner replied “Yes, that seems right” (Sentinel_3b32af853bf4819197b3413b2ae3129f). This approves requirements and design work, not design, task planning or implementation. |+| Q10 | 2026-10-26 | Put ordinary Remove link in the existing chapter-association row. | Code research found association-note editing and skipped-link review in `EntryDetailView.chapterAssociationsSection`, but no ordinary removal action. This supplies the correction path Decision 4 assumes without a group-specific interface. Approved by Q11. |+| Q11 | 2026-10-26 | Approve the design at `13c18546` and add the ordinary Remove link button. | The parent asked whether the design looked good, including ordinary Remove/Restore actions (Sentinel_30b808f7f6988191a0dc40c95f22cb14). The owner replied “Design is fine. Add the remove link button” (Sentinel_e93851bc8dc48191a144fa25f0962c25). This approves design and task planning, not feature implementation. |++## Decision 1: Chapter-dependent groups feed individual assignment++**Date**: 2026-10-25+**Status**: accepted++### Context++The reader wants to refer to named groups of people in story notes. Membership can change as the story progresses, and a person can belong to multiple groups. The existing app assigns individual character records from saved chapter-note names.++### Decision++Groups have chapter-based join and leave transitions whose effect carries forward until changed. A group reference feeds automated assignment of the individual members effective for that chapter. Groups follow character-list persistence: absence from later prose does not disband them. Later owner clarification in Decisions 2–4 resolves the transition boundaries, automatic linking and ordinary correction path; chapter-order anomalies are deferred by Q8.++### Rationale++This is the direction the owner accepted in the voice discussion for T-2491. Historical membership is needed so a later roster does not rewrite who a group reference meant in an earlier chapter. Individual assignment remains the useful result for character history.++### Alternatives Considered++- **Use the current roster for every historical reference:** rejected by the owner's request for membership effective from and until particular chapters.+- **Treat a group as only a separate, non-individual mention:** rejected by the owner's request that automated character assignment keep working for each person.++### Consequences++**Positive:**+- A chapter's group reference can identify the individuals relevant at that point in the story.+- A person can participate in overlapping groups without losing individual character history.++**Negative:**+- Roster changes and chapter reordering can affect past assignments, so provenance and correction semantics must be settled before implementation.+- Existing literal individual-name support rules need an explicit extension for group-derived results.++---++## Decision 2: Inclusive join and final leave chapters++**Date**: 2026-10-26+**Status**: accepted++### Context++The initial group idea did not decide whether a transition chapter itself counted. The owner annotated the requirements after the first review packet.++### Decision++A join includes its chapter. A leave names the last chapter in which the person belongs to the group. Groups start empty; reader-approved membership carries forward until a leave. Repeated same-state transitions do not create extra intervals. Opposing join/leave actions at one chapter remain a narrow clarification question.++### Rationale++Owner wording in Sentinel_ab8d15a6d99881918e8cb912eb971bfc: “Joint includes the current chapter. Leaving means they leave during that chapter, meaning they were still part of it at the start of the chapter.” The owner also said “Keep the first and last state” and “Groups are empty by default”.++### Alternatives Considered++- **Leave excludes its named chapter:** would contradict the owner's explicit description of still belonging at that chapter's start.+- **Assume a current roster before the first join:** would contradict the owner's empty-by-default instruction.++### Consequences++**Positive:**+- A join at chapter 38 and leave at 41 can display the requested `(38-41)` range.+- A later group reference uses the chapter's historical effective roster.++**Negative:**+- A join and leave both attached to one chapter need an explicit same-chapter interpretation.++---++## Decision 3: Recognised group references link individual members++**Date**: 2026-10-26+**Status**: accepted++### Context++Known individual character and place names already gain supported links during chapter-note Save, while extraction also processes notes. The first requirements draft left group expansion timing and accepted-versus-review state open.++### Decision++Uniquely recognised group references expand on both saved-note Save and extraction. They automatically create the ordinary individual-character chapter links for members effective at that chapter. New groups and inferred joins are offered for reader approval alongside character suggestions; a newly approved character whose approved membership is effective in that chapter is shown immediately. No dedicated group-link review screen is required.++### Rationale++The owner wrote in Sentinel_ab8d15a6d99881918e8cb912eb971bfc: “Expand on save and extraction and when new characters are approved and they're immediately part of the group, that should be shown” and “Automatically add the links. Doesn't need a special interface. The links already include the chapter notes so we know what's going on anyway.” The owner also requested AI suggestions for group creation and joins.++### Alternatives Considered++- **Extraction only:** would delay a group result after Save despite the owner's explicit request.+- **Review every known member link:** would add the separate interface the owner declined.++### Consequences++**Positive:**+- Existing character chapter history remains the reader-visible result.+- Save and extraction both honor the effective roster.++**Negative:**+- Historical reprocessing needs to keep manually removed links from reappearing on unchanged evidence.+- Group creation and join proposals need grounded saved-note evidence and approval before they alter the roster.++---++## Decision 4: Use existing link correction++**Date**: 2026-10-26+**Status**: accepted++### Context++The first review proposed a dedicated per-group contribution and rejection interface to distinguish overlapping evidence. The owner rejected that additional UI.++### Decision++Group expansion produces ordinary chapter–character links. Readers can remove a mistaken link manually through the existing control. The feature does not add a separate group-provenance or member-contribution rejection interface.++### Rationale++The owner wrote in Sentinel_ab8d15a6d99881918e8cb912eb971bfc: “Overkill. Readers can always manually remove the link later if needed.” Existing links already include the chapter note, which the owner considered sufficient context.++### Alternatives Considered++- **Per-group-member rejection UI:** would expose each contribution but adds the correction machinery the owner declined.+- **Mandatory review of every group-expanded member:** would conflict with Decision 3's automatic links.++### Consequences++**Positive:**+- Correction stays in the existing chapter link interaction.+- A group reference does not create another approval queue for known members.++**Negative:**+- When direct and group evidence overlap, the app must still preserve independent support and honor a manual removal on replay without exposing contribution-level controls.++---++## Decision 5: Resolve overlapping transitions and record operations++**Date**: 2026-10-26+**Status**: accepted++### Context++The revised requirements packet proposed defaults for overlapping transitions, group deletion and Work operations. These would change historical assignments, so they required owner approval.++### Decision++Join and leave in one chapter create a one-chapter membership; repeated leaves use the last leave chapter. Group deletion removes its history and unsupported derived links, preserving independently supported links and authored notes. Work merges transfer groups and transitions to surviving identities; a Work copy without source chapters leaves membership history in the source.++### Rationale++The parent presented all three defaults verbatim to the owner in Sentinel_324f2b8927408191a37c3e7a6dbd8476. The owner approved them and the revised requirements with “Yes, that seems right” in Sentinel_3b32af853bf4819197b3413b2ae3129f.++### Alternatives Considered++- **Hold same-chapter joins/leaves for review or use the first repeated leave:** would change the inclusive, last-state timeline shown in the approved packet.+- **Retain deleted group's historical links:** would conflict with the approved complete-removal default for group data.+- **Copy chapter membership without source chapters:** would manufacture destination chapter history that the approved default leaves at the source.++### Consequences++**Positive:**+- One-chapter intervals and repeated leaves have a single interpretable outcome.+- Record correction can remove group data while keeping independent evidence and authored notes.++**Negative:**+- Group deletion and Work merge require recalculation of affected saved links.+- A copied Work without chapters cannot display the source's membership ranges.++---++## Decision 6: Store authored group facts as independent identities and transition events++**Date**: 2026-10-26+**Status**: accepted with approved design (Q11)++### Context++The effective roster must be reconstructed for old chapters after sync, backup import, merges and retrospective edits. The repository already stores association decisions as independent UUID event rows and requires cross-entity references to be UUID columns.++### Decision++Store group identity, immutable named group-fact events with observed-head ancestry, and immutable chapter-anchored transition events. Fold those events into membership intervals using the approved inclusive boundaries. Preserve divergent authored heads and withhold their automatic effect until a resolution event acknowledges every head; delete tombstones prevent late event resurrection.++### Rationale++A mutable current-roster array cannot explain the roster at a historical chapter and gives concurrent changes no independent identity. Event rows allow deterministic dedupe and repointing under existing repository/CloudKit rules. Names and aliases need their own authored conflict treatment because an alias removal must survive sync.++### Alternatives Considered++- **Current roster on a group row:** cannot reconstruct past membership or distinguish concurrent transition edits.+- **Mutable interval row per member:** easy to read, but a concurrent change to either endpoint can silently combine two authors' incompatible histories.++### Consequences++- The projection must read selected events and fold them in chapter order; materialized current membership is only a cache, never authority.+- Merge, deletion, backup and empty-library paths must handle event identities explicitly. Merge writes immutable successor rebind events, preserving old event bytes so late copies dedupe.++---++## Decision 7: Extend ordinary association proof with typed group support++**Date**: 2026-10-26+**Status**: accepted with approved design (Q11)++### Context++The existing association ledger only validates a literal individual-name match in the chapter note. A group-derived member often has no individual spelling there. A link may also have direct or multiple group supports.++### Decision++Keep V21 direct acceptance/receipt decoding and validation unchanged. Add versioned V22 typed support and support-specific receipts for new direct or group roots, where a group root proves its mention and effective approved membership. Publish one ordinary link for the union of current accepted roots. Ordinary Remove covers all support keys observed for the pair, while genuinely new direct/group evidence can re-establish it; Restore explicitly acknowledges that correction. Existing spelling-scoped rejections keep their V21 meaning. Retire only unsupported roots and preserve authored note recovery.++### Rationale++Pretending a group name is an individual's name would falsely validate an acceptance after the roster changed. A separate group-link table/UI would make the reader see two types of character history and contradict Decision 4.++### Alternatives Considered++- **Fake member spelling evidence:** loses the group/roster validation dependency.+- **Separate group-derived association:** duplicates links and correction affordances.+- **Rebuild all historical direct acceptances during migration:** unnecessary and risks old notes; decode existing direct payloads as direct support.++### Consequences++- Ledger receipt decoding and every current-pair caller need a parity audit.+- Group change reconciliation can retire group support while leaving direct or other group support alive.++---++## Decision 8: Reconcile historical saved notes from current authored facts++**Date**: 2026-10-26 +**Status**: accepted with approved design (Q11)++### Context++The owner explicitly wants past notes reprocessed when group names or membership changes. Save, share extension and queued replay currently use one Core known-link hook before committing final saved content.++### Decision++Use that Core hook for current Save and an affected-Work reconciliation on group mutations, import and remote CloudKit changes observed through `SyncMonitor`/`reconcileAfterSync`. Both use the same resolver and ledger receipt validation; model suggestions never become roster authority before reader approval. Keep final source, transition and association writes in a transaction. A device-local cursor advances only after each historical batch commits, so interrupted reconciliation resumes idempotently.++### Rationale++One resolver prevents the app, extension and replay from disagreeing. Reading current saved notes rather than extraction drafts preserves the existing source-of-truth boundary.++### Alternatives Considered++- **Model-only group expansion:** misses share-extension Save and known names after model refusal.+- **Current-chapter-only reconciliation:** leaves historically wrong links after retrospective roster edits.++### Consequences++- Large Works may need bounded, durable post-save reconciliation; a measured performance risk remains in `design.md`.++---++## Decision 9: Review explicit extracted membership leaves++**Date**: 2026-10-26+**Status**: accepted by implementation follow-up authorization++### Context++The approved task plan originally left extraction of leaves manual. In the later acceptance follow-up, the owner supplied the concrete sequence “Team Loser” + Ainar, an explicit join note, an extracted false character candidate for the group, an independently skipped character candidate, and an explicit leave in the next chapter; the requested correction authorized this leave journey to be implemented.++### Decision++Extract explicit leave events alongside joins and present them for reader review. Include current group names and aliases in extraction context, conservatively arbitrate a group-name candidate as a character only when there is no matching character record, require a verbatim quote containing the group and character names, and never infer a leave from absence. Approval revalidates the current note, roster and identities in Core. The recorded leave includes its chapter; repeated extraction must not offer the same already accepted transition again, while a later leave chapter may extend the inclusive boundary. Leave Skip evidence is durable for automatic extraction and manual extraction can explicitly reconsider it.++### Consequences++- V22 carries a `groupLeaves` result in the same extraction output; no live schema change is needed.+- Ledger validation, grounded suggestion skipping, approval, and coordinator filtering all recognize leave as a distinct transition kind.+- Same-name character ambiguity remains reviewable; group arbitration cannot erase independent real-character evidence.++---++## Decision 10: Stage group edits in the enclosing Work session++**Date**: 2026-10-27+**Status**: accepted by implementation follow-up authorization++### Context++The acceptance follow-up found that the group editor's Save/Delete wrote immediately. That bypassed the Work page's Save/Cancel boundary: cancelling Work could leave a changed roster behind. The default gray disclosure also did not match the Work page's existing character/place pill collections.++### Decision++The nested group editor's Done stages a child draft in the active Work edit session; nested Cancel discards only that child's changes. Group create/rename/alias/transition/delete facts stay staged until Work Save. Work Cancel discards all staged group changes. A Work Save with group drafts uses one Core transaction containing all staged Work editor writes, including URL, metadata, records, links and site removals. The transaction has one exclusive context and one save; any refusal or failure rolls back the combined edit and preserves the drafts. In view mode, render a read-only group pill collection with the existing expanded detail-card treatment, ordered between Characters and Places. Group mutation controls appear only in Work edit mode. Membership history uses a chapter picker beside a segmented Join/Leave action.++### Rationale++Independent group writes cannot be undone by Work Cancel. Saving group changes first allows a later Work edit failure to leave the roster changed; saving groups last allows a group refusal to leave preceding Work writes committed. A single transaction keeps the reader's enclosing Save meaningful. Reusing the existing Work record presentation keeps group rosters legible without creating another visual language.++### Alternatives Considered++- **Commit nested editor Done immediately:** rejected because parent Work Cancel would not restore the prior group state.+- **Commit groups before or after the existing sequence of independent repository saves:** rejected because a refusal in the other step can leave only part of the requested Work edit stored.+- **A separate group disclosure style:** rejected because Characters and Places already establish a pill-and-expanded-card pattern on the same page.++### Consequences++- `WorkDetailModel` owns staged group drafts and computes final operations against each original basis.+- The composite Core edit command must include every Work edit step that can be staged alongside group edits, use context-local mutation bodies, preserve typed refusal/receipt behavior, and save once.+- Work page view mode is read-only for groups; the nested editor Done label signals staging within Work edit mode.+- UI verification covers parent Cancel, parent Save, nested Cancel, delete, transition controls, and the matching view-mode disclosure pattern on phone and iPad.++## Decision 11: Restore cyan selection within native segmented controls++**Date**: 2026-10-27+**Status**: accepted by implementation follow-up authorization++### Context++The owner asked to restore the prior cyan selection mark while keeping the+native segmented-control shape and Liquid Glass treatment for both Work sort+and group Join/Leave. A scoped SwiftUI `.tint(AsterismColors.cyan)` compiled+and passed the light/dark journey but rendered the same gray track and white+selected capsule on iOS 27.++### Decision++On UIKit platforms, use a per-instance `UISegmentedControl` with+`selectedSegmentTintColor` set to the adaptive cyan token. Keep the system's+segmented-control geometry and track, and use black selected text for readable+contrast on the adaptive cyan in both appearances. Do not use `UIAppearance`,+view-hierarchy introspection, or custom backgrounds. Keep the SwiftUI Picker+fallback for non-UIKit platforms, scoped with `.tint(AsterismColors.cyan)`.++Preserve the shared control's accessibility contract by exposing explicit+`UIAccessibilityElement` children with their existing option identifiers and+labels, `.selected` state, and 44-point target frames. Recompute their visual+frames from `effectiveUserInterfaceLayoutDirection` so option order follows+the system's LTR or RTL layout.++### Rationale++The SwiftUI tint experiment proved that `.tint` does not change the current+native segmented selection on iOS. The UIKit control restores the accent while+retaining native capsule geometry and the system track; actual light/dark+screenshots and the existing accessibility journey verify the result.++### Alternatives Considered++- **Scoped SwiftUI Picker tint alone:** rejected after the rendered light and+ dark screenshots showed no cyan change.+- **Global UIKit appearance or view introspection:** rejected because it would+ affect unrelated controls or depend on undocumented view hierarchy.+- **Hand-drawn SwiftUI segments:** rejected because the request is to retain+ native control geometry and Liquid Glass treatment.++### Consequences++- UIKit option accessibility is supplied by the control's public accessibility+ container APIs rather than relying on private segment views.+- The shared UI journey must keep checking option IDs, selection state, and+ 44-point hit targets in both appearances; host tests pin the RTL frame order.+- Screenshot and gate evidence for this correction is recorded in+ `verification-run.md`.++---++## Decision 12: Soften selection and share it with status controls++**Date**: 2026-10-27+**Status**: accepted by owner acceptance follow-up++### Context++After reviewing the installed cyan controls, the owner said the cyan seemed+“darker and more solid” and requested the same refinement for Reading and Work+status selectors (owner message `Sentinel_b1ab70f1ef908191a48e5fc1c4f1c0b7`).+This supersedes Decision 11’s opaque cyan and black text.++### Decision++Use the existing adaptive `selectedMarkFill` cyan wash (14 percent) with cyan+selected text in the scoped native segmented control. Apply the shared control+to group Join/Leave, chapter sorting, Work status and Reading status. Preserve+native material and geometry where labels fit. On narrow screens, the five-option+Reading selector uses the shared stacked SwiftUI fallback, with the same selected+fill, border and text tokens; that fallback is not a native glass segment. Keep+44-point targets, stable option identifiers, selected traits and status staging.++### Rationale++The softer wash follows the existing app selection token and the owner’s visual+feedback. A stacked fallback keeps all five labels readable without truncating+their meaning or shrinking their targets. Actual light/dark phone and iPad+screenshots, rather than colour values alone, qualified this change.++### Consequences++Decision 11’s per-instance UIKit styling, public accessibility container and RTL+handling remain. The fill and selected text are amended; the narrow fallback is+an explicit layout exception. Reading status retains a visible field caption.+Verification and installed source provenance remain in `verification-run.md`.
diff --git a/specs/named-character-groups/design-review.md b/specs/named-character-groups/design-review.mdnew file mode 100644index 00000000..c4c0c333--- /dev/null+++ b/specs/named-character-groups/design-review.md@@ -0,0 +1,30 @@+# T-2491 design review — named character groups++**Review gate:** approved by owner on 2026-10-26 (Sentinel_e93851bc8dc48191a144fa25f0962c25). The owner explicitly requested the ordinary Remove link button. Implementation remains a separate workflow.++## What the design will build++- Groups belong to one Work and hold approved chapter-anchored joins/leaves. Join and leave chapters both count; repeated same-state events form one interval. A character can belong to several groups.+- A unique saved-note group name uses that chapter's roster to add the same ordinary character links the app already displays. Direct and several group references can support one link. Saved-note edits, historic roster changes, import and CloudKit arrivals trigger revalidation and historical relinking.+- Extraction offers new groups and joins for approval from grounded note evidence. The app and share sheet show group-to-character and character-to-group chapter ranges, including open endpoints.+- New schema/archive generations preserve authored group facts and association history through sync, backup, merges and deletion. Older character links continue through their existing validation path.++## Code findings that shaped the design++| Finding | Design consequence |+| --- | --- |+| `LibraryRepository+SaveTimeKnownLinks.recordKnownChapterLinks` is already shared by chapter Save, capture, reparse, correction and replay. | Group expansion joins this one Core path so app and extension use final saved content. |+| `AssociationEndpointInventory.current` requires a literal target-character name in the note. | Group links need a distinct, typed proof of group mention and effective membership; old direct receipts retain their existing decoding and validation. |+| `EntryDetailView.chapterAssociationsSection` offers association-note editing and Skipped links, but no ordinary Remove action. | The design adds a generic trailing **Remove link** action on the existing chapter-link row, plus explicit **Restore link**. No group-specific correction screen or provenance display. |+| CloudKit arrivals already reach `SyncMonitor` and `reconcileAfterSync`. | Those paths detect changed group facts and resume an idempotent saved-chapter reconciliation; a local cursor advances after each committed batch. |+| Live schema is V21 and import currently accepts 20/21, 19/20 and 18/19 archives. | Append V22 to the retained V16–V21 chain and preserve that import window when adding archive 21/22. |++## Review result++The design-critic raised four blocking contracts: migration/archive retention, the missing Remove action, preservation of concurrent group edits, and legacy association receipt compatibility. All four are specified in the revised design. Peer review then identified immutable merge rebinds, remote reconciliation and new-evidence behavior after Remove; these are specified, and the peer confirmed all three resolved. The UX peer found only the owner decision below still open.++## Owner decision at this gate — approved++The owner approved the design and requested the ordinary **Remove link** button on the existing chapter-link row. The approved design also contains the explicit **Restore link** action. The current app has no Remove control. Remove suppresses the direct/group evidence currently supporting that character link; unchanged evidence will not recreate it. A genuinely new direct name or group reference can create the link again. Restore explicitly accepts current evidence. Existing association notes remain recoverable.++This design approval allowed the Starwave task plan to be drafted for a separate review. No app code, real library data or device run changed at this gate.
diff --git a/specs/named-character-groups/design.md b/specs/named-character-groups/design.mdnew file mode 100644index 00000000..72f029f6--- /dev/null+++ b/specs/named-character-groups/design.md@@ -0,0 +1,74 @@+# T-2491 — Named character groups: design++**Status:** Approved by owner on 2026-10-26 (Sentinel_e93851bc8dc48191a144fa25f0962c25); ordinary Remove link button explicitly requested.++## Architecture++The Core store owns group identities, chapter-anchored transitions, and a deterministic roster projection. A shared Core linker resolves complete names in the final saved chapter note, expands uniquely identified groups against that chapter's approved roster, and writes ordinary character association acceptances. The app extraction pipeline proposes group creation and joins; the share extension reads groups and runs the same known-name linker without running the model. All writes use the repository's one locked `ModelContext` transaction and one save.++| Existing pattern or call site | Equivalent? | Design action |+| --- | --- | --- |+| `LibraryRepository+SaveTimeKnownLinks.recordKnownChapterLinks`: manual entry create/edit (`+ManualEntry`, 2 calls) | Yes | Shared matcher and group expansion before the caller's save. |+| Capture and chapter capture (`+Capture`, 2; `+ChapterCapture`, 1) | Yes | Resolve final persisted chapter, not share-sheet draft. |+| Reparse and queued replay (`+ReparseCapture`, 2) | Yes | Same group expansion after final content and identity resolution. |+| Repository save/edit (`LibraryRepository.swift`, 2) | Yes | Same linker, including chapter-note edits. |+| Entry correction (`+EntryCorrection`, 1) | Yes | Recompute source and destination chapter support. |+| Duplicate resolution (`+DuplicateResolution`, 1) | Yes | Recompute survivor after rebind. |+| `AssociationEndpointInventory.current` / `AssociationLedgerInventory.activeAcceptanceIDs` | Yes | Validate legacy direct roots against their original direct-only receipt; validate new typed direct/group roots against support-specific receipts. Union active roots at publication. |+| `AssociationMutation` and association publication/notes | Yes | Retire only unsupported acceptance roots; one pair remains one ordinary link; authored notes use existing detached-note recovery. |+| `LibraryRepository+RecordEditing` character delete/combine; `+WorkMerge` | Yes | Remove/repoint/deduplicate transition claims and reconcile affected chapters in the same transaction. |+| `+RecordCopy` character/place copy between Works | No | It copies selected records only; leave groups and chapter transitions in the source. If a whole-Work copy is added without chapters, it likewise does not copy chapter-anchored transitions. |+| `ShareWorkContext` / `ShareCharacterChipsView` / app `WorkDetailView` | Yes | Add one shared, ordered group/range projection and reciprocal cards using existing character detail presentation. |+| `AsterismIntelligence.ExtractionResult` / `CharacterExtractionCoordinator` / character review | Yes | Ground group and join proposals in saved evidence, review in existing proposal flow; do not change the extension's model dependency. |+| Backup export/import, sync, empty-library, model contract, schema readiness | Yes | Include new rows and proof payload; validate/reconcile imported events, clear in child-before-parent order, append V22 to the retained migration chain and add readiness 22. |++`RecordMentionGrounding` supplies complete-name spans for characters, places and groups. Within overlapping spans choose the longest complete spelling; equally long claims across identities or kinds remain ambiguous and create no automatic link. A rename changes the current spelling claim; explicit aliases are the only retained older spellings. The linker treats group names as names of groups, never as individual character evidence.++## Components and interfaces++| Component | Contract |+| --- | --- |+| `CharacterGroup` and `GroupFactEvent` (Core live schema) | Group UUID/Work UUID identity plus immutable named events: create, setName, addAlias, removeAlias, delete. Each event carries its own UUID and observed parent-head IDs. The fold accepts one causally complete head; concurrent unequal names or add/remove of the same alias keep both facts but withhold that claim until a later event names both heads. Delete tombstones win over late events descending only from pre-delete heads. |+| `GroupTransition` (Core live schema) | Immutable UUID event with group/character/Entry UUIDs, join or leave action, and observed predecessor-head IDs. Edit/remove supersedes named event IDs with replacement/tombstone; merge adds a rebind event naming predecessor event IDs and survivor identities without mutating originals. Late copies of originals dedupe, not conflict. Concurrent divergent heads are retained and withhold the affected interval. |+| `GroupRoster.project(workID:chapterOrder:groups:events:)` | Produces chapter-effective members and distinct display intervals. Join starts on its chapter; last repeated leave ends on its chapter; same-chapter join/leave yields one chapter. Repeated joins keep the first start. A later join after a closed interval starts another. Missing/torn anchors cannot create inferred chapter membership. |+| `GroupReferenceResolver.resolve(note:directory:roster:)` | Returns unique group evidence and member pairs for the saved chapter, after longest-match arbitration across all three name kinds. Stable IDs and normalized spelling keys make replay idempotent. |+| `AssociationSupport` in the existing ledger | V21 acceptance/receipt JSON remains the legacy direct variant and is validated byte-for-byte by the V21 receipt path. New V22 acceptance payloads carry a versioned typed support: direct spelling or group `(groupID, spelling key, resolved transition-event IDs)`, each with its own receipt. A group receipt proves source, group identity/name, chapter roster, target character and current pair barrier/rejection digests together. One link is published if any root is current. |+| `LibraryRepository` group commands | Create/rename/delete/alias and transition add/edit/remove, all under final same-Work identity checks. Each command reconciles its current chapter in one save and marks other affected saved chapters for durable bounded reconciliation; stale/torn facts abort without partial writes. |+| `LibraryRepository.removeChapterCharacterLink` | New ordinary trailing Remove action on the current `EntryDetailView.chapterAssociationsSection` row, wired through `EntryDetailModel` and `LibraryProviding`. It writes one pair correction covering every currently active support key: direct normalized name or `(groupID, normalized group name)`. Unchanged support keys remain suppressed across replay, including roster edits; genuinely new direct/group support keys can establish the pair again. Explicit Restore link acknowledges the correction and revalidates current evidence. Existing spelling-scoped rejections keep their V21 semantics. The row's primary tap still opens the note editor. |+| Group proposals | Extend `NamedExtractionResult` and review models with grounded group creation, join and leave proposals. Approval rechecks final saved evidence and coherent identities in Core, inserts approved facts, and immediately re-runs the known linker. Skip uses the existing evidence-scoped review suppression. The model receives current group names and aliases as context; exact quoted join/leave evidence is required, and mere absence of a character from a later note never implies a leave. |+| `GroupSummary` and `MembershipRange` | Core read values for both app and `ShareWorkContext`; sorted by Work chapter ordering then stable UUID. Both group-to-character and character-to-group projections share the same intervals. Unknown endpoints remain open; they are not extrapolated. |+| Work group editor draft | A nested group editor owns a private child draft. Done replaces the Work edit session's staged value; Cancel discards only the child draft. The Work session retains each group's original basis and latest value, derives one operation set from that pair, and clears all staged groups on Work Cancel. |+| Work detail Save transaction | When group edits are staged, `WorkDetailModel` sends the entire Work edit (URL, optional metadata, record edits, related-work links, groups and site-membership removals) through one `commitWorkDetailEdit` command. The repository applies context-local mutation bodies under one exclusive lock, rolls back every refusal/error, and performs one final save. Typed outcomes preserve the existing conflict and record-copy behavior. Historical group reconciliation resumes only after commit. |+| Work group presentation | In view mode, Groups follows the same wrapping outlined pill and expanded translucent detail card used by character/place records. It is read-only and sits between Characters and Places. Creation/edit actions live only inside Work edit mode. A membership change places its chapter picker beside an accessible segmented Join/Leave control. |++The group editor follows `CharacterReviewView`/`WorkDetailView` navigation and the share-sheet group cards follow `ShareCharacterChipsView`'s disclosure and accessibility pattern. The app and extension receive the same Core projection; only the app offers editing or model suggestions. Existing direct character/place links and place suggestions keep their current behavior in Works without groups.++## Data models and continuity++Add CloudKit-compatible, relationship-free `CharacterGroup`, `GroupFactEvent` and `GroupTransition` tables in `AsterismCore`'s live schema. Cross-table references and event parents are UUID columns/encoded UUID arrays; columns are defaulted or optional, with no uniqueness constraint. Identity-conflicting physical copies of one event ID quarantine that event. The causal fold uses ancestor relationships, not timestamps or physical row order; equal event copies dedupe. Concurrent incompatible heads remain stored, and no automatic recognition or roster effect derives from their disputed claim. Explicit editing of a disputed claim writes one resolution event naming every observed head. A delete tombstone dominates pre-delete descendants and has no implicit undo. Merge/rebind events name predecessor IDs and new Work, Entry or character IDs; all old facts remain byte-identical so late CloudKit copies cannot fabricate conflicts.++Advance V21 to V22 with a frozen V21 snapshot and append one lightweight V21→V22 stage to the retained V16→V17→V18→V19→V20→V21 chain. Preserve app-openable markers 16–21 and add 22; only the extension opens 22. Add archive 21/22 while continuing to accept 20/21, 19/20 and 18/19, as the current importer does. Export includes group identity, fact/transition events, tombstones and versioned association supports. Older archives import with empty group rows. Import validates same-Work UUID references and entire receipts, merges by event identity, and retains incoherent authored facts without publishing guessed links. A populated V21 ledger fixture must prove existing acceptances, rejections and authored notes remain active or detached as before. `docs/agent-notes/schema-migration.md` governs the coordinated schema change.++Character deletion tombstones that identity's transition history. Character merge writes successor rebind events for affected transitions and folds duplicates; Work merge writes successor group-fact/transition rebind events through its surviving identity map, then reconciles saved notes. The existing record-copy flow moves selected character/place facts to another Work without chapters, so it leaves groups and transition history in the source. Any whole-Work copy without chapters also leaves transitions in the source. Group deletion tombstones its identity and transitions, retires only that group's unsupported acceptance roots, and preserves direct/other-group roots and authored association notes. No operation rewrites an independently supported association merely because one source changes.++## Error handling++- If the saved Entry is not an eligible chapter, its Work, group or character identity is torn, or chapter placement is incoherent, withhold the affected group-derived assignment and keep authored facts for correction; do not guess a roster.+- If equal longest names identify multiple records, emit no automatic group or direct link for that span. Already accepted unrelated links remain.+- Model refusal or failure leaves the saved note and approved state intact. Approval with stale evidence or identities is rejected before inserting group facts or links; skips follow the existing pending-review suppression path.+- Reconciliation uses the current saved note and ledger receipts. A disappeared name or changed roster retires only unsupported roots; detached authored association notes remain recoverable under existing behavior. The V21 receipt path and spelling-scoped rejection/rebind/acknowledgement digests do not change; V22 group roots use a distinct receipt domain and new pair-wide rejection/restore decisions. Transaction failure rolls back group and association writes together.++The existing `SyncMonitor` remote-change signal and app activation `reconcileAfterSync(tier:)` path trigger an idempotent group-fact inventory comparison against a device-local per-Work reconciliation digest. A changed group/transition digest queues that Work's saved chapters for the shared Core linker; batches process at most 128 chapters and advance a durable local cursor only after their association save. Interruption retries remaining chapters. Backup import and local group commands invoke the same invalidation. Receipt validation may hide stale roots before the sweep, while the sweep creates newly eligible roots. The share extension performs the current chapter's Save-time link and never relies on a model run.++## Risks and assumptions++- Risk: V22 migration and archive import may expose duplicate CloudKit physical rows or old receipt decoding the local fixtures miss. | Verify: early migration/import fixtures with predecessor archives and torn rows. | If wrong: retain every authored variant, withhold unsafe links, and repair the adapter before feature UI.+- Risk: Historical reconciliation may scan unrelated chapters or block current Save on a large Work. | Verify: an automated 1,000-chapter changed Work plus 5,000 unrelated-chapter fixture asserts zero unrelated scans and at most 128 chapters per committed reconciliation batch; report elapsed M4 time before UI completion. | If wrong: retain current-chapter Save atomicity and reduce the queued batch size or index the changed Work's references.++## Testing strategy++Core generated-table tests exercise interval fold across chapter sequences, same-chapter/repeated transitions, multiple groups, duplicate/reordered physical events, removal and merge; compare group and character range projections. Seeded generation uses Swift Testing without a new dependency. Matcher tests permute name and row ordering and assert longest-match, equal-length refusal, Unicode normalization and no cross-kind regression. Ledger tests prove support union, pair rejection, retirement, note recovery and old direct receipt decoding.++Repository tests cover Save, capture, reparse, replay, correction, duplicate/Work merge followed by late original-event delivery, copy, deletion, backup/sync, torn identities and transactional failure. Remote-only join/rename/alias removal tests exercise `SyncMonitor`/activation reconciliation and interrupted durable retry against previously processed chapters. A populated V21 ledger migration/import fixture pins direct acceptances, spelling rejections, rebinds and authored note attachment before/after V22; Remove/Restore tests pin unchanged-key suppression and activation from genuinely new evidence. Proposal tests cover grounded group/join/leave approval, Skip persistence and manual reconsideration, stale evidence, accepted-leave duplicate suppression, inclusive leave boundary and immediate assignment after character approval. App and share-extension tests cover reciprocal ranges, open endpoints, editing, ordinary Remove link and accessibility. During implementation use affected Core and focused native/UI journeys; before any code commit follow `AGENTS.md`'s serial Core/Mac/quick bars; full UI acceptance belongs to pre-push-review. No physical `Personal` run is part of this spec.++**Traceability:** 1.1–1.7 → group storage, commands and proposal review; 2.1–2.5, 6.1–6.2 → transition fold and reconciliation; 3.1–3.9 → matcher, typed association support and transactional linker; 4.1–4.4 → shared projections and views; 5.1–5.3, 6.3–6.4 → delete/merge/copy, archive and sync contracts. The test groups above exercise each mapped component.
diff --git a/specs/named-character-groups/implementation.md b/specs/named-character-groups/implementation.mdnew file mode 100644index 00000000..c2d92c33--- /dev/null+++ b/specs/named-character-groups/implementation.md@@ -0,0 +1,128 @@+# Named character groups: implementation explanation++## Beginner Level++### What changed++A Work can contain named groups such as Team Loser. A character can belong to+several groups. Membership starts in the joining chapter and includes the leaving+chapter. Later chapters carry the last accepted membership forward. Mentioning a+group links its members according to that chapter's roster, rather than today's+roster. Empty groups do not invent members.++### Why it matters++Readers can record who belonged together at each point in a story. Both a group+and a character show the reciprocal membership ranges. Existing notes survive+link removal and record changes. Group edits stay drafts until the enclosing Work+Save; Cancel discards them.++### Key concepts++A roster is the membership list at a chapter. An alias is another explicitly saved+name for the same group. Suggestions require review; a group name cannot silently+become a new character. Remove/Restore actions control ordinary chapter links.++## Intermediate Level++### Changes overview++V22 adds three UUID-addressed tables and archive21/schema22 preserves their raw+records. `GroupRoster` folds accepted facts and transitions into immutable ranges.+`GroupReferenceResolver` arbitrates complete name spans across groups, characters+and places. Save-time matching and historical reconciliation consume the same+projection. Group references contribute support to individual character links.++### Implementation approach++The Work model owns value drafts, including nested group edits. Group-bearing+Work saves use a composite repository transaction covering staged Work, record,+link, site and roster edits with one final save. Core owns all SwiftData writes.+Causal event ancestry and physical variants remain available across import and+merges; ambiguous or incomplete evidence is withheld rather than guessed.++Extraction receives known group names and aliases, filters duplicate/type-colliding+new-entity proposals, and presents grounded create/join/leave suggestions. Durable+Skip decisions remain scoped to their evidence. Ordinary Remove/Restore links+retain authored notes and suppression behavior. Historical edits trigger bounded+Work-local recalculation, with unrelated chapters excluded.++### Trade-offs++Causal raw history costs additional storage and validation but preserves concurrent+edits and archive fidelity. Chapter-order anomalies remain explicitly deferred.+Shared native segmented controls preserve system geometry and scoped cyan styling;+a narrow five-option Reading selector uses a readable stacked fallback rather than+compressing its labels. The fallback is not native glass.++## Expert Level++### Technical deep dive++Projection validates coherent physical copies and complete causal chains before+electing live heads. Root tombstones remain authoritative; merge successors retain+their ancestry. Equivalent concurrent heads transfer through one successor observing+every head; incompatible values retain separate survivor-addressable successors+for the ordinary editor. Explicit deletion tombstones the complete source root.+Work merge refuses unresolved group names, live alias conflicts or unsafe histories+atomically before+deleting the source, while coherently deleted groups do not block a merge.+An indexed global transition-metadata read discovers foreign-Work+successors connected to transferred roots, retaining every physical variant; the+same selection feeds projection and the history digest. Inherited group-fact+physical parent closure also feeds both reads, so late hydration cannot leave a+completed historical cursor unchanged. Chapter processing remains+scoped to affected Works. Membership ranges use the existing chapter spine with inclusive+start and end checks. Cross-kind equally complete name claims remain unresolved;+longer complete spans win without substring-based entity guessing. Automatic+recognition rechecks that same arbitration against final saved evidence before+writing. Generic notes have no chapter expansion, and existing explicit kind+choices/Restore retain their guarded authority. Compatible divergent transition+heads stay withheld but are available as empty chapter/action fields in the+ordinary editor; an explicit choice writes a successor over every observed head+under the complete current basis. Untouched conflicts survive unrelated drafts,+and no automatic winner, separate provenance panel or autosave flow was added.++Group-derived association support includes transition evidence, allowing saved-note+changes and roster corrections to retire stale support while preserving independent+links and authored annotation history. An unavailable accepted join/leave anchor withholds the affected member rather+than discarding one endpoint and inventing an open interval. Retirement requires coherent removal:+physical conflicts, incomplete ancestry, missing chapter anchors and disputed+semantic claims preserve existing support until evidence resolves. Recovery keeps+the original acceptance and exact authored note. If a coherent new proof changes+the association generation, the existing explicit detached-note recovery action+can attach that exact note to the current link; no automatic attachment policy+was added. Remove captures refreshed direct aliases only when direct support is+active, so a group-only longest match cannot suppress later independent direct+evidence. Retrospective reconciliation operates in+bounded batches and records its progress without scanning unrelated Works as if+they were affected. Reprocessing and record operations share repository locks and+save boundaries; refusal/failure preserves the user's editable draft.++### Architecture impact++The app and share extension receive immutable projections. The extension retains+its current-generation-only, non-migrating, non-mirroring contract. The app retains+the V16–V22 lightweight migration chain and opens prior accepted readiness markers;+archives convert only the explicitly supported predecessor generations. No custom+CloudKit engine, relationship expansion or automatic disbanding was introduced.++### Potential issues and limits++Model availability and generated candidate quality remain platform-dependent;+regressions cover actual candidate assembly and arbitration with synthetic data.+Simulator checks do not prove device CloudKit delivery. Mac UI automation and+extension-hosted UI coverage have the limits recorded in `verification-run.md`.+Chapter reorder/tie behavior was deferred by the owner, not inferred as a new rule.+A recorded nonblocking limitation remains: equivalent skipped AI transitions can+reappear after an unrelated note edit if the model chooses a different valid quote+extent. This suggestion-repeat edge case is not claimed fixed.++## Completeness assessment++All 20 approved implementation tasks and subsequent accepted UI/correction requests+have corresponding implementation and focused qualification evidence. Pre-push+review and full phone/iPad gates are recorded separately as they complete. Real+library sync behavior is not established by an install or ordinary launch. No+unapproved ordering policy, automatic expiry, or bespoke correction interface is+claimed.
diff --git a/specs/named-character-groups/requirements-review.md b/specs/named-character-groups/requirements-review.mdnew file mode 100644index 00000000..bce3ed60--- /dev/null+++ b/specs/named-character-groups/requirements-review.md@@ -0,0 +1,36 @@+# T-2491 — Revised requirements review packet++**Gate completed:** The owner approved the [revised requirements](requirements.md) and all three defaults below on 2026-10-26 (Sentinel_3b32af853bf4819197b3413b2ae3129f). The [decision log](decision_log.md) records the user wording and provenance. This is the requirements review record; the design still requires its own approval.++## What changed after the owner's annotations++- A join includes its chapter. A leave chapter is the last chapter of membership. Groups start empty; approved membership carries forward.+- The app and share sheet show both group rosters and a character's groups, with chapter ranges such as `Team Loser: Bjorn (38-), Missha (38-41)`. Unknown endpoints remain open or visibly unknown.+- Group aliases are allowed. The most complete overlapping name wins (`Team Jake` before `Jake`); a rename does not retain the old spelling unless added as an alias.+- Group creation and joins may be suggested from saved chapter notes for reader approval. Members can also be added manually with a chapter link.+- A uniquely recognised group reference expands on both note Save and extraction into ordinary individual-character chapter links. A newly approved character with an approved effective membership appears immediately.+- The existing manual link removal is the correction path. There is no separate group-provenance or member-rejection interface. Relevant historical notes are reconsidered after group or membership changes.+- Deleting a mistaken character removes their group memberships; merging characters transfers and deduplicates memberships. Rare chapter-order anomalies are deferred as a separate workflow.++## Narrow points needing an answer++1. If a join and leave for the same person and group both name one chapter, should that chapter be a one-chapter membership, or should the conflicting pair wait for reader review? **Proposed default:** count that chapter as one membership interval, matching the inclusive boundary rule. For join 38, leave 41, leave 42, should the range end at 41 or 42? **Proposed default:** 42, following the owner's “keep the first and last state.” This is an interpretation, not an approved rule.+2. Should deleting a group remove its roster transitions and group-derived links while preserving independently supported individual links and authored notes? **Proposed default:** yes, consistent with complete removal of a mistaken record.+3. On a Work merge, should groups and transitions follow the surviving character/chapter identities? On a Work copy lacking the source chapters, should membership history stay in the source Work? **Proposed default:** yes to both, following existing identity and evidence rules.++All three defaults were approved with the requirements and appear in Requirements 6.1–6.4. The owner explicitly deferred rare chapter-order tie/reorder behavior; it is not an extra approval gate here.++## Critic and peer review++The design critic reviewed the owner-annotated draft first. Two independent peer checks then validated its findings with technical-correctness and reader-UX lenses; external Codex and Kiro agent tools were unavailable, so the prescribed fallback used Sol and Luna subagents. They agreed that four existing guarantees needed to be explicit:++- Retire group-derived links when their note spelling or effective membership no longer supports them, while retaining independent support and authored notes.+- Revalidate final saved content, approved roster, coherent identities and standing rejections before writes; apply app, extension and queued-replay saves atomically.+- Preserve group aliases and deliberate alias removals through sync and backups.+- Suppress unchanged skipped suggestions and avoid promising suggestions when the model fails.++The revised [requirements](requirements.md) state these behaviors without adding a separate correction UI. The reviewers identified the repeated-leave example above as an owner choice. A final critic pass followed by both peer checks found no material blocker to owner review, and the owner subsequently approved all three defaults.++## Verification++Documentation checks verify EARS anchors, user stories and Markdown formatting. No implementation, build, device run or release operation is in scope. Existing Transit T-2491 is already in `spec` status.
diff --git a/specs/named-character-groups/requirements.md b/specs/named-character-groups/requirements.mdnew file mode 100644index 00000000..852725d0--- /dev/null+++ b/specs/named-character-groups/requirements.md@@ -0,0 +1,89 @@+# T-2491 — Named character groups: requirements++**Status:** Approved by owner on 2026-10-26 (Sentinel_3b32af853bf4819197b3413b2ae3129f), including the three defaults in the review packet.++## Introduction++Readers want to name groups of people in a Work so a chapter note can refer to the group without listing each person. Membership changes by chapter and carries forward until changed. A group reference should contribute to the existing automated assignment of its individual members using the roster effective for that chapter.++## Definitions++- **Group:** a reader-named collection of character records within one Work, distinct from a character or place.+- **Transition:** a reader-stated or reader-approved join or leave for one character and one group, attached to a chapter in their Work. A join includes that chapter; a leave includes its chapter as the last chapter of membership.+- **Effective roster:** the members produced by applying approved transitions through a chapter. A group starts empty; an unknown start or end in the display is not evidence of membership outside known chapters.+- **Group reference:** a supported mention of a group in a saved chapter note. It is distinct from an individual character name in that note.+- **Individual assignment:** the existing per-character chapter link, also created from a uniquely recognised group reference for its effective members.++## Non-goals++- Inferring a join, leave or disbanding from the absence of later prose.+- Automatically creating a new character solely because a group name appears.+- Changing the existing individual-name or place-detection behavior for Works without groups.+- Treating a Work-wide note or non-chapter note as a chapter with an effective roster.+- Adding a separate group-provenance or member-rejection interface to chapter links; readers can remove a link through the existing manual control.+- Solving rare tied, unplaced or reordered chapter-order anomalies as a separate user workflow in this feature.++## 1. Named groups and memberships++**User Story:** As a reader, I want to name groups of characters within a Work, so that my notes can refer to several people together.++1. <a name="1.1"></a>The reader SHALL be able to create, rename and delete a group within one Work, keep it distinct from characters and places, and add or remove its aliases. Renaming SHALL NOT retain the former spelling unless the reader adds it as an alias. +2. <a name="1.2"></a>WHEN a character belongs to two groups over the same chapter interval, the system SHALL retain both memberships without removing or merging either group. +3. <a name="1.3"></a>WHEN a group is created, the system SHALL start it with no members and SHALL retain it when its effective roster is empty; the reader SHALL be able to add a member manually with a chapter link. +4. <a name="1.4"></a>WHEN the app restarts, devices sync, or a full-library backup is exported and imported, the system SHALL preserve each group's reader-authored name, aliases, deliberate alias removals and approved membership transitions without silently replacing them with a current-only roster. +5. <a name="1.5"></a>WHEN group or member suggestions are shown, the reader SHALL be able to inspect the saved chapter-note evidence and approve or skip suggested group creation and joins before those changes become part of the roster. +6. <a name="1.6"></a>WHEN successful extraction grounds a new group name or a named character's join or leave in a saved chapter note, the system SHALL offer a creation, join or leave suggestion where the group or transition is not already accepted; it SHALL NOT silently create or change the roster from model output. Model refusal or failure SHALL leave the note and prior accepted state intact.+7. <a name="1.7"></a>WHEN the reader skips a grounded group, join or leave suggestion, unchanged equivalent note evidence SHALL remain suppressed during automatic extraction and explicit manual reconsideration SHALL remain available.+8. <a name="1.8"></a>WHEN the reader creates, renames, aliases, edits membership transitions for, or deletes a group from Work edit mode, the group change SHALL remain a draft until the enclosing Work Save. Cancel SHALL discard all of that Work edit's group drafts. The enclosing Save SHALL commit staged group, metadata, record, link, Work URL and site-membership edits in one atomic transaction; any refusal or save failure SHALL leave every stored edit unchanged and the drafts available for correction or cancellation.++## 2. Chapter-based changes++**User Story:** As a reader, I want to record when someone joins or leaves a group, so that later group references use the right people.++1. <a name="2.1"></a>The reader SHALL be able to record, inspect, edit and remove a character's join or leave for a group at a selected chapter of their shared Work. +2. <a name="2.2"></a>WHEN a member joins at chapter J and leaves at a later chapter L, the effective roster SHALL include the member in J, L and the chapters between them, and exclude the member before J and after L unless another approved transition establishes membership there. +3. <a name="2.3"></a>WHEN no later approved transition changes a member's state, the system SHALL carry that state through later chapters regardless of whether the member or group is mentioned again. +4. <a name="2.4"></a>WHEN repeated joins or leaves do not change a character's current group state, the effective roster SHALL retain one continuous interval rather than create a duplicate interval. +5. <a name="2.5"></a>WHEN a transition is added, edited or removed, the system SHALL recalculate effective rosters and reconsider affected saved group references, including previously processed chapters. ++## 3. Group references and individual assignment++**User Story:** As a reader, I want a note that names a group to assign its members individually, so that existing character history remains useful.++1. <a name="3.1"></a>WHEN a saved chapter note uniquely matches an existing group, successful note Save and extraction SHALL automatically add the ordinary individual-character chapter links for exactly the group's effective members at that chapter, without using its current roster for earlier chapters. +2. <a name="3.2"></a>WHEN a character is named directly or belongs to two referenced groups in one chapter, the system SHALL retain at most one ordinary chapter link for that character and chapter. +3. <a name="3.3"></a>WHEN a group's effective roster is empty, a reference to that group SHALL add no individual-character links. +4. <a name="3.4"></a>WHEN a new character is approved and an approved group membership makes that character effective for the source chapter, the system SHALL show the resulting group membership and ordinary chapter link without waiting for another extraction request. +5. <a name="3.5"></a>WHEN a group is created or renamed, an alias changes, or an approved membership changes, the system SHALL reconsider relevant saved chapter notes, including notes processed before that change. +6. <a name="3.6"></a>WHEN group, character or place names overlap the same span of a chapter note, the system SHALL prefer the most complete matched name for that span, so `Team Jake` wins over `Jake` there; when an equally complete match still identifies multiple records, it SHALL avoid choosing one arbitrarily. +7. <a name="3.7"></a>WHEN a group-derived link is removed manually, the system SHALL honor that correction on later processing of unchanged evidence; other existing individual-name and place behavior SHALL remain available. +8. <a name="3.8"></a>WHEN a saved note loses its supported group spelling or an approved roster change removes a member from that chapter, the system SHALL retire unsupported group-derived link support; absent an explicit reader removal of the pair, it SHALL retain the link while independent accepted group or individual-name support remains, and preserve authored link notes under existing recovery behavior when all support is lost. +9. <a name="3.9"></a>BEFORE saving a group-derived link or approved group/join/leave suggestion, the system SHALL revalidate the final saved note, coherent same-Work identities, applicable approved roster history and standing rejections; stale or failed writes SHALL leave prior links, notes, corrections and proposals intact. App Save, share-extension Save and queued replay SHALL apply equivalent results atomically to final saved content.++## 4. Group and character views++**User Story:** As a reader, I want to see group membership from either a group or a character, so that I can understand who belongs where in the story.++1. <a name="4.1"></a>The app Work page and share sheet SHALL let the reader open a group and see its characters with chapter ranges, and open a character and see the groups to which that character belongs with the same ranges. +2. <a name="4.2"></a>WHEN a known membership start or end is unavailable, the displayed range SHALL leave that endpoint open or mark it unknown without inferring a chapter; a join at chapter 38 with no known leave MAY display as `(38-)`, and a join at 38 with a leave at 41 MAY display as `(38-41)`. +3. <a name="4.3"></a>WHEN a character has multiple separate membership intervals in one group, both the group and character views SHALL preserve the distinct ranges rather than collapse them into one continuous interval. +4. <a name="4.4"></a>WHEN a group or membership proposal is reviewed, the reader SHALL be able to see its source chapter and supported note text, using the existing character review pattern as the baseline. +5. <a name="4.5"></a>WHEN the Work page is in view mode, group rosters SHALL be read-only and use the same wrapping pill and expanded detail-card presentation as Characters and Places; the Groups collection SHALL appear between Characters and Places. Group creation and editing controls SHALL appear only in Work edit mode.+6. <a name="4.6"></a>WHEN a transition is edited, the selected chapter and its Join or Leave action SHALL be presented together as one membership-change row; Join and Leave SHALL be directly selectable and accessible by name.++## 5. Removal and data continuity++**User Story:** As a reader, I want corrections to remove mistaken group data without losing unrelated notes, so that the cast remains trustworthy.++1. <a name="5.1"></a>WHEN a character is deleted as a mistaken record, the system SHALL remove its group memberships; WHEN duplicate characters are merged, the surviving character SHALL inherit their memberships without duplicate intervals for the same group and chapters. +2. <a name="5.2"></a>WHEN group-derived chapter support changes, the system SHALL preserve independent individual-name support and any reader-authored chapter-link note under the existing link-note recovery behavior. +3. <a name="5.3"></a>WHEN a backup is imported or sync delivers conflicting authored group names, aliases or membership changes that cannot be reconciled coherently, the system SHALL retain the authored changes rather than silently choose one. ++## 6. Same-chapter transitions and Work operations++**User Story:** As a reader, I want group history to follow the records I keep, so that correcting duplicates or copying a Work does not invent membership.++1. <a name="6.1"></a>WHEN a join and leave for one character and group name the same chapter, the effective roster SHALL include that character for that one chapter. +2. <a name="6.2"></a>WHEN repeated leaves name later chapters without a new join, the last stated leave chapter SHALL be the final membership chapter; repeated joins before a leave SHALL keep the first join chapter. +3. <a name="6.3"></a>WHEN a group is deleted, the system SHALL remove that group, its transitions and unsupported group-derived chapter links while preserving independently supported individual links and reader-authored chapter-link notes. +4. <a name="6.4"></a>WHEN Works merge, groups and transitions SHALL follow surviving character and chapter identities without duplicate memberships; WHEN a Work is copied without source chapters, the chapter-based membership history SHALL remain in the source Work.
diff --git a/specs/named-character-groups/scope-assessment.md b/specs/named-character-groups/scope-assessment.mdnew file mode 100644index 00000000..0e187eb7--- /dev/null+++ b/specs/named-character-groups/scope-assessment.md@@ -0,0 +1,37 @@+# T-2491 — Named character groups: scope assessment++**Stage:** Starwave Phase 1 completed; full-spec routing and the `named-character-groups` folder name were approved on 2026-10-25. The folder name does not decide the product label.++**Historical note:** This document records the questions that drove scope routing. The owner's 26 October annotations answered many of them; [requirements.md](requirements.md) and [decision_log.md](decision_log.md) are the current requirements-stage record.++## Agreed direction++A reader can name a group of people within one Work. A character may belong to multiple groups. Joining and leaving are chapter-based transitions, with membership carried forward until a later transition. A reference to a group should feed the existing automated assignment of its individual members using the roster effective for that chapter. Groups follow the existing character-list behavior; absence from later prose does not disband a group. The example of joining in chapter 5 and leaving from chapter 12 illustrates the goal; it does not decide boundary conventions.++## Current behavior found in the repository++- Characters are Work-owned records with a name, retained name key and aliases (`Models.swift`, `Character`). Chapter notes are `Entry` records with stable UUIDs and optional sequence and title fields.+- The live model output names individual characters and places from the saved note. Grounding rejects an unquoted name, and the note-first assembler routes grounded names to existing records. Known coherent character matches gain chapter links automatically; new characters reach review (`ExtractionResult.swift`, `CharacterGrounding.swift`, `CharacterExtractionAssembler.swift`, `character-chapter-associations/note-first-redesign/requirements.md`).+- Successful saved chapter-note writes also link complete names of coherent known characters **and known places**, without AI, through the shared app, extension and queued-replay repository path. An unchanged-note Save can fill a missing supported link. There is no launch-wide backfill (`character-chapter-associations/save-time-known-links/smolspec.md`). Group expansion's timing relative to this path is an open decision.+- A saved chapter–character link currently asserts supported mention in that chapter note. Removing its final supported spelling removes the active link. A group reference expanded into individual links would change that evidence contract and needs explicit requirements for provenance, correction, and removal (`character-chapter-associations/requirements.md`, §§2 and 4).+- Chapter display order uses a derived placement from URL sequence or title and falls back to last-share time for unplaced chapters, then input order for ties; the stable Entry UUID is separate from its mutable placement (`WorkChapterOrder.swift`, `ChapterKeyDerivation.swift`). Input order is not a safe implicit cross-device transition order. Chronology for transitions cannot be inferred from chapter number alone.+- Accepted links, pending review, suppression, source guards and coverage already have persistence and replay rules. A group edit or changed chapter placement may affect previously processed notes, so recalculation and stale-review behavior need explicit treatment.++Relevant captured knowledge: [How to rank saved associations without double counting evidence](/Users/arjen/Documents/Obsidian/Main/03-Notes/Generated/How%20to%20rank%20saved%20associations%20without%20double%20counting%20evidence.md) and [Preventing false coverage when asynchronous review results arrive](/Users/arjen/Documents/Obsidian/Main/03-Notes/Generated/Preventing%20false%20coverage%20when%20asynchronous%20review%20results%20arrive.md). These are implementation cautions, not product decisions.++## Routing recommendation++**Full spec.** User-owned ambiguity fires: several materially different behaviors remain valid for join/leave boundaries, unplaced or reordered chapters, aliases and ambiguous group names, reader review, and retrospective edits. Expensive-to-reverse also fires: group and transition history will be persisted and must survive CloudKit and backup/restore. The central design may also have competing representations, but that need not be decided during scope assessment. A smolspec would prematurely settle product semantics in implementation tasks.++## Questions for requirements++1. Does a join affect the named chapter itself, and does a leave stop membership in the named chapter itself? What should the UI say at the boundary?+2. What orders a transition when a chapter is unnumbered, has duplicate placement, or is moved, renumbered or merged? Should its effect move with the Entry or remain at its former position?+3. Can groups have aliases? If a group spelling also matches a character, place or another group, what should be suggested, saved or left unresolved?+4. Does a group reference create the same chapter association as an individual mention, or a distinct association that is displayed as individual assignment? How should a reader see and correct its group provenance, including explicit Skip or later roster changes?+5. When a roster transition is inserted, edited or removed after later chapters were processed, which saved group references should recalculate? What happens to explicit reader corrections and authored chapter-link notes?+6. What should happen when a character or group is renamed, combined, deleted, copied to another Work, or arrives out of order through sync or restore?++## Phase 1 outcome++The owner approved full-spec routing and the folder name. The parent verified Transit T-2491 is in `spec` status. Requirements questions and an EARS draft are in [requirements.md](requirements.md). The Phase 1 approval did not decide any of their open product questions.
diff --git a/specs/named-character-groups/tasks-review.md b/specs/named-character-groups/tasks-review.mdnew file mode 100644index 00000000..f183c3f3--- /dev/null+++ b/specs/named-character-groups/tasks-review.md@@ -0,0 +1,24 @@+# T-2491 task-plan review — named character groups++**Gate:** approve the coding task plan only. The design is approved; no implementation has begun or is authorized by this packet.++## Plan shape++The [task list](tasks.md) has 20 pending coding tasks in 10 adjacent red/green pairs. A single dependency chain keeps schema, association proof and saved-note behavior stable before extraction and UI work. It covers all 32 approved acceptance criteria.++| Sequence | What gets proven before implementation |+| --- | --- |+| 1–4 | A populated V21 library and old archives survive V22; authored group events fold into inclusive historical intervals even after sync conflicts and late copies. |+| 5–8 | Complete-name matching and typed group proof produce one ordinary character link; group commands and all final-note Save paths update history safely. |+| 9–12 | Remote changes resume historical relinking; backup, empty library, merges, deletion and chapterless copies retain the approved data semantics. |+| 13–16 | Grounded group/join proposals require approval; app and share sheet show reciprocal ranges; the app gains group and transition editing. |+| 17–20 | The requested ordinary Remove link button and Restore action persist through restart, backup and reordered sync; focused app/extension journeys finish the wiring. |++## Early risks and review outcome++- The first red/green pair uses a **populated V21** fixture to pin direct associations, rejections, rebinds and authored notes before the V22 schema/receipt work.+- Historical relinking uses a covered 1,000-chapter affected Work plus 5,000 unrelated chapters. Tests require zero unrelated scans and batches of at most 128 chapters, while M4 elapsed time is reported before UI work. The current chapter is linked in its Save transaction; older chapters use a durable retry queue. This makes the design's latency fallback concrete without claiming a measured time threshold.+- The plan uses focused tests during development and the repository's code-commit/pre-push test gates at the appropriate phases. No physical `Personal` device run is part of this spec.+- Planning critic and peers reviewed the plan. Their findings about missing editor controls, executable reconciliation bounds, correction-event persistence and empty-library tests were incorporated; follow-up reviews confirmed each resolved. `rune list` parsed all 20 tasks, and every approved requirement ID is referenced.++**Approval question:** Do the tasks look good? Approval would allow the remaining Starwave wrap-up steps for this spec; implementation remains a separate workflow and needs its own instruction.
diff --git a/specs/named-character-groups/tasks.md b/specs/named-character-groups/tasks.mdnew file mode 100644index 00000000..e7065288--- /dev/null+++ b/specs/named-character-groups/tasks.md@@ -0,0 +1,148 @@+---+references:+ - specs/named-character-groups/requirements.md+ - specs/named-character-groups/design.md+ - specs/named-character-groups/decision_log.md+---+# T-2491 Named character groups implementation tasks++- [x] 1. Red: test V21 to V22 data compatibility <!-- id:2xazcpj -->+ - Core fixtures pin populated V21 ledger, rejections, notes, migration markers 16–21, archive 20/21,19/20,18/19, and conflicting physical rows.+ - Stream: 1+ - Requirements: [1.4](requirements.md#1.4), [5.3](requirements.md#5.3)+ - References: specs/named-character-groups/design.md++- [x] 2. Green: add V22 tables and legacy adapters <!-- id:2xazcpk -->+ - Freeze V21; append lightweight V22 schema/group event tables and marker 22; preserve old archive acceptance and byte-identical V21 direct ledger receipts.+ - Blocked-by: 2xazcpj (Red: test V21 to V22 data compatibility)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.4](requirements.md#1.4), [5.3](requirements.md#5.3)+ - References: specs/named-character-groups/design.md++- [x] 3. Red: generate group-fact and roster fold cases <!-- id:2xazcpl -->+ - Swift Testing seeded permutations cover names/aliases/removals, concurrent heads, tombstones, joins/leaves including same chapter, repeated transitions and multi-group intervals.+ - Blocked-by: 2xazcpk (Green: add V22 tables and legacy adapters)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2)+ - References: specs/named-character-groups/design.md++- [x] 4. Green: implement causal groups and roster projection <!-- id:2xazcpm -->+ - Add Core GroupFactEvent/GroupTransition folds, immutable edit/rebind events, coherent chapter roster and reciprocal MembershipRange values; quarantine disputed claims.+ - Blocked-by: 2xazcpl (Red: generate group-fact and roster fold cases)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2)+ - References: specs/named-character-groups/design.md++- [x] 5. Red: test longest matching and typed link proof <!-- id:2xazcpn -->+ - Pin Team Jake over Jake, equal-length refusal, Unicode, empty roster, direct/group support union, V21 parity, unsupported retirement and authored-note recovery.+ - Blocked-by: 2xazcpm (Green: implement causal groups and roster projection)+ - Stream: 1+ - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.6](requirements.md#3.6), [3.8](requirements.md#3.8), [5.2](requirements.md#5.2)+ - References: specs/named-character-groups/design.md++- [x] 6. Green: implement shared resolver and V22 association support <!-- id:2xazcpo -->+ - Extend RecordMentionGrounding, AssociationEndpointInventory and ledger with group basis receipts and support union, leaving existing literal direct validation intact.+ - Blocked-by: 2xazcpn (Red: test longest matching and typed link proof)+ - Stream: 1+ - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.6](requirements.md#3.6), [3.8](requirements.md#3.8), [5.2](requirements.md#5.2)+ - References: specs/named-character-groups/design.md++- [x] 7. Red: test group commands and all saved-note paths <!-- id:2xazcpp -->+ - SwiftData tests cover create/rename/delete/alias and transition edit/remove; manual/capture/reparse/replay/correction Save; historical relink, same-Work guards and rollback.+ - Blocked-by: 2xazcpo (Green: implement shared resolver and V22 association support)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.9](requirements.md#3.9), [6.3](requirements.md#6.3)+ - References: specs/named-character-groups/design.md++- [x] 8. Green: wire group mutations and known-link expansion <!-- id:2xazcpq -->+ - Add LibraryProviding/Repository group commands and extend recordKnownChapterLinks call sites inside their existing one-save transactions, using final saved chapter evidence.+ - Blocked-by: 2xazcpp (Red: test group commands and all saved-note paths)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.9](requirements.md#3.9), [6.3](requirements.md#6.3)+ - References: specs/named-character-groups/design.md++- [x] 9. Red: test remote reconciliation and bounded retry <!-- id:2xazcpr -->+ - In Core integration tests seed 1,000 chapters in the changed Work plus 5,000 unrelated chapters; assert current Save scans no unrelated chapters and resumed historical batches process at most 128 selected chapters with one association save per batch. Report M4 elapsed time without a fabricated pass threshold. Cover remote-only join/rename/alias removal, import invalidation, interruption and idempotence.+ - Blocked-by: 2xazcpq (Green: wire group mutations and known-link expansion)+ - Stream: 1+ - Requirements: [1.4](requirements.md#1.4), [2.5](requirements.md#2.5), [3.5](requirements.md#3.5), [3.8](requirements.md#3.8)+ - References: specs/named-character-groups/design.md++- [x] 10. Green: implement historical reconciliation queue <!-- id:2xazcps -->+ - Add device-local per-Work digest/cursor, current-chapter Save atomicity, and durable batches of at most 128 other saved chapters; advance cursor only after each commit. Hook SyncMonitor/reconcileAfterSync and import invalidation; run the covered M4 test from task 9 before UI work.+ - Blocked-by: 2xazcpr (Red: test remote reconciliation and bounded retry)+ - Stream: 1+ - Requirements: [1.4](requirements.md#1.4), [2.5](requirements.md#2.5), [3.5](requirements.md#3.5), [3.8](requirements.md#3.8)+ - References: specs/named-character-groups/design.md++- [x] 11. Red: test backup, deletion, merge and copy semantics <!-- id:2xazcpt -->+ - Archive roundtrip/predecessor/conflict tests plus character/group deletion, character/Work merge with late old events, duplicate intervals and chapterless record/Work copy. Add isolated empty-library tests for all three new tables, tombstones, inventory/remaining-row counts, interrupted sweep and successful completion.+ - Blocked-by: 2xazcps (Green: implement historical reconciliation queue)+ - Stream: 1+ - Requirements: [1.4](requirements.md#1.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+ - References: specs/named-character-groups/design.md++- [x] 12. Green: integrate backup and record operations <!-- id:2xazcpu -->+ - Extend backup/empty-library, RecordEditing, WorkMerge and RecordCopy with immutable successor rebinds, tombstones, dedupe and link recalculation; keep chapter history at source on copy.+ - Blocked-by: 2xazcpt (Red: test backup, deletion, merge and copy semantics)+ - Stream: 1+ - Requirements: [1.4](requirements.md#1.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4)+ - References: specs/named-character-groups/design.md++- [x] 13. Red: test grounded group and join proposals <!-- id:2xazcpv -->+ - Intelligence/coordinator tests pin saved-note evidence, group/join/leave suggestions, model arbitration against existing group names/aliases, review/Skip suppression and manual reconsideration, duplicate accepted-leave suppression, stale approval refusal, model failure and immediate character-link publication.+ - Blocked-by: 2xazcpu (Green: integrate backup and record operations)+ - Stream: 1+ - Requirements: [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [1.7](requirements.md#1.7), [3.4](requirements.md#3.4), [4.4](requirements.md#4.4)+ - References: specs/named-character-groups/design.md++- [x] 14. Green: extend extraction and approval review <!-- id:2xazcpw -->+ - Extend ExtractionResult, CharacterExtractionCoordinator and existing character review path; approved proposals commit through Core after final evidence recheck.+ - Blocked-by: 2xazcpv (Red: test grounded group and join proposals)+ - Stream: 1+ - Requirements: [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [1.7](requirements.md#1.7), [3.4](requirements.md#3.4), [4.4](requirements.md#4.4)+ - References: specs/named-character-groups/design.md++- [x] 15. Red: test reciprocal roster views and group editor <!-- id:2xazcpx -->+ - Core/native tests cover group-to-character and character-to-group cards, open endpoints, separate intervals, empty groups, sorting and accessible disclosure. App model/UI tests cover create/rename/delete, alias add/remove, member and chapter selection, transition edit/remove, Save/Cancel and failed/stale commit states.+ - Blocked-by: 2xazcpw (Green: extend extraction and approval review)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3)+ - References: specs/named-character-groups/design.md++- [x] 16. Green: implement reciprocal cards and group editor <!-- id:2xazcpy -->+- Extend WorkDetailModel/View and ShareWorkContext with shared GroupSummary/MembershipRange disclosure. Build the app group editor and chapter-linked member/transition controls following existing character review/editor recipes. Nested Done stages in the Work edit session; Work Save commits one atomic Work+groups transaction and Work Cancel discards all group drafts. In view mode, use the existing wrapping pill/detail-card presentation, read-only, between Characters and Places.+ - Blocked-by: 2xazcpx (Red: test reciprocal roster views and group editor)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3)+ - References: specs/named-character-groups/design.md++- [x] 17. Red: test ordinary Remove and Restore chapter link <!-- id:2xazcpz -->+ - Core/EntryDetailModel/focused UI tests pin approved generic Remove button, current-support suppression, genuinely new evidence, explicit restore and retained association notes. Persist/replay correction events through restart, archive export/import and reordered CloudKit delivery; assert unchanged-key suppression survives.+ - Blocked-by: 2xazcpy (Green: implement reciprocal cards and group editor)+ - Stream: 1+ - Requirements: [3.7](requirements.md#3.7), [3.8](requirements.md#3.8), [5.2](requirements.md#5.2)+ - References: specs/named-character-groups/design.md++- [x] 18. Green: wire ordinary chapter-link correction <!-- id:2xazcq0 -->+ - Add new pair-support rejection/acknowledgement encoding and fold to AssociationLedger/Backup codecs, with LibraryProviding API and EntryDetailView.chapterAssociationsSection trailing Remove/Restore actions. Preserve primary note editor and skipped-link flow; rerun archive compatibility tests after new event types exist.+ - Blocked-by: 2xazcpz (Red: test ordinary Remove and Restore chapter link)+ - Stream: 1+ - Requirements: [3.7](requirements.md#3.7), [3.8](requirements.md#3.8), [5.2](requirements.md#5.2)+ - References: specs/named-character-groups/design.md++- [x] 19. Red: test complete app and extension journeys <!-- id:2xazcq1 -->+- Focused iPhone/iPad/Mac/extension journeys cover nested and enclosing Save/Cancel/failure, delete, manual transitions, grounded proposal approval, Save expansion, retrospective updates, reciprocal ranges, ordinary Remove/Restore and accessibility.+ - Verification note: the three CharacterGroups journeys passed on iPhone and iPad. The native Mac UI test compiled, but XCTest timed out enabling automation before test discovery (0 test cases executed; 1 runner failure); this is not a green Mac rendered journey. The share-extension XCUITest surface is unavailable by its existing Q9 decision; the Core share-context projection is asserted and the embedded iOS/Mac extensions compiled.+ - Blocked-by: 2xazcq0 (Green: wire ordinary chapter-link correction)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [4.1](requirements.md#4.1), [4.4](requirements.md#4.4)+ - References: specs/named-character-groups/design.md++- [x] 20. Green: finish navigation/state wiring and focused gates <!-- id:2xazcq2 -->+ - Connect Work/Entry detail, review and share-sheet refresh paths to Core values; satisfy focused journeys and AGENTS.md phase-selected serial Core/native/UI gates without weakening assertions.+ - Verification note: endpoint validation now follows coherent live group-transition heads, so removed/merged ancestors do not block reconciliation of the Work; missing live endpoints remain retryable. Focused regressions and final Core/fast/quick gates passed. See [verification run](verification-run.md) for exact counts and the Mac automation limitation.+ - Blocked-by: 2xazcq1 (Red: test complete app and extension journeys)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.4](requirements.md#3.4), [4.1](requirements.md#4.1), [4.4](requirements.md#4.4)+ - References: specs/named-character-groups/design.md
diff --git a/specs/named-character-groups/verification-run.md b/specs/named-character-groups/verification-run.mdnew file mode 100644index 00000000..2a38ae7a--- /dev/null+++ b/specs/named-character-groups/verification-run.md@@ -0,0 +1,651 @@+# Verification Run: Ordinary Chapter-Link Remove and Restore++Date: 2026-10-26++Tasks 17/18 add durable pair-scoped correction and acknowledgement events for+ordinary character chapter links. Removal suppresses only support captured by+that correction. A later direct or group support can reactivate the pair, and+Restore acknowledges the correction and re-evaluates current evidence under+the repository lock. Authored association notes remain attached to their pair.++## Focused regression coverage++- `AssociationLedgerTests`: pair-scoped support suppression, explicit ack,+ cross-pair acknowledgement rejection, legacy direct-root support capture,+ serialization, and reordered/duplicate event replay (28 tests in the focused+ suite).+- `NamedGroupSaveLinkTests.ordinaryRemovalSuppressesCapturedGroupSupportAndExplicitRestoreReactivatesIt`:+ removes a supported group link, confirms unchanged Save stays suppressed,+ exports/imports a current V21 archive, reopens, restores, and exercises new+ support after changed note and roster evidence (1 test).+- `EntryDetailModelTests`: preserves the open note draft and exposes the note+ editor when active support exists alongside an unresolved older correction+ (41 tests in the suite).+- `AssociationNotesUITests.testOrdinaryChapterLinkRemoveRestoreKeepsTheNoteEditorRoute`:+ exercises Remove, Restore, and the existing note-editor route on the+ dedicated `Asterism T2491 Phone` simulator (1 test, 0 failures).++## Required implementation gates++- `make test-core SWIFT_TEST_FLAGS='--scratch-path /tmp/t2491-pair-correction-core'`:+ **passed**, 3,604 tests in 349 suites, exit 0; no compiler warnings in the+ captured output (`/tmp/t2491-final-core.log`).+- `make test-fast`: **passed**, 152 tests in 12 suites; 456 declared identifiers+ verified.+- `make test-quick`: **passed**, 1,871 tests, 0 failures, 0 skipped. Its+ Development Mac build succeeded and verified the embedded+ `AsterismShareExtensionMac.appex`. The quick target used its configured+ iPhone 18 Pro simulator.++The test output includes expected Core Data diagnostics from tests that+deliberately use corrupt fixtures. Existing warnings also appear in unrelated+NoEpisode, Intelligence and re-share files during some focused/native builds;+the final unfiltered Core compile emitted no compiler warnings.++## Final tasks 19/20 verification++Date: 2026-10-26++- `NamedGroupSaveLinkTests`: **27 tests in 1 suite passed**, including the+ Work-detail roster and share-context range, deletion followed by a new member+ join, and merge followed by a remote group rename.+- Final unfiltered serial `make test-core`: **3,606 tests in 349 suites passed**+ in 226.255 s. The changed Core source compiled cleanly in the focused suite;+ the unfiltered run reused that successful build and emitted no new compiler+ warnings.+- `make test-fast`: **152 tests in 12 suites passed**; 456 declared test+ identifiers verified.+- `make test-quick`: result bundle `/tmp/t2491-quick-final.xcresult` reports+ **1,871 total tests passed, 0 failed, 0 skipped**. Its Development Mac app+ build succeeded, and the embedded `AsterismShareExtensionMac.appex` was+ present.+- `CharacterGroupsUITests` on `Asterism T2491 Phone`: **3 tests passed, 0+ failures** (134.242 s), result bundle+ `/tmp/t2491-groups-iphone-final-source.xcresult`.+- `CharacterGroupsUITests` on `iPad Pro 11-inch (M5)`: **3 tests passed, 0+ failures** (126.074 s), result bundle+ `/tmp/t2491-groups-ipad-final-source.xcresult`.+- The native Mac UI test target compiled, but its runner failed to initialize:+ XCTest reported `Timed out while enabling automation mode`; the result bundle+ records **0 test cases executed and 1 test-runner failure**. This is an+ incomplete Mac rendered journey, not a passing Mac UI result. No workaround+ was used.+- The share extension has no XCUITest coverage by its existing Q9 decision.+ The Core integration test asserts the same group/member/range value exposed+ in `ShareWorkContext`, and both iOS and Mac embedded share extensions+ compiled.++The read-only final source review cleared the P2 finding in group-history+reconciliation: endpoint validation now uses coherent live transition heads,+while immutable ancestry and retry behavior for missing live endpoints remain+in place. Full UI acceptance remains a pre-push-review gate; this verification+records only the focused implementation journeys.++## Acceptance follow-up: group editor style and explicit leave extraction++Date: 2026-10-26++The owner authorized a follow-up after the 20-task implementation to keep group+creation inside Work edit mode, retain the existing app form/sheet presentation,+and review explicit extracted membership leaves. The leave path is evidence+based: group and character names must occur in a saved chapter quote; absence+does not create a leave. The two-chapter Ainar sequence below exercises group+creation filtering, independent character Skip, accepted join, alias-name leave,+and accepted leave through the extractor, assembler, coordinator, and review+model.++### Focused regressions and rendered journeys++- `CharacterExtractionCoordinatorTests.existingGroupAinarJoinSkipThenLeave`:+ **1 test passed** as part of 49 coordinator tests in 1 suite. The test supplies+ `Team Loser` and `The Losers` as existing names/aliases, model output that+ includes both as noisy character candidates and a duplicate group candidate,+ an independent `Borin` character row that is skipped through+ `CharacterReviewModel`, an approved `Team Loser` join for Ainar, and an+ explicit next-chapter `The Losers` leave that is approved through review. The+ test confirms the leave applicability query uses the normalized alias key.+ Result bundle: `/tmp/t2491-coordinator-sequence-normalized.xcresult`.+- `CharacterGroupsUITests` on `Asterism T2491 Phone`: **3 tests passed, 0+ failures**. This covers grounded group/join review and approval, editor+ Cancel/Save, and manual membership with reciprocal chapter range and+ accessible actions. Result bundle:+ `/tmp/t2491-character-groups-ui.xcresult`.+- The picker journey was rerun separately after the style correction:+ `testManualJoinPublishesReciprocalChapterRangeAndAccessibleActions` passed+ **1/1**, including selecting the exact Brede character option. Result bundle:+ `/tmp/t2491-group-picker-ui.xcresult`.+- `CharacterGroupsUITests` on `iPad Pro 11-inch (M5)`: **3 tests passed, 0+ failures**. Result bundle:+ `/tmp/t2491-groups-ipad-final-source.xcresult`.+- Rendered screenshots from the editor flow were exported to+ `/tmp/t2491-character-groups-ui-export/`: `group-view-mode`,+ `group-work-edit-mode`, `group-editor`, and `group-saved-view-mode`. The view+ mode shows a read-only roster disclosure; Add group appears in Work edit+ mode; the group editor uses the app's established sheet/form treatment.+- Mac rendered UI automation remains incomplete: the earlier runner failed+ during automation-mode startup with 0 test cases executed. No retry or+ workaround was used. The Mac app and embedded share extension compile+ successfully; the extension has no rendered UI suite under its existing Q9+ decision.++### Final implementation gates++- Unfiltered serial `make test-core` with private scratch path+ `/tmp/t2491-namedgroups-core`: **3,609 tests in 349 suites passed**, exit 0,+ in 248.671 s. No compiler warnings were emitted in this unfiltered Core run.+- `make test-fast`: **152 tests in 12 suites passed**, exit 0.+- `make build-mac DERIVED_DATA=/tmp/t2491-acceptance-derived`: **BUILD+ SUCCEEDED**. `AsterismShareExtensionMac.appex` is present in the built+ Development app. The build reports existing warnings in NoEpisode,+ Foundation Model initializer call sites, and RuleSuggestionCoordinator;+ none are in the changed group implementation.+- `make test-quick` on the Development iPhone 18 Pro simulator: **1,875 total+ tests passed, 0 failed, 0 skipped** according to the result bundle. This is+ 1,864 Swift Testing cases plus 11 XCTest cases. Result bundle:+ `/tmp/t2491-final-test-quick.xcresult`.++The quick run and focused UI runs include system/Core Data diagnostics from+isolated test fixtures and simulator services. The Development app was used+only on the dedicated simulator; no Personal install, physical-device run, or+real-library access occurred. Full simulator UI acceptance remains a+pre-push-review gate.++## Cyan selection follow-up++Date: 2026-10-27++The user authorized a scoped return of cyan selection while retaining the+native segmented-control shape and appearance. A first SwiftUI `.tint` test+passed its light/dark assertions but its screenshots still showed a white+selected capsule. The per-instance UIKit candidate was retained after its+screenshots and accessibility journey passed; no global appearance or+introspection was used.++### Rendered verification++- `CharacterGroupsUITests/testGlassSortAndMembershipControlsInLightAndDark` on+ iPhone 18 Pro: **1 test passed, 0 failures** (130.580 s), result bundle+ `/tmp/t2491-cyan-uikit-final.xcresult`.+- The same focused journey on iPad Pro 11-inch (M5): **1 test passed, 0+ failures** (121.330 s), result bundle+ `/tmp/t2491-cyan-uikit-ipad.xcresult`.+- Both runs assert the existing option IDs and selection state for Newest,+ Chapter, Join and Leave; the 44-point target; accessible group labels; and+ selected/unselected behavior in forced light and dark appearances.+- Exported phone screenshots in+ `/tmp/t2491-cyan-uikit-final-attachments/` show cyan selection with readable+ black selected text and the native gray track/capsule geometry. Representative+ files: `6B5589EF-CDC1-4F7E-92D7-D02B9021B36C.png` (light Newest),+ `ACC978B1-7235-4A82-8BB4-8C699267B3C7.png` (dark Newest),+ `64490A1A-8AF8-4320-8DA8-CD6908325FBE.png` (light Join), and+ `028D4780-CEC2-4EBD-A26D-35CA801FBE8C.png` (dark Join).++### Final implementation gates++- Unfiltered serial `make test-core`, private scratch path+ `/tmp/t2491-cyan-core-scratch`: **3,613 tests in 350 suites passed** in+ 226.596 s. The run emitted 90 pre-existing warnings; none referenced the+ changed ConstellationKit source or selection test.+- `make test-quick`, result bundle `/tmp/t2491-cyan-quick.xcresult`: **1,887+ total tests passed, 0 failed, 0 skipped** (1,876 Swift Testing cases plus 11+ XCTest cases). The signed Development Mac app and embedded share extension+ build succeeded; there were no new warnings in changed files.+- `ConstellationSelectionRecipesTests.segmentedAccessibilityFramesFollowVisualDirection`+ passed as part of the full Core run and checks LTR/RTL frame ordering and the+ 44-point frame height.+- `git diff --check` passed. No app was installed or launched on a physical+ device, and no real library was accessed.++The initial UIKit test startup stalled before XCTest after 9:29 with no runner+and the simulator at SpringBoard. After the documented simulator shutdown+recovery, the raw-log retry completed normally. An intermediate bridge without+explicit option children failed the existing stable-ID assertion; the retained+implementation restores those IDs through public accessibility-container+elements. Full UI acceptance remains a pre-push-review gate.++## Softened cyan across status selectors++Date: 2026-10-27++The selected native segment now uses the existing adaptive 14% selected-mark+wash and cyan text on the same per-instance UIKit control. This keeps the+system's native track and material. The shared control is used for group sort+and Join/Leave, Work/Reading status in WorkDetail, and Reading status in the+Works status sheet. The five-choice Reading control uses the native horizontal+row when it fits (verified on iPad); on iPhone it selects the stacked SwiftUI+capsule fallback to keep every label readable. That fallback shares the+selection palette and accessibility identifiers but does not use native Liquid+Glass geometry/material. No global appearance setting or subview introspection+is used.++### Rendered verification++- `CharacterGroupsUITests/testGlassSortAndMembershipControlsInLightAndDark` on+ iPhone 18 Pro: **1 test passed, 0 failures**, both forced appearances. The+ light/dark Work and Reading controls, sort and membership states are attached+ in `/tmp/t2491-softcyan-phone-r5-attachments/`.+- `CharacterGroupsUITests/testWorksStatusSheetUsesTheSharedGlassReadingSelectorInLightAndDark`+ on iPhone 18 Pro: **1 test passed, 0 failures**, including the visible and+ accessible “Reading status” purpose caption; light/dark screenshots are in+ `/tmp/t2491-softcyan-phone-sheet-context-r6-attachments/`.+- The same Works status-sheet test on iPad Pro 11-inch (M5): **1 test passed,+ 0 failures**; light/dark screenshots are in+ `/tmp/t2491-softcyan-ipad-sheet-context-r3-attachments/`.+- `WorkDetailStatusUITests/testMarkingAWorkToReadReachesTheFifthSegmentAndTheMetaLine`+ on iPad Pro 11-inch (M5): **1 test passed, 0 failures**, including the fifth+ status choice and resulting “Reading: To read” meta line. Its first attempt+ stopped at fixture setup because the helper queried `recent-list` specifically+ as a collection view; the identifier-agnostic query used by the sibling+ journey fixes this and preserves the full fifth-choice assertions.++### Final implementation gates++- Unfiltered serial `make test-core`, private scratch path+ `/tmp/t2491-softcyan-core`: **3,613 tests in 350 suites passed**, exit 0, in+ 230.417 s. The build reported existing warnings in unrelated Core and+ Intelligence sources/tests; none referenced the changed selector source.+- `make test-fast`: **152 tests in 12 suites passed**; the 456 declared fast+ identifiers were verified before execution.+- `make test-quick`, result bundle `/tmp/t2491-softcyan-quick.xcresult`:+ **1,887 passed, 0 failed, 0 skipped** (1,876 Swift Testing cases and 11+ XCTest cases). Its signed Development Mac app/embedded-share-extension build+ succeeded, and the Makefile confirmed the extension product is present.+- `git diff --check` passed. Full UI acceptance remains a pre-push-review gate.+ Only Development simulator fixtures were used; no Personal install, physical+ device run, or real-library access occurred.++## PR Pilot qualification — 2026-10-27++Initial source: `085f9943`, based exactly on fresh `origin/main`+`ecbe812f2a04ef8fcc622d6a354ebd8418490c5a`. Four independent native pre-push+reviews accounted for the full 168-file initial diff. Reviews found and resolved:++- Character-to-place conversion now retires its group memberships in the same+ transaction. The regression executed once before the fix and failed on four+ assertions; the four-test record-operation suite and eleven-test roster suite+ passed afterward. It checks notes, rollback and later historical relinking.+- Merged groups load bounded immutable ancestry for later edits, while stale+ bases remain scoped to the surviving Work. Transition revision uses the live+ head's destination. The initial merge/edit regression executed and refused+ rename as `.groupTorn` before the fix. The final six-test suite covers repeated+ merges, rollback, stale bases, divergent heads and foreign-Work physical twins.+ A separately reproduced alias-twin guard regression refused after correction+ without deleting the conflicting row or appending an unprojectable rename.+- Leave review states inclusive final-chapter membership. The caption checkpoint+ ran two tests: leave failed before correction, join remained green. That red+ run's post-test Xcode cleanup stalled and was interrupted only after inspecting+ the owned process/result; it is recorded as cleanup-incomplete, not a green run.+- Empty group proposal buckets no longer keep retired Works tracked. A method+ selector initially executed zero tests and was rejected as failed selection.+ The whole coordinator suite then executed 50 tests, with the new case alone+ failing an unnecessary later candidate read. The corrected checkpoint passed+ all 52 coordinator/caption cases in two suites and completed cleanly.+- Group support reads cache resolution per chapter within the invocation and+ inspect only the addressed member's ranges. Inclusive interval behavior and+ multi-member/chapter support remain covered.++Independent follow-up review cleared each scoped correction. Minor opportunities+for sharing transition/metadata helpers and total ordering of otherwise tied raw+archive variants remain recorded; no loss or round-trip failure was demonstrated.++### Completed gates++- Explicit opt-in `ASTERISM_RUN_GROUP_SCALE=1 make test-core` with selector+ `NamedGroupSaveLinkTests/groupHistoryScaleScopesOneThousandChaptersAwayFromFiveThousandOthers`:+ **1/1 passed**, relinking elapsed **7.729991541 s**, total test **11.069 s**.+ Asserted exactly 1,000 changed chapters, disjoint from 5,000 unrelated chapters,+ batches `[128 × 7, 104]`, eight saves and empty replay. Debug host run, ten logical+ CPUs, load before `{18.12,35.13,37.82}`, after `{12.79,32.23,36.68}`. This is a+ measured fixture result, not a quiet-host performance band or asserted budget.+- Unfiltered serial `make test-core`: **3,621 tests / 351 suites passed** in+ **223.276 s**, no compiler warnings in the run.+- Final unfiltered `make test-quick`: **1,890 passed, zero failed/skipped**, zero+ runtime warnings in the result summary; 1,879 Swift Testing cases / 138 suites+ plus XCTest. Signed Mac app and embedded Mac extension compilation passed.+ Expected isolated failure fixtures logged CoreData errors; the result was green.++Expected UI selection audit: 308 source XCTest declarations, minus eleven+macOS-only methods, leaves 297 iOS methods. The two iPad-only suites contain+30 + 3 methods, so the full phone target expects **264 methods**, and the iPad+target expects **33**. The new rendered witness is+`CharacterGroupsUITests/testLeaveReviewCaptionIncludesItsChapter`.+Two selected methods intentionally require opt-in physical measurement and are+expected to skip on the simulator:+`M4ScaleTodayPerformanceUITests/testTodayPresentationSignpostAtM4ComposedScale`+and `M4ScaleTodayPerformanceUITests/testTodayPresentationSignpostAtM4DuplicateSiteRowsScale`.+Their guard requires `ASTERISM_RUN_PHYSICAL_PERFORMANCE=1` and independently+rejects a simulator. Their two seeded Recent sibling methods must execute.+These source-declared exclusions do not whitelist any baseline failure.++Full unfiltered phone/iPad UI and simulator Personal compile results are recorded+below when complete. No pre-push green verdict is inferred from the focused runs.++### Evidence retention++At the owner's request, superseded recreatable build caches and raw result bundles+are released for disk cleanup after compact results are captured. Historical `/tmp`+paths in this document describe run locations, not a promise of retained files.+Source/specs/commits, compact receipts, and release archives/dSYMs are preserved.+The PR Pilot runner reuses one DerivedData location and one Core scratch directory.++### Connected-root correction and superseded qualification++A subsequent repository-level review found that current-Work/ancestor-only+transition loading omitted new foreign-Work successor IDs sharing an inherited+root. A coherent late source removal was therefore absent from both the surviving+roster and its history digest. The new regression ran seven cases: six passed,+and the late-removal case failed its member-removal and history-rescan assertions.++The V22-compatible correction indexes one global transition fetch per inventory,+selects the connected roots and every physical variant, and reuses that selection+for projection and history. It does not change the installed schema. Multi-Work+support reads share the inventory, and chapter scans remain Work scoped. Review+also required quarantine to follow disputed roots into surviving addresses, and+retirement to distinguish temporary physical conflicts, missing event ancestry,+missing chapter anchors and unresolved semantic claims from coherent removal.+Focused red/green cases cover recovery of the original acceptance after hydration+or repair; final corrected-source totals are recorded separately below.++The earlier 3,621/Core, 1,890/quick and 7.73-second scale results above qualify the+pre-connected-root source (runtime/test fingerprint+`1c9d66d6f68249b377bea14c727a28437227f5b2b04cfff2d6ca562a1a715fac`).+The scale timing is not claimed unchanged after the global metadata lookup.++The full phone run on that superseded binary was stopped gracefully and finalized+as **TEST INTERRUPTED**, not green: 94 methods reported, 92 passed, one actual+largest-text status-dialog failure and one test canceled by interruption. All+seven executed group UI cases passed, including the new inclusive-leave witness.+The actual failure was+`AccessibilityJourneyUITests/testTheStatusControlsAndDialogStayOperableAtLargestDynamicType`;+`ComposedSurfaceUITests/testWorkOnlySelectionRequiresUnsettledAcknowledgment` was+canceled. These partial results do not satisfy the full acceptance gate.++Failure evidence showed the status-option tap at window coordinate `(45,57.67)`+in a 402×874 window, near the navigation bar rather than the status control.+The model's guarded Finished transition remained correct. A focused diagnostic+with post-scroll frame/snapshot inspection passed 1/1; a second lightweight+frame-only run passed 1/1 in 113.17 seconds. Those observations do not alone claim+a production fix. The final journey retains all original dialog/cancel assertions+and strengthens readiness around the actual visible content region.+++### Initial full pre-push gates (9b165ecd)++These results qualify runtime/test/resource fingerprint+`1da45a168a51a2bf2f3b64e37152698cf972f9a7822f57871044cc0f752f8ec3`+(161 files), including the connected-root and reversible-quarantine corrections.++- Unfiltered serial `make test-core`: **3,627 tests / 351 suites**, zero failures+ and no new Swift compiler warnings, 234.080 seconds. Native Swift Testing XML+ expands argument cases to 4,229 rows: 4,173 passed and 56 expected known-issue+ or opt-in skips, with no failures/errors. These are distinct counting levels.+- `make test-quick`: **1,890 passed**, no failures, skips or runtime warnings+ (1,879 Swift Testing tests / 138 suites plus 11 XCTest tests). Its signed Mac+ app and embedded extension compile prerequisite passed; neither was launched.+- `make build-release`: Personal configuration **simulator compile passed** for+ iPhone 18 Pro. This did not install or launch a physical-device application.+- Final status-dialog readiness check passed 1/1 in 113.34 seconds, retaining+ the original dialog, cancellation and state assertions. It follows three+ passing diagnostic/lightweight runs; the change waits for visible content+ coordinates rather than tapping near the navigation bar.++The unfiltered final phone UI run completed successfully in 11,209.711 seconds.+The canonical public xcresult tree contains **all 264 expected unique method IDs**:+**262 passed, 2 skipped, 0 failed**, no missing, extra or duplicate IDs and no+runtime warnings. The device-execution summary is a separate counting level:+265 passed executions plus 2 skips, because the launch method ran four dynamic+variants. JUnit retains the 264 canonical method nodes; the compact public JSON+also retains the dynamic-run evidence.++The only skips are the two predeclared device-only signpost methods listed above.+Both seeded Recent siblings ran and passed. `CharacterExtractionUITests` passed+26/26 and `CharacterGroupsUITests` passed 7/7, including the rendered inclusive+leave caption, reciprocal ranges, outer Save/Cancel/deletion and light/dark+control routes. The repaired largest-text status dialog passed its full-run+repetition, and the previously interrupted composed Work-selection case passed.++The full iPad gate selects 33 methods on the configured iPad Pro 11-inch (M5),+UDID `171C19AD-D129-4015-B106-A1858A281045`. Its first sandboxed command failed on+SwiftPM/Clang cache access and CoreSimulator service access before any test ran+(totalTestCount 0); this is not a UI test pass or failure. The same unfiltered+Makefile target was retried with approved escalation and a fresh result path;+the runner launched and completed the full gate. **33/33 methods passed**, with no+failures, skips or runtime warnings, in 858.526 seconds. The public tree matches+all 33 source-expected IDs, with no missing, extra or duplicate IDs:+`WideLayoutAccessibilityUITests` 3/3 and `WideLayoutUITests` 30/30.++All 161 frozen runtime/test/resource files still match the fingerprint above.+The code checkpoint is `bd910b10`; subsequent qualification updates are+documentation only. Compact native summaries, public test trees, exact-ID audits+and their JUnit transcriptions form the review packet. Tests ran against the+frozen content, including when it was uncommitted; the content check relates+those results to the final commits. These simulator results do not claim a+physical Release update, normal device launch or CloudKit delivery.+++### PR 118 review corrections (48b221f5)++The independent full-diff review of `9b165ecd` accounted for all 175 then-changed+paths and found two major issues: an unavailable leave anchor could create an+open-ended membership, and Remove could omit newer direct alias evidence from a+refreshed legacy receipt. Both were reproduced before correction. The initial+focused run executed 53 tests in two suites and reported four issues.++A bounded independent delta check caught two coupled cases before final bars:+a late, independently rooted leave must preserve an older acceptance/note while+its anchor is unavailable, and a group-only longest match must not suppress a+later genuine direct mention. The revised focused selection passed 54 tests in+two real SwiftData suites. Its late-leave fixture also exercises the existing+explicit note-recovery API and verifies exact authored text on the current link;+no automatic attachment or new recovery interface was introduced. The subsequent+independent delta review was clear.++The revised content is frozen across **162 runtime/test/resource files**, SHA256+`fad7ad240c4407e9f88b5c18a4e7d06d3f4bf5d8523d88812cd413f7210a60a3`,+and committed as `48b221f5`. Five Core production/test files changed; views,+selection controls, UI fixtures, schemes and rendering adapters did not change.+The PR-fix validation follows the commit-phase selection and retains the initial+full phone/iPad outcomes with their `9b165ecd` source qualification; it does not+claim a new unfiltered UI run on this revision.++- Unfiltered serial `make test-core`: **3,630 tests / 351 suites passed**,+ 229.323 seconds, no compiler warning lines. Native XML expands to 4,232 cases:+ 4,176 passed and 56 expected known-issue/opt-in skips, no failures/errors.+- `make test-quick`: **1,890 passed**, no failures, skips or runtime warnings;+ signed Mac app and embedded share-extension compilation passed. The only log+ warnings were four AppIntents metadata-extraction notices, not Swift compiler+ diagnostics. No Mac application was launched.+- Current-binary phone consumers: **8/8 expected IDs passed**, no skips, failures+ or runtime warnings: all seven `CharacterGroupsUITests` and the ordinary+ note-editor Remove/Restore journey from `AssociationNotesUITests`.+- Current-binary iPad consumers: **2/2 expected IDs passed**, no skips, failures+ or runtime warnings: reciprocal member/range display and the same ordinary+ Remove/Restore note-editor route.+- `make build-release`: Personal **simulator** compilation passed on the reused+ build cache. Existing warnings were confined to untouched NoEpisode/model+ client code and AppIntents metadata extraction. No physical install/launch.+- Explicit opt-in scale/scoping check: **1/1 passed**, exactly 1,000 changed+ chapters and 5,000 unrelated chapters excluded, seven 128-row batches plus a+ 104-row batch, eight association saves, then a no-op reconciliation. Measured+ reconciliation was **8.122551458 seconds** (full case 11.547 seconds), an+ observed loaded-host result rather than a quiet-host performance band.++The first focused phone command failed before test execution on sandbox cache+access; its escalated Makefile retry ran the full intended eight-method set.+Both targeted ID audits have no missing, extra or duplicate methods. All 162+frozen files still matched after UI and simulator compilation. The earlier full+UI XML remains source-qualified; the revised review packet's JUnit totals use+the current Core, quick and targeted phone/iPad results.+++### PR 118 second-review corrections (9bd4ca30)++The fresh full-PR review of `dd2f1d38` accounted for 176 paths and confirmed two+major gaps: unattended existing-character extraction bypassed complete-name+arbitration, and a coherent divergent membership root could not be explicitly+resolved. The minor quote-excerpt Skip identity observation remains recorded as+nonblocking; it is not silently described as fixed. Autosave is outside this PR.++Core regressions reproduced the masked `Jake`/`Team Jake` and equal-name cases,+while a separate genuine direct mention remained valid. Final saved-evidence+arbitration now covers the automatic commit boundary with character, place and+group claims. Explicit kind decisions and captured Restore keep their existing+guarded authority. Generic Work notes use an unanchored resolver mode and never+acquire group roster membership through an invented chapter UUID.++Current, compatible divergent heads are exposed separately from the resolved+roster for ordinary editing. The row starts with no chapter/action selection.+Only an explicit complete choice emits a successor over the full observed basis;+stale, incomplete, physically torn, tombstoned and incompatible-address input+remains refused. A peer check reproduced a missing-parent fallback gap (red 1/1,+then green 1/1); the whole merge/edit suite passed 13/13 after the completeness+guard. Untouched conflicts preserve withheld previews even beside a separate+coherent join, and do not force unrelated name/alias edits to resolve them.+Nested Done, outer Cancel and outer Save retain their existing draft transaction.+No provenance panel or automatic conflict winner was added.++The revised frozen content is **166 runtime/test/resource files**, SHA256+`81fc8e6ccf9c0e2374d3a618afb30a12d455e54e324151f8986e5df8bf1119c2`,+committed as `9bd4ca30`. The DEBUG-only synthetic conflict helper and its only+DEBUG scenario caller were independently reviewed; neither is a Personal entry+point. Four localisation keys were added from source, with no removed keys or+changes to retained values. The final bounded peer review was clear.++- Unfiltered serial Core: **3,635 tests / 351 suites passed**, 257.371 seconds,+ no compiler warning lines. Native XML has 4,237 case rows: 4,181 passed and+ 56 expected known-issue/opt-in skips, no failures/errors.+- Unfiltered quick: **1,893 canonical test cases passed**, no failures/skips or+ runtime warnings; 1,882 Swift Testing plus 11 XCTest. Dynamic parameter runs+ produce 2,005 device executions. Signed Mac app and embedded extension compile+ passed; no Mac application was launched.+- Frozen-source phone consumers: **11/11 expected IDs passed** (eight group+ journeys including the new conflict flow, plus automatic recognised linking,+ the following place-row character hint and ordinary note Remove/Restore).+- Frozen-source iPad consumers: **3/3 expected IDs passed** (new conflict flow,+ reciprocal membership/range display and ordinary note Remove/Restore).+- The exact-ID audit has no missing, extra, duplicate, skipped or failed methods.+ Light/dark phone and iPad PNGs were inspected: no default conflict selection,+ selected choices visibly distinct, existing native icons/cyan styling retained,+ and no stale validation error after completing a choice. The focused journey+ checks partial input, outer Cancel/reopen, then explicit outer Save and the+ resolved roster on reopening.+- Personal iOS **simulator** compile passed; no physical install or launch.+ Warning sites are unchanged code (including AppLibraryModel's pre-existing+ unreachable `#else` paths shifted by the DEBUG fixture insertion), not new+ diagnostics in the correction hunks.+- Existing opt-in history scale/scoping: **1/1 passed**, exactly 1,000 changed+ chapters, 5,000 unrelated excluded, seven 128-row batches plus 104, eight saves+ and subsequent no-op. Measured reconciliation **8.114776875 seconds**, full+ case 11.526 seconds; loaded-host observation only, no quiet-host band claim.++The initial iPad command was rejected before process creation because approval+review misclassified a different task's target restriction. Read-only scope+evidence confirmed this repository's authorised simulator targets; one exact+retry was approved and passed. No workaround was used. A first phone capture+revealed a stale inline error; it was corrected before freeze and the refreshed+journey/captures passed. These are separate from the final green source record.++As in the first correction, the full 264-method phone and 33-method iPad results+remain qualified to `9b165ecd`. They are retained unchanged-path evidence, not a+claim of another unfiltered UI run on this revision. Current JUnit, snapshots and+consumer audits identify the revised frozen source explicitly. Final exact-head+PR review and deployment evidence are tracked separately from simulator results.+++### PR 118 third-review corrections++The independent full-PR review of `c6fa34cf` accounted for all 180 paths and+confirmed two major preservation gaps. Equivalent concurrent transition heads+were accepted by projection but discarded by Work/character merge helpers;+inherited group-fact ancestors were omitted from the historical inventory digest.++Real SwiftData regression tests reproduced both before production changes:+23 outer tests in two suites reported 24 issues. The final focused selection+passed **25 outer tests / two suites**, including equivalent and divergent+Work/character merges, ordinary post-move conflict resolution, explicit+character deletion/conversion, late original copies, unresolved-name atomic+merge refusal, coherently deleted-group non-revival, injected save rollback,+and late inherited fact hydration with another group keeping member IDs stable.++A shared causal-head selector now requires complete coherent physical history.+Equivalent heads are rebound by a successor observing every head. Divergent+values retain separate survivor-addressable successors and remain withheld until+an explicit ordinary-editor choice. Removal tombstones complete source roots.+A Work with an unresolved group name or unsafe history refuses atomically before+source deletion; an ordinary previously deleted group does not block a merge.+No automatic winner or additional conflict-management screen was added.+Historical digests use the same physical fact-parent closure as projection,+so missing-parent arrival and conflicting ancestral copies invalidate completion.++Final frozen content: **979 runtime/test/resource files**, SHA256+`5c3227b68b836e9a8576690ae4a66f38872e3cfa34c34ddc480c3888fdd7900b`.+This inventory includes unchanged repository runtime files, unlike the preceding+166-path changed-content inventory. All 979 hashes matched after verification.+The bounded peer review inspected the full delta and new selector and was clear.++- Unfiltered serial Core: **3,643 tests / 351 suites passed**, 231.338 seconds,+ no compiler warning lines. Native XML contains 4,245 case rows: 4,189 passed+ and 56 expected known-issue/opt-in skips, no failures/errors.+- Unfiltered quick: **1,893 canonical cases passed**, zero skipped/failures:+ 1,882 Swift Testing cases / 138 suites plus 11 XCTest. Signed Mac app and+ embedded extension compiled; no Mac app was launched. Reported compiler+ warning sites remain unchanged baseline sites.+- Affected phone consumers: **3/3 exact methods passed**, 387.449 seconds:+ `DuplicateResolutionUITests/testConfirmingAToReadMatchMergesAndShowsTheSurvivor`,+ `CharacterExtractionUITests/testCombinePresentsItsDialogAndKeepsLegacyFactsHidden`,+ and `CharacterGroupsUITests/testConflictedMembershipRequiresExplicitChoiceInLightAndDark`.+ These cover Work merge, character combine and the existing explicit editor.+- Existing opt-in scope check: **1/1 passed**, 1,000 changed chapters and+ 5,000 unrelated excluded; history 7.881483583 seconds, full case 11.255 seconds.+ This is a loaded-host observation, not a new quiet-host performance band.++The full phone/iPad gate remains qualified to `9b165ecd`; prior affected iPad+and broader phone consumers remain qualified to the preceding frozen source.+This Core-only correction changes neither the layouts nor the editor controls.+Current packet JUnit uses the latest Core, quick and three affected phone cases;+retained earlier results are not relabelled as new runs. The preceding Personal+simulator build likewise retains its original source qualification. No physical+install or launch occurred. Fresh exact-head PR review and final merged Personal+build/install remain separate gates. The minor Skip quote-extent observation+remains recorded and nonblocking; autosave remains outside this PR.+++### PR 118 fourth-review alias correction++The independent review of `b1100ccc` accounted for all 181 paths and found one+major gap: a coherent concurrent alias add/remove conflict was excluded from+`summary.aliases`, then silently became an ordinary absent alias during Work+merge. Retained old parents alone did not preserve a destination-addressable+claim. A real SwiftData regression reproduced the incorrect commit before the+fix. The existing atomic refusal now includes unresolved alias spellings, using+the same canonical projection as the source-name check. No new workflow or+automatic conflict winner was added.++The focused Work-merge suite passed **20/20**. The new test proves both Work+snapshots and every raw authored fact remain unchanged on refusal, then uses an+ordinary alias edit against the full basis and proves a successful merge retains+the alias. Existing coherently deleted-group non-revival also passed.++Final frozen inventory: **979 runtime/test/resource files**, SHA256+`3fd589d9ef7cbfef8d2458238083db7cd6e814a53a74a34b6318b1812b625036`.+All hashes remained unchanged after these final checks:++- Unfiltered serial Core: **3,644 tests / 351 suites passed**, 231.409 seconds;+ no compiler warning lines. Native XML: 4,246 case rows, comprising 4,190+ passed and 56 expected known-issue/opt-in skips, no failures/errors.+- Unfiltered quick: **1,893 canonical cases passed**, zero failures/skips;+ signed Mac app and embedded extension compiled. No Mac app was launched.+- Affected phone consumer: **1/1 passed**, 56.269 seconds:+ `DuplicateResolutionUITests/testConfirmingAToReadMatchMergesAndShowsTheSurvivor`.+- Personal **iOS Simulator build only** passed on the reused cache. Warnings+ remain in unchanged NoEpisode/model-client/RuleSuggestion/AppLibraryModel+ sites; no diagnostic was introduced by the correction hunks. No install or+ launch occurred.++The preceding three-consumer phone, broader phone/iPad and scale results retain+their original frozen-source qualifications. Their unchanged behaviours are+retained evidence, not new runs. Full UI remains qualified to `9b165ecd`.+Current packet JUnit uses this final Core/quick and one affected phone result.+The independent exact-head review and rebase review are separate merge gates;+Personal physical installation still requires fresh approval at the actual run+under `AGENTS.md`. No real library was changed during these checks.
Simulator results do not prove CloudKit delivery or real-library behavior. Mac UI automation and extension-hosted UI limits remain in verification-run.md.