Independent general notes for named groups, with both existing editing contracts and additive persistence compatibility.
Multiline General note is separate from names, aliases, membership and chapter-note content. Empty notes add no placeholder; empty rosters retain No members.
Work editing stages notes within its atomic Save/Cancel transaction. Chapter editing uses the recoverable pending-edit journal and guarded autosave.
V24/marker24/archive23-24 retain frozen predecessor models/readers and deterministic authored note election. Note-only writes leave recognition and history inputs unchanged.
Fresh fix gate: native2063, phone1, iPad1 passed; unchanged Core4442/fast192 reused by source closure. Failed full UI results and their focused reruns remain distinct.
PR126 merged under the recorded publication exception
3 recorded full-UI failures remain failed under the owner’s bounded exception. PR126 squash-merged as0ffab2c28a555f9c4fa61916a67c5ada9e8d843c. Tree691f9d111ad3b0c76093641a0416630b73ec2bf3 exactly matches reviewed12e23a72. Both independent review/fixer rounds are clean; latest-main reconciliation was a no-op and no CI checks were configured. TransitT-2516 is done. Phone installation was withdrawn; no physical-phone installation/launch occurred or is scheduled.
e28a520a1dcde52d650cb36f19eeed4cdc15c1b5 T-2516: complete group note editing and display da49571d22099932572d92f9995ec72cc3fa6fad T-2516: record phase 1 sign-off and remaining editor work f7bed7ddf545c8878cdf82b4169dc84c1896f6c9 T-2516: [doc] changelog for phase 1 272263e81f929cf064f80f91ca6f2d709a3c1fff T-2516: Add group-note persistence and safe edits 90dea875c415f51d1f0004240b47b5d723d607c4 T-2516: approve group notes smolspec and implementation plan Groups can have a multiline General note describing what the group is. Work editing saves it with the Work; chapter-note editing preserves it through the existing autosave journal. Read-only cards show saved notes.
Note text and its edit timestamp are independent group identity fields. Deterministic projection selects an authored note from duplicate rows. Guarded repository writes validate the loaded note basis and fan out under the existing transaction lock.
V23 is frozen and V24 adds defaulted columns. App markers16–24 remain accepted, extensions require24. Archive23/24 preserves exact raw note variants and validates predecessor shapes before conversion. Legacy journal staging adopts only the first loaded note basis while retaining historical fact/membership authority; later staging cannot silently refresh that basis.
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupNoteWrites.swift
Why it matters. Reader text must survive clear, duplicate rows and stale edits.
What to look at. guarded note write and fan-out
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV24.swift
Why it matters. Existing libraries and released backups must remain readable.
What to look at. V23 frozen snapshot, V24 stage and archive23/24
Asterism/Asterism/Support/PendingSharedRecordEdit.swift
Why it matters. Recovered typing previously discarded a loaded note basis and repeatedly refused save.
What to look at. keepingBasis(of:)
Asterism/Asterism/Views/GroupNoteText.swift
Why it matters. Saved notes should be readable without changing roster meaning.
What to look at. General note field, Work/NoteCast/share projections
Full phone283:278 pass,2 fail,3 skip. Full iPad34:33 pass,1 fail. Corrected exact accessibility label has a focused pass. Creator reachability failed focused once, then passed on branch/main; wide-layout focused retry passed. Cause of intermittent All works reachability remains unresolved. Owner accepted exactly these existing failures for publication; no result is relabelled green.
Core4442 and fast192 remain unchanged package/tooling inputs at e28a520a; the review fix changes app journal staging only. Fresh full native units, signed Mac compile and affected phone/iPad autosave journeys cover the changed app dependency. Full UI is retained as historical failed acceptance, not rerun just to change its colour.
Reuse: no actionable finding. Quality: legacy note-basis P2 fixed and rechecked. Efficiency: two low-priority duplicate projection/fetch suggestions deferred; no measured regression and no Core change. Spec/docs: canonical schema, count/inventory and current owner-exception wording corrected.
Round1 independent note6753564212 and fresh post-rebase note6753641732 each review exact head12e23a72 and all117 files. Both fixer rounds have no actionable unresolved items. Final SHA/CI rechecked before squash merge; remote feature branch deleted. The user cancelled phone installation before any physical operation.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Legacy journal note authority | First typing restored a legacy empty/epoch note basis over the newly loaded note. | Preserve historical fact basis and adopt loaded note basis only while prior note intent is absent; real repository/session regression and full native gate. |
| minor | Canonical documentation | AGENTS schema guidance and native total/current publication status were stale. | Align V24/marker24/archive23-24 and2062 native baseline; preserve failures and record bounded owner exception. |
| nitpick | Efficiency | Note writer reprojects roster and import fetches group rows twice. | Deferred nonblocking cleanup; no measured regression and tested Core closure preserved. |
Source: local run at 2026-11-09T22:43:12.894473+00:00 · snapshot e28a520a1dcde52d650cb36f19eeed4cdc15c1b5 (dirty working tree)
Baseline: none
Execution: failed · JUnit: 5 files · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 2376 passed · 3 failed · 3 skipped · 0 errored · 0 flaky
| Suite | Test | Job or artifact | Message |
|---|---|---|---|
| AccessibilityJourneyUITests | testTheCreatorControlsStayReachableAtLargestDynamicType() | — | testTheCreatorControlsStayReachableAtLargestDynamicType() |
| ChapterNotesUITests | testNoteCastGroupChoicesAndLinkNoteAutosave() | — | testNoteCastGroupChoicesAndLinkNoteAutosave() |
| WideLayoutAccessibilityUITests | testTheFiveReadingStatusSegmentsAreOperableInBothWideLayouts() | — | testTheFiveReadingStatusSegmentsAreOperableInBothWideLayouts() |
Derived by declaration name, from the diff (no baseline run).
The test run changed these tracked files; they were restored afterwards.
Asterism/Asterism/Localizable.xcstrings — generated output retained outside repository; clean pre-run bytes restoredFiles 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 89d61d46a51cdd8798d9d731886d8eaa7aae8a5e.
117 files: 108 code · 9 docs. Click to expand.
diff --git a/Asterism/Asterism/Support/DevelopmentResetUITestFixture.swift b/Asterism/Asterism/Support/DevelopmentResetUITestFixture.swiftindex ee466e1e..abd659af 100644--- a/Asterism/Asterism/Support/DevelopmentResetUITestFixture.swift+++ b/Asterism/Asterism/Support/DevelopmentResetUITestFixture.swift@@ -21,7 +21,7 @@ enum DevelopmentResetUITestFixture { at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true ) try Data("Synthetic incompatible store".utf8).write(to: configuration.storeURL)- try Data("23".utf8).write(to: configuration.readinessMarkerURL)+ try Data("24".utf8).write(to: configuration.readinessMarkerURL) } let token = "me.nore.ig.apps.Asterism.dev" let identity = DevelopmentResetIdentity(
diff --git a/Asterism/Asterism/Support/PendingSharedRecordEdit.swift b/Asterism/Asterism/Support/PendingSharedRecordEdit.swiftindex e4859101..ea5e55a2 100644--- a/Asterism/Asterism/Support/PendingSharedRecordEdit.swift+++ b/Asterism/Asterism/Support/PendingSharedRecordEdit.swift@@ -15,7 +15,7 @@ enum PendingSharedRecordEdit: Codable, Equatable, Sendable { var copyableText: String { switch self { case .record(_, _, let draft): ([draft.name] + draft.aliases + [draft.note]).joined(separator: "\n")- case .group(let draft): [draft.name, draft.aliases].joined(separator: "\n")+ case .group(let draft): ([draft.name, draft.aliases] + [draft.note].compactMap { $0 }).joined(separator: "\n") } } func keepingBasis(of previous: Self) -> Self {@@ -24,7 +24,18 @@ enum PendingSharedRecordEdit: Codable, Equatable, Sendable { return .record(workID: workID, basis: basis, draft: draft) case (.group(var draft), .group(let previous)): draft = draft.keepingReplacementRoots(of: previous)+ let loaded = draft.original draft.original = previous.original+ // A legacy journal never edited notes. Keep its historical fact+ // basis, while retaining the note basis loaded by the editor.+ if previous.note == nil, let loaded, let basis = previous.original {+ draft.original = GroupSummary(groupID: basis.groupID, name: basis.name,+ note: loaded.note, noteModifiedAt: loaded.noteModifiedAt,+ aliases: basis.aliases, members: basis.members,+ factEventIDs: basis.factEventIDs, transitions: basis.transitions,+ conflictedTransitions: basis.conflictedTransitions,+ transitionEventIDs: basis.transitionEventIDs)+ } return .group(draft) default: return self }@@ -81,7 +92,8 @@ extension CharacterGroupDraft { choice.replacementRootID != nil || pendingRoots.contains(rootID) || summary.conflictedTransitions.contains { $0.rootID == rootID } }- result.original = GroupSummary(groupID: summary.groupID, name: summary.name, aliases: summary.aliases,+ result.original = GroupSummary(groupID: summary.groupID, name: summary.name,+ note: summary.note, noteModifiedAt: summary.noteModifiedAt, aliases: summary.aliases, members: summary.members, factEventIDs: summary.factEventIDs, transitions: summary.transitions.filter { !pendingTransitionRoots.contains($0.rootID) }, conflictedTransitions: summary.conflictedTransitions + pendingConflicts,@@ -102,6 +114,7 @@ extension CharacterGroupDraft { } return name.trimmingCharacters(in: .whitespacesAndNewlines) == summary.name && desiredAliases == Set(summary.aliases)+ && (note == nil || note == summary.note) && previewTransitions.sorted { $0.rootID.uuidString < $1.rootID.uuidString } == actual.previewTransitions.sorted { $0.rootID.uuidString < $1.rootID.uuidString } && unresolved.sorted { $0.rootID.uuidString < $1.rootID.uuidString }
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex 007c44c1..3785ed25 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -352,8 +352,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 BackupV22SnapshotProviding).- private var backupRepository: (any BackupV22SnapshotProviding)?+ /// Retains the concrete repository for backup export (conforms to BackupV23SnapshotProviding).+ private var backupRepository: (any BackupV23SnapshotProviding)? /// 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.@@ -2819,11 +2819,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() -> BackupV22Exporter? {+ private func backupExporter() -> BackupV23Exporter? { guard let repo = backupRepository, let config = resolvedConfiguration else { return nil } let stagingDir = config.rootDirectory .appending(path: "Library/Caches/BackupExports")- return BackupV22Exporter(repository: repo, stagingDirectory: stagingDir)+ return BackupV23Exporter(repository: repo, stagingDirectory: stagingDir) } /// The per-entry markdown export model (Req 1.5), staged beside the backup
diff --git a/Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swift b/Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swiftindex d41f5fc2..0d987170 100644--- a/Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swift+++ b/Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swift@@ -7,6 +7,8 @@ struct CharacterGroupDraft: Codable, Sendable, Equatable { let groupID: UUID var original: GroupSummary? var name: String+ /// Optional for legacy journals: nil means the old draft never edited a note.+ var note: String? var aliases: String var transitions: [GroupTransitionFact] var conflictResolutions: [UUID: GroupTransitionResolution]@@ -56,6 +58,10 @@ struct CharacterGroupDraft: Codable, Sendable, Equatable { operation: operation) } if trimmed != original.name { result.append(fact(.setName(trimmed))) }+ if let note, note != original.note {+ result.append(.note(groupID: groupID, expectedNote: original.note,+ expectedModifiedAt: original.noteModifiedAt, value: note))+ } for alias in Set(original.aliases).subtracting(aliasValues).sorted() { result.append(fact(.removeAlias(alias))) }@@ -90,6 +96,10 @@ struct CharacterGroupDraft: Codable, Sendable, Equatable { } } else { result.append(.create(groupID: groupID, name: trimmed))+ if let note, !note.isEmpty {+ result.append(.note(groupID: groupID, expectedNote: "",+ expectedModifiedAt: Date(timeIntervalSince1970: 0), value: note))+ } for alias in aliasValues.sorted() { result.append(.fact(groupID: groupID, expectedEventIDs: [], operation: .addAlias(alias)))@@ -124,6 +134,7 @@ final class CharacterGroupEditorModel: Identifiable { let groupID: UUID let workID: UUID var name: String { didSet { onEdit?(draft) } }+ var note: String { didSet { onEdit?(draft) } } var aliases: String { didSet { onEdit?(draft) } } var transitions: [GroupTransitionFact] { didSet { onEdit?(draft) } } var conflictResolutions: [UUID: GroupTransitionResolution] { didSet { onEdit?(draft) } }@@ -133,7 +144,7 @@ final class CharacterGroupEditorModel: Identifiable { private let onStage: @MainActor (CharacterGroupDraft) -> Void var onEdit: (@MainActor (CharacterGroupDraft) -> Void)? var draft: CharacterGroupDraft {- .init(workID: workID, groupID: groupID, original: original, name: name, aliases: aliases,+ .init(workID: workID, groupID: groupID, original: original, name: name, note: note, aliases: aliases, transitions: transitions, conflictResolutions: conflictResolutions, isDeleted: false) } func acknowledge(_ value: CharacterGroupDraft) {@@ -151,9 +162,22 @@ final class CharacterGroupEditorModel: Identifiable { 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 }+ if let draft {+ original = draft.original+ // A legacy draft has no note field. Adopt the loaded current note+ // basis without changing the draft's historical name/event basis.+ if draft.note == nil, let group, let basis = draft.original {+ original = GroupSummary(groupID: basis.groupID, name: basis.name,+ note: group.note, noteModifiedAt: group.noteModifiedAt,+ aliases: basis.aliases, members: basis.members,+ factEventIDs: basis.factEventIDs, transitions: basis.transitions,+ conflictedTransitions: basis.conflictedTransitions,+ transitionEventIDs: basis.transitionEventIDs)+ }+ } else { original = group } groupID = draft?.groupID ?? group?.groupID ?? UUID() name = draft?.name ?? group?.name ?? ""+ note = draft?.note ?? group?.note ?? draft?.original?.note ?? "" aliases = draft?.aliases ?? group?.aliases.joined(separator: "\n") ?? "" transitions = draft?.transitions ?? group?.transitions ?? [] conflictResolutions = draft?.conflictResolutions ?? [:]@@ -231,7 +255,7 @@ final class CharacterGroupEditorModel: Identifiable { isSaving = true defer { isSaving = false } onStage(CharacterGroupDraft(workID: workID, groupID: groupID,- original: original, name: trimmed, aliases: aliases,+ original: original, name: trimmed, note: note, aliases: aliases, transitions: transitions, conflictResolutions: conflictResolutions, isDeleted: deleting)) return true
diff --git a/Asterism/Asterism/ViewModels/NoteCastModel.swift b/Asterism/Asterism/ViewModels/NoteCastModel.swiftindex fc5f2830..a59cf995 100644--- a/Asterism/Asterism/ViewModels/NoteCastModel.swift+++ b/Asterism/Asterism/ViewModels/NoteCastModel.swift@@ -160,9 +160,12 @@ final class NoteCastModel { .init(id: .init(kind: record.kind == .character ? .characters : .places, id: record.id), name: record.name, aliases: record.aliases, note: record.note) }- let items = detail.characters.map(item) + groups.compactMap { group in- group.name.map { .init(id: .init(kind: .groups, id: group.groupID), name: $0, aliases: group.aliases, note: "") }- } + detail.places.map(item)+ let groupItems = groups.compactMap { group -> NoteCastItem? in+ guard let name = group.name else { return nil }+ return .init(id: .init(kind: .groups, id: group.groupID), name: name,+ aliases: group.aliases, note: group.note)+ }+ let items = detail.characters.map(item) + groupItems + detail.places.map(item) return Catalog(items: items, members: Dictionary(uniqueKeysWithValues: groups.map { group in (group.groupID, group.members.filter { $0.value.contains { $0.endChapterID == nil } }.map(\.key)) }))
diff --git a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift b/Asterism/Asterism/ViewModels/SettingsBackupModel.swiftindex e9e01486..c79e7a52 100644--- a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift+++ b/Asterism/Asterism/ViewModels/SettingsBackupModel.swift@@ -5,13 +5,10 @@ import OSLog // MARK: - Backup Exporting Protocol /// Test seam abstracting the exporter's operations needed by the Settings-/// surface. Conforms `BackupV22Exporter` to this protocol via extension below.+/// surface. Conforms `BackupV23Exporter` 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-/// memberships, the reader's dismissed pairs, citations that name a rule by UUID-/// alone, and the Work's two statuses and verdict. It is also the only format-/// the app reads, so there is one exporter and one importer.+/// Settings exports 23/24 with group-note variants while retaining the bounded+/// released predecessor readers. Historical payload records remain frozen. public protocol BackupExporting: Sendable { func export(metadata: BackupV18Metadata) async throws -> BackupExportResult func cleanup(_ result: BackupExportResult)@@ -19,7 +16,7 @@ public protocol BackupExporting: Sendable { } extension BackupV19Exporter: BackupExporting {}-extension BackupV22Exporter: BackupExporting {}+extension BackupV23Exporter: BackupExporting {} // MARK: - Export Stage
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel+GroupNoteProjection.swift b/Asterism/Asterism/ViewModels/WorkDetailModel+GroupNoteProjection.swiftnew file mode 100644index 00000000..e17e5a68--- /dev/null+++ b/Asterism/Asterism/ViewModels/WorkDetailModel+GroupNoteProjection.swift@@ -0,0 +1,12 @@+import AsterismCore+import Foundation++extension WorkDetailModel {+ static func stagedGroupNote(_ draft: CharacterGroupDraft, original: GroupSummary?) -> String {+ draft.note ?? original?.note ?? ""+ }++ static func stagedGroupNoteModifiedAt(_ original: GroupSummary?) -> Date {+ original?.noteModifiedAt ?? Date(timeIntervalSince1970: 0)+ }+}
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel.swift b/Asterism/Asterism/ViewModels/WorkDetailModel.swiftindex 4f4bb22a..0689acd0 100644--- a/Asterism/Asterism/ViewModels/WorkDetailModel.swift+++ b/Asterism/Asterism/ViewModels/WorkDetailModel.swift@@ -32,10 +32,10 @@ public final class WorkDetailModel { 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,+ name: draft.name.trimmingCharacters(in: .whitespacesAndNewlines), note: Self.stagedGroupNote(draft, original: original),+ noteModifiedAt: Self.stagedGroupNoteModifiedAt(original),+ aliases: Self.groupAliasValues(draft.aliases), members: original?.members ?? [:],+ factEventIDs: original?.factEventIDs ?? [], transitions: draft.previewTransitions, conflictedTransitions: (original?.conflictedTransitions ?? []).filter { draft.conflictResolutions[$0.rootID] == nil },@@ -65,8 +65,8 @@ public final class WorkDetailModel { 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+ return GroupSummary(groupID: source.groupID, name: source.name, note: source.note,+ noteModifiedAt: source.noteModifiedAt, aliases: source.aliases, members: projection.members.filter { characterID, _ in !source.conflictedTransitions.contains { $0.characterID == characterID } }, factEventIDs: source.factEventIDs, transitions: source.transitions,
diff --git a/Asterism/Asterism/Views/CharacterGroupEditorView.swift b/Asterism/Asterism/Views/CharacterGroupEditorView.swiftindex 08a31e4b..1b05506e 100644--- a/Asterism/Asterism/Views/CharacterGroupEditorView.swift+++ b/Asterism/Asterism/Views/CharacterGroupEditorView.swift@@ -23,6 +23,11 @@ struct CharacterGroupEditorView: View { TextField("Aliases (one per line)", text: $model.aliases, axis: .vertical) .lineLimit(1...4) .accessibilityIdentifier("group-editor.aliases")+ TextField("General note", text: $model.note, axis: .vertical)+ .lineLimit(2...8)+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityLabel("General note")+ .accessibilityIdentifier("group-editor.note") } .disabled(noteSession?.editable == false || noteSession?.isPerformingStructural == true) Section("Membership history") {
diff --git a/Asterism/Asterism/Views/GroupNoteText.swift b/Asterism/Asterism/Views/GroupNoteText.swiftnew file mode 100644index 00000000..a6222dd9--- /dev/null+++ b/Asterism/Asterism/Views/GroupNoteText.swift@@ -0,0 +1,18 @@+import ConstellationKit+import SwiftUI++struct GroupNoteText: View {+ let note: String+ let groupID: UUID++ var body: some View {+ Text(note)+ .font(.subheadline)+ .foregroundStyle(AsterismColors.noteText)+ .lineSpacing(4)+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: .infinity, alignment: .leading)+ .accessibilityLabel("General note: \(note)")+ .accessibilityIdentifier("work-detail.group-note.\(groupID)")+ }+}
diff --git a/Asterism/Asterism/Views/NoteCastView.swift b/Asterism/Asterism/Views/NoteCastView.swiftindex 60ce53a0..32b87df8 100644--- a/Asterism/Asterism/Views/NoteCastView.swift+++ b/Asterism/Asterism/Views/NoteCastView.swift@@ -111,7 +111,15 @@ private struct NoteCastSection: View { VStack(alignment: .leading, spacing: 12) { Text(item.name).font(AsterismTypography.serifHeading) if !item.aliases.isEmpty { Text(item.aliases.joined(separator: " · ")).font(.subheadline).foregroundStyle(.secondary) }- if !item.note.isEmpty { Text(item.note).font(.subheadline).foregroundStyle(AsterismColors.noteText) }+ if !item.note.isEmpty {+ Text(item.note)+ .font(.subheadline)+ .foregroundStyle(AsterismColors.noteText)+ .lineSpacing(4)+ .fixedSize(horizontal: false, vertical: true)+ .accessibilityLabel("General note: \(item.note)")+ .accessibilityIdentifier("note-cast.general-note.\(item.id.id)")+ } if item.id.kind == .groups { Text(model.groupMembers.isEmpty ? "No current members" : model.groupMembers.joined(separator: ", ")) .font(.subheadline)
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex 01594528..d7ef62e3 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -2375,6 +2375,7 @@ struct WorkDetailView: View { } } .frame(maxWidth: .infinity, alignment: .leading)+ if !group.note.isEmpty { GroupNoteText(note: group.note, groupID: group.groupID) } if members.isEmpty { Text("No members").foregroundStyle(AsterismColors.secondaryText) } else {@@ -2387,8 +2388,7 @@ struct WorkDetailView: View { } } }- .padding(12)- .constellationCard()+ .padding(12).constellationCard() .constellationListRow() }
diff --git a/Asterism/AsterismTests/CharacterGroupEditorTests.swift b/Asterism/AsterismTests/CharacterGroupEditorTests.swiftindex 085a1414..d158370a 100644--- a/Asterism/AsterismTests/CharacterGroupEditorTests.swift+++ b/Asterism/AsterismTests/CharacterGroupEditorTests.swift@@ -63,6 +63,75 @@ import Testing expectedEventIDs: group.factEventIDs, operation: .removeAlias("The Team")))) } + @Test func editingOnlyANoteProducesOnlyAGuardedNoteOperation() async throws {+ let basisTime = Date(timeIntervalSince1970: 100)+ let group = GroupSummary(groupID: UUID(), name: "Team Jake", note: "old",+ noteModifiedAt: basisTime, aliases: ["The Team"], factEventIDs: [UUID()])+ var staged: CharacterGroupDraft?+ let model = CharacterGroupEditorModel(workID: UUID(), group: group) { staged = $0 }+ model.note = " 雪\nsecond line "+ #expect(await model.save())+ let operations = try #require(staged).operations+ #expect(operations == [.note(groupID: group.groupID, expectedNote: "old",+ expectedModifiedAt: basisTime, value: " 雪\nsecond line ")])+ }++ @Test func legacyDraftWithoutNoteDoesNotRequestAClear() throws {+ let workID = UUID()+ let summary = GroupSummary(groupID: UUID(), name: "Team Jake", aliases: [],+ members: [:], factEventIDs: [UUID()], transitions: [],+ conflictedTransitions: [], transitionEventIDs: [:])+ var value = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(+ CharacterGroupDraft(workID: workID, groupID: summary.groupID, original: summary,+ name: "Team Jake", note: nil, aliases: "", transitions: [],+ conflictResolutions: [:], isDeleted: false))) as? [String: Any])+ value.removeValue(forKey: "note")+ if var original = value["original"] as? [String: Any] {+ original.removeValue(forKey: "note")+ original.removeValue(forKey: "noteModifiedAt")+ value["original"] = original+ }+ let decoded = try JSONDecoder().decode(CharacterGroupDraft.self,+ from: JSONSerialization.data(withJSONObject: value))+ #expect(decoded.note == nil)+ #expect(decoded.original?.note == "")+ #expect(decoded.original?.noteModifiedAt == Date(timeIntervalSince1970: 0))+ #expect(decoded.operations.isEmpty)++ let current = GroupSummary(groupID: summary.groupID, name: "Team Jake",+ note: "Saved after this old draft was written",+ noteModifiedAt: Date(timeIntervalSince1970: 2_500), factEventIDs: summary.factEventIDs)+ let editor = CharacterGroupEditorModel(workID: workID, group: current, draft: decoded) { _ in }+ #expect(editor.note == current.note,+ "A legacy journal with no note field displays the loaded authored note")+ #expect(editor.draft.original?.note == current.note)+ #expect(editor.draft.original?.noteModifiedAt == current.noteModifiedAt)+ #expect(editor.draft.operations.isEmpty,+ "Loading an old draft does not convert its missing note into a clear")+ }++ @Test func noteSurvivesNestedWorkDraftAndIndependentCancel() async throws {+ let workID = UUID()+ var staged: CharacterGroupDraft?+ let initial = CharacterGroupEditorModel(workID: workID) { staged = $0 }+ initial.name = "The Night Crew"+ initial.note = "Initial note\nsecond line"+ #expect(await initial.save())+ let initialDraft = try #require(staged)+ #expect(initialDraft.note == "Initial note\nsecond line")+ #expect(initialDraft.operations.contains(.note(groupID: initial.groupID,+ expectedNote: "", expectedModifiedAt: Date(timeIntervalSince1970: 0),+ value: "Initial note\nsecond line")))++ let nested = CharacterGroupEditorModel(workID: workID, draft: initialDraft) { staged = $0 }+ #expect(nested.note == initialDraft.note, "Reopening a staged group retains the note draft")+ nested.note = "Nested note that is cancelled"+ #expect(staged?.note == initialDraft.note,+ "Editing the nested sheet does not publish before Done")+ #expect(initialDraft.note == "Initial note\nsecond line",+ "Cancelling the nested sheet leaves the enclosing Work draft intact")+ }+ @Test func deletingExistingGroupStagesTombstoneOnly() async { let group = GroupSummary(groupID: UUID(), name: "Team Jake", factEventIDs: [UUID()]) var staged: CharacterGroupDraft?
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex 699a1e8f..19d6eeec 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 = BackupV22Exporter(repository: repository, stagingDirectory: stagingDirectory)+ let exporter = BackupV23Exporter(repository: repository, stagingDirectory: stagingDirectory) let exportedAt = Date(timeIntervalSince1970: 1_784_246_400) let result = try await exporter.export(- metadata: BackupV21Metadata(+ metadata: BackupV23Metadata( 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 BackupV22Codec.decode(encoded)- let source = try await repository.backupV22Snapshot()+ let decoded = try BackupV23Codec.decode(encoded)+ let source = try await repository.backupV23Snapshot() #expect(decoded.payload == source) #expect(decoded.payload.library.entries.count == 1)@@ -247,7 +247,7 @@ struct IntegrationSafetyNetTests { // 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 BackupV22Codec.decode(Data(contentsOf: backupURL))+ let document = try BackupV23Codec.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 = BackupV22Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+ let exporter = BackupV23Exporter(repository: sourceRepo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV21Metadata(appBuild: "fill-test", exportedAt: Date())+ metadata: BackupV23Metadata(appBuild: "fill-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } let backupData = try Data(contentsOf: exportResult.fileURL)
diff --git a/Asterism/AsterismTests/NoteRecordEditingSessionTests.swift b/Asterism/AsterismTests/NoteRecordEditingSessionTests.swiftindex 5239ddd7..5ba305da 100644--- a/Asterism/AsterismTests/NoteRecordEditingSessionTests.swift+++ b/Asterism/AsterismTests/NoteRecordEditingSessionTests.swift@@ -8,7 +8,7 @@ import Testing /// the Work editor's staged Save/Cancel draft. @Suite("Note record editing session", .serialized) @MainActor struct NoteRecordEditingSessionTests {- private func fixture(root: URL) async throws -> (LibraryRepository, EntrySnapshot, WorkRecordPresentation) {+ func fixture(root: URL) async throws -> (LibraryRepository, EntrySnapshot, WorkRecordPresentation) { let configuration = LibraryConfiguration(rootDirectory: root) try FileManager.default.createDirectory(at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true)@@ -258,6 +258,87 @@ import Testing #expect(saved?.transitions.contains { $0.chapterID == entry.id && $0.action == .join } == true) } + @Test("A group note survives a lost save acknowledgement, restart and retry")+ func groupNoteLostAcknowledgementRecoversAndRemainsEditable() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let (library, entry, _) = try await fixture(root: root)+ let workID = try #require(entry.workID), groupID = UUID()+ guard case .committed = try await library.commitGroupEdits(workID: workID,+ operations: [.create(groupID: groupID, name: "Recovery group")], currentChapterID: entry.id) else {+ Issue.record("The note recovery group must be created")+ return+ }+ let item = NoteCastItem(id: .init(kind: .groups, id: groupID), name: "Recovery group",+ aliases: [], note: "")+ let store = PendingNoteEditStore(rootDirectory: root)+ let submitted = " Keep this note.\nSecond line. "+ let failedRunner = PendingNoteEditRunner(store: store,+ commit: { .committed($0.basis) },+ commitSharedRecord: { request in+ _ = try await NoteSharedRecordWriter.commit(request, library: library)+ throw CocoaError(.fileWriteUnknown)+ })+ let first = NoteRecordEditingSession(entry: entry, item: item, library: library, runner: failedRunner)+ await first.load()+ let firstEditor = try #require(first.groupEditor)+ firstEditor.note = submitted+ #expect(!(await first.flush()), "The repository commit loses its acknowledgement")+ #expect(first.failure != nil)+ #expect(failedRunner.latest(entryID: groupID)?.copyableText.hasSuffix(submitted) == true,+ "The exact multiline note remains copyable from recovery")+ #expect(try await library.characterGroups(workID: workID)+ .first { $0.groupID == groupID }?.note == submitted)++ let recoveredRunner = PendingNoteEditRunner(store: store,+ commit: { .committed($0.basis) },+ commitSharedRecord: { try await NoteSharedRecordWriter.commit($0, library: library) })+ let recovered = NoteRecordEditingSession(entry: entry, item: item, library: library, runner: recoveredRunner)+ await recovered.load()+ let recoveredEditor = try #require(recovered.groupEditor)+ #expect(recoveredEditor.note == submitted, "Restart restores the exact note draft")+ #expect(await recovered.flush(retry: true), "Retry recognizes the saved full content")+ recoveredEditor.note = "Edited again after restart"+ #expect(await recovered.flush(), "The acknowledged note basis supports a later edit")+ #expect(try await library.characterGroups(workID: workID)+ .first { $0.groupID == groupID }?.note == "Edited again after restart")+ }++ @Test("A stale group-note draft remains available for review")+ func staleGroupNoteDraftIsKeptAfterRefusal() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: root) }+ let (library, entry, _) = try await fixture(root: root)+ let workID = try #require(entry.workID), groupID = UUID()+ guard case .committed = try await library.commitGroupEdits(workID: workID,+ operations: [.create(groupID: groupID, name: "Stale group note")], currentChapterID: entry.id) else {+ Issue.record("The stale-note group must be created")+ return+ }+ let item = NoteCastItem(id: .init(kind: .groups, id: groupID), name: "Stale group note",+ aliases: [], note: "")+ let runner = PendingNoteEditRunner(store: .init(rootDirectory: root),+ commit: { .committed($0.basis) },+ commitSharedRecord: { try await NoteSharedRecordWriter.commit($0, library: library) })+ let session = NoteRecordEditingSession(entry: entry, item: item, library: library, runner: runner)+ await session.load()+ let editor = try #require(session.groupEditor)+ let basis = try #require(editor.draft.original)+ editor.note = "My stale draft"+ #expect(try await library.commitGroupEdits(workID: workID, operations: [+ .note(groupID: groupID, expectedNote: basis.note,+ expectedModifiedAt: basis.noteModifiedAt, value: "Remote winner")+ ]) == .committed(groupIDs: []))+ #expect(!(await session.flush()), "The stale note basis is refused")+ #expect(editor.note == "My stale draft")+ #expect(session.failure != nil)+ #expect(runner.latestSharedRecord(targetID: groupID)?.copyableText.contains("My stale draft") == true)+ #expect(try await library.characterGroups(workID: workID)+ .first { $0.groupID == groupID }?.note == "Remote winner")+ }+ @Test func recoveredGroupEditCanBeEditedAndDeletedAgain() async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)@@ -459,15 +540,19 @@ import Testing let session = NoteRecordEditingSession(entry: entry, item: item, library: library, runner: runner) await session.load() let editor = try #require(session.groupEditor)+ editor.note = "First note held behind the save gate" editor.remove(try #require(editor.transitions.first { $0.rootID == transitionID })) await entered.wait() editor.name = "Typed while removal saves"+ editor.note = "Typed while note saves" release.open()- #expect(await session.flush(), "The removal and its newer queued edit both acknowledge")+ #expect(await session.flush(), "The removal and newer note/name draft both acknowledge") let saved = try #require(try await library.characterGroups(workID: workID) .first { $0.groupID == groupID }) #expect(saved.name == "Typed while removal saves")+ #expect(saved.note == "Typed while note saves",+ "Further note typing survives an acknowledgement for an earlier note") #expect(!saved.transitions.contains { $0.rootID == transitionID }, "The successor edit does not reinsert the acknowledged removal") }
diff --git a/Asterism/AsterismTests/PendingNoteEditTests.swift b/Asterism/AsterismTests/PendingNoteEditTests.swiftindex 5e002eaf..8834e526 100644--- a/Asterism/AsterismTests/PendingNoteEditTests.swift+++ b/Asterism/AsterismTests/PendingNoteEditTests.swift@@ -309,6 +309,22 @@ import Testing #expect(restored.map(\.revision) == [1, 2, 3]) #expect(restored[1].selection == selection) }++ @Test("A pending group-note draft remains available as exact copyable recovery text")+ func groupNoteRecoveryTextRetainsWhitespaceAndLineBreaks() throws {+ let basis = TestFixtures.makeEntry()+ let workID = UUID(), groupID = UUID()+ let original = GroupSummary(groupID: groupID, name: "The Watch",+ note: "Old note", noteModifiedAt: Date(timeIntervalSince1970: 1_000))+ let note = " Keep the lamp.\n\nDo not lose this text. "+ let draft = CharacterGroupDraft(workID: workID, groupID: groupID, original: original,+ name: "The Watch", note: note, aliases: "", transitions: [],+ conflictResolutions: [:], isDeleted: false)+ let edit = PendingNoteEdit(request: .init(basis: basis, note: "", rating: nil),+ revision: 1, selection: .sharedRecord(.group(draft)), targetID: groupID)+ #expect(edit.copyableText.hasSuffix(note))+ #expect(edit.copyableText.contains(note))+ } } @MainActor private final class CommitGate {
diff --git a/Asterism/AsterismUITests/ChapterNotesUITests.swift b/Asterism/AsterismUITests/ChapterNotesUITests.swiftindex e5ded0d3..8ce7b1bf 100644--- a/Asterism/AsterismUITests/ChapterNotesUITests.swift+++ b/Asterism/AsterismUITests/ChapterNotesUITests.swift@@ -285,7 +285,8 @@ final class ChapterNotesUITests: XCTestCase { tapNoteControl(place, "A known place can be selected without its name in the text") XCTAssertEqual(place.value as? String, "Linked") XCTAssertTrue(app.anyElement("note-cast.places.card").exists)- XCTAssertTrue(app.staticTexts["A quiet port"].exists)+ XCTAssertTrue(app.staticTexts.matching(NSPredicate(+ format: "label CONTAINS %@", "A quiet port")).firstMatch.exists) tapNoteControl(app.buttons["note-cast-copy"], "Place Copy uses the current name") let cardScreen = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) cardScreen.name = "Place card after group choices"; cardScreen.lifetime = .keepAlways; add(cardScreen)@@ -298,6 +299,50 @@ final class ChapterNotesUITests: XCTestCase { "The entry's Note/Details form remains open after record Details closes") } + func testNoteCastGroupNoteAutosavesAndAppearsInReadOnlyCard() {+ openWork(); revealManualCastSpine()+ waitFor(app.buttons.matching(identifier: "work-detail-entry").firstMatch,+ "Existing chapter").tap()+ let group = app.buttons["note-cast.groups.chip.0"]+ tapNoteControl(group, "The named group is available")+ let card = waitFor(app.anyElement("note-cast.groups.card"),+ "The read-only group card opens")+ XCTAssertFalse(app.descendants(matching: .any).matching(NSPredicate(+ format: "identifier BEGINSWITH %@", "note-cast.general-note.")).firstMatch.exists,+ "An empty note adds no placeholder")+ tapNoteControl(app.buttons["note-cast-details"], "Group Details opens")+ let details = waitFor(app.anyElement("note-record-editor"), "The group editor opens")+ let note = waitFor(app.textFields["group-editor.note"], "The General note field is editable")+ XCTAssertEqual(note.label, "General note")+ note.tap()+ note.typeText("A quiet harbor.\nKeep the lantern lit.")+ waitFor(app.buttons["note-record-close"], "Close saves the shared group note").tap()+ waitUntilGone(details, "Closing group Details returns to the chapter")+ XCTAssertFalse(app.keyboards.firstMatch.exists, "Close dismisses the multiline editor keyboard")+ let renderedNote = app.descendants(matching: .any).matching(NSPredicate(+ format: "identifier BEGINSWITH %@", "note-cast.general-note.")).firstMatch+ waitFor(renderedNote, "The saved note appears in the read-only card")+ XCTAssertTrue(renderedNote.label.contains("General note: A quiet harbor."))+ XCTAssertTrue(renderedNote.label.contains("Keep the lantern lit."))+ XCTAssertTrue(card.exists, "The group card remains open after refresh")+ tapNoteControl(app.buttons["note-cast-details"], "Group Details can reopen")+ let reopened = waitFor(app.textFields["group-editor.note"],+ "The saved multiline note is restored")+ XCTAssertTrue((reopened.value as? String ?? "").contains("Keep the lantern lit."))+ reopened.tap()+ reopened.coordinate(withNormalizedOffset: CGVector(dx: 0.98, dy: 0.9)).tap()+ let remaining = reopened.value as? String ?? ""+ reopened.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: remaining.count + 2))+ XCTAssertEqual(reopened.value as? String, "", "The editor accepts an authored clear")+ waitFor(app.buttons["note-record-close"], "Reopened Details closes").tap()+ XCTAssertTrue(renderedNote.waitForNonExistence(timeout: 10),+ "Clearing the note removes it from the card without a placeholder")+ tapNoteControl(app.buttons["note-cast-details"], "A cleared note can be reviewed")+ let cleared = waitFor(app.textFields["group-editor.note"], "The authored clear persists")+ XCTAssertEqual(cleared.value as? String, "")+ waitFor(app.buttons["note-record-close"], "Details closes after the clear").tap()+ }+ func testManualCharacterChipsStayHiddenOnOrdinaryNote() { openWork(); revealManualCastSpine() waitFor(app.buttons.matching(identifier: "work-detail-entry").firstMatch, "Ordinary note").tap()
diff --git a/Asterism/AsterismUITests/CharacterGroupsUITests.swift b/Asterism/AsterismUITests/CharacterGroupsUITests.swiftindex 88729d80..d05bc60b 100644--- a/Asterism/AsterismUITests/CharacterGroupsUITests.swift+++ b/Asterism/AsterismUITests/CharacterGroupsUITests.swift@@ -50,6 +50,9 @@ final class CharacterGroupsUITests: XCTestCase { XCTAssertFalse(app.buttons["Delete group"].exists, "An unsaved draft has no delete action") name.typeText("Discarded group")+ let cancelledNestedNote = app.textFields["group-editor.note"]+ cancelledNestedNote.tap()+ cancelledNestedNote.typeText("Discarded with the nested editor") app.buttons["group-editor.cancel"].tap() waitFor(addGroup, "Cancel returns to Work detail") XCTAssertFalse(app.staticTexts["Discarded group"].exists,@@ -58,6 +61,9 @@ final class CharacterGroupsUITests: XCTestCase { addGroup.tap() waitFor(name, "The group editor can reopen").tap() name.typeText("Cancelled Work edit group")+ let cancelledWorkNote = app.textFields["group-editor.note"]+ cancelledWorkNote.tap()+ cancelledWorkNote.typeText("Discarded with the enclosing Work edit") app.buttons["group-editor.save"].tap() waitFor(addGroup, "Done returns to the enclosing Work edit") let stagedGroupLine = app.descendants(matching: .any)@@ -73,6 +79,15 @@ final class CharacterGroupsUITests: XCTestCase { 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")+ let generalNote = waitFor(app.textFields["group-editor.note"],+ "A new group can receive its general note")+ XCTAssertEqual(generalNote.label, "General note")+ let authoredGroupNote = " Keeps the archive through winter. The crew records every lantern, repairs the old chart, "+ + "and leaves a message for the next watch.\nChecks the west wing. "+ generalNote.tap()+ generalNote.typeText(authoredGroupNote)+ XCTAssertEqual(generalNote.value as? String, authoredGroupNote,+ "Long multiline whitespace remains intact in the editor") app.buttons["group-editor.save"].tap() let groupEditLine = app.descendants(matching: .any) .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work-detail.group-edit.")).firstMatch@@ -83,6 +98,14 @@ final class CharacterGroupsUITests: XCTestCase { 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")+ let groupDisclosure = app.buttons["The Night Crew, group"]+ scrollUntilTappableAndTap(groupDisclosure, in: app,+ "The saved group expands to its read-only detail card")+ let groupNote = app.descendants(matching: .any).matching(NSPredicate(+ format: "identifier BEGINSWITH %@", "work-detail.group-note.")).firstMatch+ waitFor(groupNote, "The saved multiline note is shown in the Work group card")+ XCTAssertTrue(groupNote.label.contains("Keeps the archive"))+ XCTAssertTrue(groupNote.label.contains("Checks the west wing.")) attachSurface("group-saved-view-mode") XCTAssertFalse(app.buttons["work-detail.add-group"].exists, "Group creation is absent from view mode")
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swiftindex 55b2cffa..06261366 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 = AsterismSchemaV23.AssociationEvent-public typealias PairNoteVersion = AsterismSchemaV23.PairNoteVersion+public typealias AssociationEvent = AsterismSchemaV24.AssociationEvent+public typealias PairNoteVersion = AsterismSchemaV24.PairNoteVersion -extension AsterismSchemaV23 {+extension AsterismSchemaV24 { @Model public final class AssociationEvent { #Index<AssociationEvent>([\.id], [\.workID], [\.entryID], [\.recordID]) public var id: UUID = UUID()
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23.swiftindex 0fc429c2..de131f31 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23.swift@@ -107,7 +107,3 @@ extension AsterismSchemaV23 { } } }--public typealias NamedCharacterGroup = AsterismSchemaV23.CharacterGroup-public typealias GroupFactEvent = AsterismSchemaV23.GroupFactEvent-public typealias GroupTransition = AsterismSchemaV23.GroupTransition
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23AssociationModels.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23AssociationModels.swiftnew file mode 100644index 00000000..f296d3c3--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23AssociationModels.swift@@ -0,0 +1,60 @@+import Foundation+import SwiftData++extension AsterismSchemaV23 {+ @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+ case .groupSuggestionSkip(let skip): entryID = skip.chapterID+ case .groupSelection(let selection): entryID = selection.pair.entryID; recordID = selection.pair.groupID+ 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/AsterismSchemaV23ChapterCheckModels.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23ChapterCheckModels.swiftnew file mode 100644index 00000000..277b0c55--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23ChapterCheckModels.swift@@ -0,0 +1,31 @@+import Foundation+import SwiftData++extension AsterismSchemaV23 {+ /// One immutable chapter-check row: a complete grounded outcome, or a review+ /// receipt. Relationship-free, defaulted, never unique and never deleted by a+ /// sync-side sweep; an orphan simply stays unusable. The compact header is a+ /// selection hint only — completion and supersession authority come from the+ /// validated body (`ChapterCheckCodec.admit`).+ ///+ /// `payloadData` is `.externalStorage` so the large body stays out of the+ /// initial row materialisation; whether the native store honours that on a+ /// scoped read is the early risk gate of `chapter-ai-check-results` (task 7).+ @Model public final class ChapterCheckRecord {+ #Index<ChapterCheckRecord>([\.id], [\.workID], [\.entryID], [\.entryID, \.noteFingerprint])+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var entryID: UUID = UUID()+ public var noteFingerprint: String = ""+ public var recordKindRaw: String = ""+ public var headerData: Data = Data()+ @Attribute(.externalStorage) public var payloadData: Data = Data()++ public init(id: UUID = UUID(), workID: UUID = UUID(), entryID: UUID = UUID(), noteFingerprint: String = "",+ recordKindRaw: String = "", headerData: Data = Data(), payloadData: Data = Data()) {+ self.id = id; self.workID = workID; self.entryID = entryID+ self.noteFingerprint = noteFingerprint; self.recordKindRaw = recordKindRaw+ self.headerData = headerData; self.payloadData = payloadData+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23Models.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23Models.swiftnew file mode 100644index 00000000..5aa09d9f--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV23Models.swift@@ -0,0 +1,1661 @@+import Foundation+import SwiftData++extension AsterismSchemaV23 {++@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 = ""+ /// M4a: the Site this Entry was captured on, as a modelled reference (Req+ /// 1.1). `hostname` stays beside it as capture-time evidence (Q3). Nil while+ /// the Site has not arrived, or where no Site row matches — a tolerated+ /// state, not an error (Req 2.1). Written in the same save as `hostname`+ /// (Req 1.4).+ public var site: Site?+ public var entryIdentityKey: String = ""+ /// M4 secondary lookup index: the conservative (v1) key for this Entry's raw+ /// URL, retained even after an S-rule rewrites `entryIdentityKey` to v3 so a+ /// title-less same-URL re-share still matches (Q21). Backfilled at migration.+ 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+ /// V7: the fingerprint of the note text a character-extraction pass last+ /// covered (Q59). A **derived** field, excluded from authored content the+ /// way a parsed `chapterTitle` is: editing the note is what uncovers the+ /// revision, so this column tracks the model's work, never the reader's.+ /// Nil means the note has never been covered.+ public var characterExtractionFingerprint: String?+ /// V8: the Entry's seven rule citations and its identity basis, as one+ /// `EntryCitations` blob (Q25) — the column that superseded+ /// `identityKeyVersion` and the seventeen citation/provenance columns V9+ /// dropped, and now the **only** home any of them has.+ ///+ /// Every writer writes it and `init` seeds it, so nil means one thing: a row+ /// a V8 build wrote that this build has not rewritten. It reads as the+ /// default rather than throwing (Q6) and `entriesWithoutCitationBlobCount`+ /// counts it — a **report**, not a quarantine (Q25): the validator throws on+ /// bytes that will not decode and says nothing about bytes that are absent.+ public var citationsData: Data?++ public init(+ id: UUID = UUID(),+ captureTitle: String,+ captureTitleSource: CaptureTitleSource,+ rawURLString: String,+ canonicalURLString: String? = nil,+ hostname: String,+ entryIdentityKey: String,+ timestamp: Date,+ capturedAt: Date? = nil,+ note: String = "",+ rating: Rating? = nil,+ work: Work? = nil+ ) {+ self.id = id+ self.captureTitle = captureTitle+ captureTitleSourceRaw = captureTitleSource.rawValue+ self.rawURLString = rawURLString+ self.canonicalURLString = canonicalURLString+ self.hostname = hostname+ self.entryIdentityKey = entryIdentityKey+ self.note = note+ ratingRaw = rating?.rawValue+ // The two clocks (Req 3.2, Decision 2). `capturedAt` is the instant the+ // reader shared the page, which a preserved capture carries and an+ // ordinary one does not: it supplies the two reader-facing fields and+ // nothing else. `modifiedAt` is bookkeeping about this row and always+ // takes `timestamp`, the instant of the write — backdating it would+ // change which of two diverging copies wins on another device.+ firstCapturedAt = capturedAt ?? timestamp+ lastSharedAt = capturedAt ?? timestamp+ modifiedAt = timestamp+ self.work = work+ // **Every code path that creates an Entry writes the blob at creation**+ // (V9 Req 4). Since the blob is the only home a citation has, a row born+ // without one would read as "cites nothing" for the rest of its life+ // rather than as "not converted yet" — so the default value is written+ // here, once, instead of at a dozen construction sites. A nil blob is+ // therefore only ever a row a V8 build wrote and this one has not+ // rewritten, which is exactly the state the validator reports — so the+ // default is encoded once into a constant rather than `try?`d here,+ // where a failed encode would spell itself the same way.+ citationsData = EntryCitations.defaultBlob+ }++ public var captureTitleSource: CaptureTitleSource {+ get { ToleratedEnum.read(captureTitleSourceRaw, default: .manual) }+ set { captureTitleSourceRaw = newValue.rawValue }+ }++ public var rating: Rating? {+ get { ToleratedEnum.read(ratingRaw) }+ set { ratingRaw = newValue?.rawValue }+ }++ public var identityBasis: EntryIdentityBasis {+ get { ToleratedEnum.read(identityBasisRaw, default: .conservative) }+ set { identityBasisRaw = newValue.rawValue }+ }++ /// The chapter title's provenance kind, **derived from the blob**. Read-only:+ /// the blob stores the whole citation, and a kind written without its cited+ /// rule is a state `EntryCitations` deliberately cannot spell (Q39). Writers+ /// go through `setCitations` or `editCitations`.+ public var chapterTitleProvenance: FieldProvenanceKind {+ citationValues.chapterTitle.kind+ }++ /// How this Entry came to be on its Work, derived from the blob. Read-only,+ /// for the reason above.+ public var workAssignmentProvenance: FieldProvenanceKind {+ citationValues.workAssignment.provenanceKind+ }++ /// Which half of a URL rule assigned the Work, derived from the blob.+ public var workURLAssignmentKind: URLWorkAssignmentKind? {+ citationValues.workURLAssignmentKind+ }++ /// Everything this Entry cites, as one value (Q25).+ ///+ /// Nil bytes read as the default — identity `.rawURL`, nothing cited (Q6).+ /// A nil blob means a row a V8 build wrote and V9 has not rewritten; it is+ /// reported by the validator and counted by the diagnosis, but an ordinary+ /// read of one must not throw or a single exposed row would fail a screen.+ ///+ /// Throws on bytes that will not decode, as `URLRulePattern.definition`+ /// does; the validator turns that into a reportable per-row state rather+ /// than a substituted value.+ public var citations: EntryCitations {+ get throws {+ guard let citationsData else { return EntryCitations() }+ return try JSONBlob.decode(EntryCitations.self, from: citationsData)+ }+ }++ /// Whether the row carries **no** citation bytes at all, as against bytes+ /// that decode to the default. The two read the same and are a different+ /// fact: the second is what a writer wrote, the first is a row the V8 → V9+ /// drop stage reached before anything converted it (Q6). The validator, the+ /// diagnosis and the counter all ask this question, so they ask it once.+ public var citationsAreAbsent: Bool { citationsData == nil }++ /// The citations as every ordinary reader wants them: bytes that will not+ /// decode read as the default rather than throwing, which is the same+ /// tolerance the enum columns had (Q2). The validator is the one caller that+ /// wants the throw, and it uses `citations`.+ public var citationValues: EntryCitations {+ (try? citations) ?? EntryCitations()+ }++ /// Reads the citations, applies `edit`, and writes them back — the door for+ /// a writer that owns some arms of the blob and must leave the rest alone.+ ///+ /// **Bytes that will not decode are repaired in place** (Q24): the edit is+ /// applied over the default value and written, which is what the retired+ /// column-derived refresh did — it replaced bytes that would not decode+ /// rather than leaving them diagnosed for ever. Skipping the write+ /// instead would land the caller's *surrounding* write (a manual+ /// assignment, a re-teach) with its provenance stuck at `.none`, which is a+ /// state the validator refuses on the next save. What the row loses is the+ /// citations nothing could read anyway.+ ///+ /// **A nil blob is not undecodable** (Q23). It reads as the default, so a+ /// real edit over one is written and a no-op edit over one leaves it nil —+ /// which is what kept `entriesWithoutCitationBlobCount` meaning something+ /// while the reconcilers walked every Entry to rewrite citations. Those+ /// walks are gone with the version rewriting (T-2281); the guard stays,+ /// because any bulk writer that arrives next would trip the same wire.+ ///+ /// Value-guarded, so a writer that changed nothing dirties no row.+ @discardableResult+ public func editCitations(_ edit: (inout EntryCitations) -> Void) -> Bool {+ let decoded = try? citations+ var edited = decoded ?? EntryCitations()+ edit(&edited)+ // Undecodable bytes: always write, even where the edit produced the+ // default — the point of the write is that the row stops being+ // unreadable.+ if let current = decoded, edited == current { return false }+ do { try setCitations(edited) } catch { return false }+ return true+ }++ /// Writes the citations, leaving the stored bytes untouched when encoding+ /// fails (Req 4.6) — the `URLRulePattern.setDefinition` guarantee.+ public func setCitations(_ citations: EntryCitations) throws {+ try setCitations(citations) { try JSONBlob.encode($0) }+ }++ /// The seam the "a failed encode changes nothing" test drives. The+ /// assignment happens only after `encode` returns.+ internal func setCitations(+ _ citations: EntryCitations,+ encode: (EntryCitations) throws -> Data+ ) throws {+ citationsData = try encode(citations)+ }+}++@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 = ""+ /// V6: the `WorkTypeEntity` this Work is assigned, cited by UUID rather than+ /// modelled as a relationship (Decision 8 — an inverse would fault every+ /// Work assigned a type, the Q17 fan-out at larger scale). A dangling value+ /// is a tolerated state, not corruption (Req 8.6): the type row may simply+ /// not have arrived yet.+ public var workTypeID: UUID?+ public var genreTags: [String] = []+ public var titleProvenanceRaw: String = TitleProvenance.manual.rawValue+ /// V10: the **author's** side — whether the work is still being written+ /// (Req 1.1). Reader-entered; nothing infers it and a capture never changes+ /// it (Q8).+ ///+ /// Defaulted, non-optional and non-unique, the CloudKit-mirrored shape every+ /// other column here already has — and the initialiser is what SwiftData+ /// turns into the Core Data attribute default, which is what fills the+ /// column on every existing row during the V9 → V10 lightweight stage+ /// (Req 9.1). That is also why `Work.init` and both `create` doors are+ /// untouched: a defaulted column is not an init parameter (Req 2.6).+ public var workStatusRaw: String = WorkStatus.ongoing.rawValue+ /// V10: the **reader's** side — where they stand with the work (Req 2.1).+ /// Same shape and same reasoning as `workStatusRaw`.+ public var readingStatusRaw: String = ReadingStatus.reading.rawValue+ /// V10: the reader's closing thought once they are done with the work+ /// (Req 2.4) — why they stopped under `abandoned`, how they found it under+ /// `finished`. One field serves both (Q6).+ ///+ /// Stored trimmed, with no length limit; the trim happens in `updateWork`,+ /// beside `normalizeTags` and nowhere else (Q33). It survives a reading+ /// status returning to `reading` and is simply not shown (Q7, Req 2.5), so+ /// nothing here clears it.+ public var verdict: String = ""+ /// V11: the series this work belongs to, by identifier+ /// (`series-and-related-works` Decision 6). Resolved through+ /// `SeriesDirectory` exactly as `workTypeID` is resolved through+ /// `WorkTypeDirectory`, and for the same reason: an inverse relationship+ /// would fault every work and would nullify a value that must survive its+ /// target being absent. An identifier naming a `Series` this device does not+ /// hold is a **tolerated** state, not damage (Req 11.2).+ ///+ /// Optional rather than defaulted, which is what lets the V10 → V11 stage be+ /// bare `.lightweight` with no attribute default to fill: nil is "in no+ /// series", and an existing row arrives already saying so.+ public var seriesID: UUID?+ /// V11: where this work sits in that series — a finite decimal the reader+ /// enters, ties and gaps allowed (Req 2.1, 2.2).+ ///+ /// The pair is both-or-neither by convention: at the repository boundary it+ /// is one `SeriesMembership?` value, and a half-set row that arrives through+ /// sync reads as no membership and is normalised on the next write.+ public var seriesPosition: Double?+ /// V15: the weekdays this work's author publishes on, as lowercase English+ /// day names (`update-schedule` Req 1.1, Q27).+ ///+ /// Defaulted, non-optional and non-unique — the CloudKit-mirrored shape+ /// `genreTags` has had since V5, and the shape a small closed value set+ /// takes here. A bitmask would be unreadable in the CloudKit dashboard and+ /// in the archive, and a join table is the shape for a fact two devices edit+ /// concurrently, which one work's own days are not.+ ///+ /// The property initialiser is what SwiftData turns into the Core Data+ /// attribute default, which is what fills the column on every existing row+ /// during the V14 → V15 lightweight stage (Req 9.1). That is also why+ /// `Work.init` and both `create` doors are untouched: a defaulted column is+ /// not an init parameter, which is what makes Req 1.5's creation paths free.+ ///+ /// Read through `releaseDays` everywhere the set is shown or evaluated; the+ /// **raw** column is what export reads, so an unrepresentable value can be+ /// refused by name (Req 8.3).+ public var releaseDaysRaw: [String] = []+ /// V17: independently elected catch-up progress values. Optional blobs migrate as nil.+ public var catchUpConfirmationData: Data?+ public var lastChapterOverrideData: Data?+ /// V20: one authored publication state; nil retains legacy status behaviour.+ public var publicationStateData: Data?+ /// V14: the reader's cover for this work, as JPEG bytes+ /// (`work-thumbnails` Decision 2, Req 1.1).+ ///+ /// **`.externalStorage` is part of the stored shape, not a hint.** SwiftData+ /// keeps the blob in a sidecar file under the store's `_SUPPORT` directory+ /// and leaves a reference on the row, which is what keeps the whole-table+ /// faults the works list, Recent, the validator and the extension's open all+ /// perform from reading a single cover (Req 7.1, Req 9.3): a host probe over+ /// 1,000 rows with one in five carrying 150 KB measured 0.2 MB resident+ /// against 62.7 MB inline, and the phone probe measured +0.0 MB against a+ /// 10 MB gate. It is the first `@Attribute` in the schema and it must+ /// survive the next freeze verbatim.+ ///+ /// Optional with no default, like V11's two columns: nil is "this work has+ /// no cover", so the V13 → V14 stage has nothing to write.+ ///+ /// The three columns below are written and cleared **together** by every+ /// writer that touches them (Req 1.4). A row where they disagree — bytes+ /// missing, or not matching the digest, or not of the shape's dimensions —+ /// is a *tolerated* state (Req 1.8), never a diagnosis: it presents the+ /// glyph until a Save sets or removes the thumbnail, and a restore heals it+ /// because import re-derives the digest from the archived bytes.+ @Attribute(.externalStorage)+ public var thumbnailData: Data?+ /// V14: the cover's shape, `"portrait"` or `"square"`. Read tolerantly+ /// through `thumbnailShape`, where a set but unrecognised spelling answers+ /// `.portrait` (Q63) — writing stays intolerant, and the export refuses an+ /// unknown raw by name (Req 8.3).+ public var thumbnailShapeRaw: String?+ /// V14: the SHA-256 hex of the cover bytes (Q38), which is what every+ /// comparison of thumbnails reads instead of the bytes (Decision 1,+ /// Req 1.7). Fixed for this schema generation (Req 1.10).+ public var thumbnailDigest: String?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// V7: the fingerprint of the generic-notes text a character-extraction pass+ /// last covered (Q59). Derived, like `Entry.characterExtractionFingerprint`,+ /// and excluded from authored content for the same reason.+ public var genericNotesExtractionFingerprint: String?+ @Relationship(deleteRule: .nullify, inverse: \Entry.work)+ public var entries: [Entry]?+ /// V7: the characters extracted or hand-created for this Work (Q58). The+ /// inverse of `Character.work`, `.nullify` exactly as `entries` is — the+ /// cascade is repository-enforced, so a nullified orphan is a tolerated+ /// in-flight state (Req 6.7) rather than a delete SwiftData performs behind+ /// the repository's back.+ @Relationship(deleteRule: .nullify, inverse: \AsterismSchemaV23.Character.work)+ public var characters: [AsterismSchemaV23.Character]?+ /// V7: the suppression rows scoped to this Work (Q60). Same shape and same+ /// reasoning as `characters`.+ @Relationship(deleteRule: .nullify, inverse: \AsterismSchemaV23.CharacterSuppression.work)+ public var characterSuppressions: [AsterismSchemaV23.CharacterSuppression]?+ /// V8: this Work's site memberships, one per hostname (Req 1.1, Q3). The+ /// inverse of `WorkSiteMembership.work`, `.nullify` exactly as `entries` is:+ /// the cascade is repository-enforced (Req 7.3), so a nullified orphan is a+ /// tolerated in-flight state (Req 8.3) rather than a delete SwiftData+ /// performs behind the repository's back.+ @Relationship(deleteRule: .nullify, inverse: \AsterismSchemaV23.WorkSiteMembership.work)+ public var siteMemberships: [AsterismSchemaV23.WorkSiteMembership]? = []++ /// **Not public** (Decision 4, Q41): a Work must always hold at least one+ /// site membership (Req 1.3), and the only way to make that true by+ /// construction is to give creation a single door — `Work.create`, which+ /// mints the row and its first membership together. This initializer is the+ /// inside of that door, reachable from the package (and from `@testable`+ /// suites modelling a Req 2.7 membership-less arrival) and from nowhere else.+ ///+ /// It takes no hostname since V9: `siteHostname` was the last column a+ /// Work's site presence had outside its `WorkSiteMembership`, and the row+ /// that carries it is minted by `createCarrying` in the same call.+ init(id: UUID = UUID(), displayTitle: String, timestamp: Date) {+ self.id = id+ self.displayTitle = displayTitle+ createdAt = timestamp+ modifiedAt = timestamp+ }++ public var titleProvenance: TitleProvenance {+ get { ToleratedEnum.read(titleProvenanceRaw, default: .manual) }+ set { titleProvenanceRaw = newValue.rawValue }+ }++ /// Req 1.3: a spelling this build has no case for — an empty string+ /// included — reads as `ongoing` everywhere the status is shown or filtered.+ /// Writing is unaffected (Q19): committing edit mode writes what the picker+ /// showed, and the export still refuses an unrepresentable raw by name+ /// (Req 8.3).+ public var workStatus: WorkStatus {+ get { ToleratedEnum.read(workStatusRaw, default: .ongoing) }+ set { workStatusRaw = newValue.rawValue }+ }++ /// Req 2.7, the same policy on the reader's side, defaulting to `reading`.+ public var readingStatus: ReadingStatus {+ get { ToleratedEnum.read(readingStatusRaw, default: .reading) }+ set { readingStatusRaw = newValue.rawValue }+ }++ /// V15: the work's release days, canonical and ordered (Req 1.1).+ ///+ /// **Tolerant on read, canonical on write** — the same policy `workStatus`+ /// and `readingStatus` follow, spelled over an array. The getter drops a+ /// spelling this build has no case for, so an unknown value is ignored+ /// everywhere the set is shown or evaluated (Req 1.6); the setter writes the+ /// canonical order, so any write through this accessor normalises and two+ /// rows given the same days in different orders hold the same bytes+ /// (Req 7.5).+ ///+ /// Export reads `releaseDaysRaw` rather than this, so it can refuse an+ /// unknown value by name (Req 8.3, Q21), and the snapshot carries both, so+ /// the editor can tell a set that merely dropped an unknown value from an+ /// unchanged one.+ public var releaseDays: [ReleaseDay] {+ get { ReleaseDay.canonical(releaseDaysRaw.compactMap(ReleaseDay.init(rawValue:))) }+ set { releaseDaysRaw = ReleaseDay.canonical(newValue).map(\.rawValue) }+ }++ /// V14: the cover's shape, or nil where the column is unset. A *set* but+ /// unrecognised spelling reads as `.portrait` rather than as nil (Q63), so a+ /// cover a future build wrote is still shown, still removable and still+ /// named by the export refusal.+ public var thumbnailShape: ThumbnailShape? {+ ToleratedEnum.read(thumbnailShapeRaw, defaultIfSet: .portrait)+ }++ /// V14: the work's thumbnail **presence**, which is the shape and the digest+ /// and never the bytes (Req 1.1, Decision 1).+ ///+ /// Both columns set is a thumbnail; anything else is none. The bytes are+ /// expected beside them and their absence is tolerated (Req 1.8), which is+ /// exactly why presence has to be readable without them.+ public var thumbnailIdentity: ThumbnailIdentity? {+ guard let shape = thumbnailShape, let digest = thumbnailDigest else { return nil }+ return ThumbnailIdentity(shape: shape, digest: digest)+ }++ /// V14: the **one** way the three cover columns are written (Req 1.4).+ ///+ /// They are a tuple, and every writer either sets all three or clears all+ /// three — a row holding one of them without the others is the tolerated+ /// state Req 1.8 describes, never one a writer should be able to create by+ /// forgetting a line. Six call sites spelled the three assignments by hand;+ /// this is that spelling, once, so a seventh cannot be written wrong.+ ///+ /// Deliberately unguarded: *when* to write is the caller's policy and it+ /// differs per site — `updateWork` writes unconditionally so a re-pick+ /// repairs a torn row (Q58), the silent fold guards on the digest (Req+ /// 1.11), and import guards on all three so an unchanged cover does not+ /// rewrite an external-storage sidecar. This is only the write.+ public func applyThumbnail(bytes: Data?, shapeRaw: String?, digest: String?) {+ thumbnailData = bytes+ thumbnailShapeRaw = shapeRaw+ thumbnailDigest = digest+ }++ public var entryValues: [Entry] { entries ?? [] }+ public var characterValues: [AsterismSchemaV23.Character] { characters ?? [] }+ public var characterSuppressionValues: [AsterismSchemaV23.CharacterSuppression] { characterSuppressions ?? [] }++ /// The Work's memberships in the order Req 1.2 fixes: creation date, then+ /// identifier. Every surface that lists sites reads this, so "membership+ /// order" is one rule in one place rather than a sort each caller repeats.+ public var membershipValues: [AsterismSchemaV23.WorkSiteMembership] {+ Self.membershipOrder(siteMemberships ?? [])+ }++ /// The **primary** membership: the first row in `membershipValues`, found+ /// without sorting the rest.+ ///+ /// `GroupOrdering` reads this once per Work on a path every write takes+ /// (Q18), and `membershipValues.first` charged that read a whole sort to+ /// answer a question `min` answers in one pass.+ public var primaryMembership: AsterismSchemaV23.WorkSiteMembership? {+ (siteMemberships ?? []).min(by: Self.membershipPrecedes)+ }++ /// Req 1.2's order over an explicit set of rows, for the callers that hold+ /// one — a commit that has deleted a membership and not yet saved cannot+ /// trust the inverse array to have dropped it.+ static func membershipOrder(_ rows: [AsterismSchemaV23.WorkSiteMembership]) -> [AsterismSchemaV23.WorkSiteMembership] {+ rows.sorted(by: membershipPrecedes)+ }++ /// Req 1.2's comparison itself, so the order and the `min` that picks its+ /// first element cannot disagree about which membership is primary.+ private static func membershipPrecedes(+ _ lhs: AsterismSchemaV23.WorkSiteMembership, _ rhs: AsterismSchemaV23.WorkSiteMembership+ ) -> Bool {+ lhs.createdAt == rhs.createdAt+ ? lhs.id.uuidString < rhs.id.uuidString+ : lhs.createdAt < rhs.createdAt+ }++ /// The membership for `hostname`, or nil where the Work holds none.+ ///+ /// Req 1.1 forbids two memberships on one hostname, but sync can produce+ /// them until reconciliation resolves them (Req 2.6, 8.2), so this answers+ /// with one of them rather than asserting uniqueness — and the one it+ /// answers with is the **survivor** the dedupe would keep (Q23, Q61):+ /// strongest identity state, then earliest created, then lowest id.+ ///+ /// Deliberately *not* membership order, which Req 1.2 fixes for+ /// presentation. Between a duplicate arriving and the next reconcile, a+ /// state-`none` twin sorting first under `(createdAt, id)` would make+ /// identity-first matching read the Work as having no identity on this site+ /// (Req 3.1) and mint a second Work — a loss the reconcile could not undo.+ /// Answering with the survivor means the row this returns now is the row+ /// that will still be here afterwards.+ public func membership(for hostname: String) -> AsterismSchemaV23.WorkSiteMembership? {+ Self.membership(in: siteMemberships ?? [], for: hostname)+ }++ /// The same answer over rows the caller already holds — a reader that+ /// fetched the memberships rather than faulting the inverse array (Q55,+ /// Decision 5). One rule in one place, so the two cannot disagree about+ /// which duplicate is the survivor.+ public static func membership(+ in rows: [AsterismSchemaV23.WorkSiteMembership], for hostname: String+ ) -> AsterismSchemaV23.WorkSiteMembership? {+ let matching = rows.filter { $0.hostname == hostname }+ guard matching.count > 1 else { return matching.first }+ return matching+ .map { (key: AsterismSchemaV23.WorkSiteMembership.OrderKey($0), row: $0) }+ .min { $0.key < $1.key }?.row+ }++ /// Every row on `hostname` with the hostname matched+ /// **case-insensitively**, in survivor order+ /// (`wrong-host-work-url-heal` Q65).+ ///+ /// A stored hostname is not normalised, while a host derived from a URL+ /// always is, so a caller holding a derived host — the wrong-host heal, which+ /// asks about the membership of the host a Work URL names — cannot use the+ /// exact match above: a `Example.com` row would be invisible to it and it+ /// would mint a second row in a different case, which nothing ever folds.+ /// Every other caller holds a stored hostname already and keeps the exact+ /// match, which is one string comparison rather than two allocations.+ ///+ /// Plural because the heal needs both halves of the question — the row a+ /// value lands on, and *every* row a value is cleared from — and one+ /// spelling of "on this host" is what keeps those two agreeing.+ static func memberships(+ in rows: [AsterismSchemaV23.WorkSiteMembership], forHostMatching hostname: String+ ) -> [AsterismSchemaV23.WorkSiteMembership] {+ let host = hostname.lowercased()+ let matching = rows.filter { $0.hostname.lowercased() == host }+ guard matching.count > 1 else { return matching }+ return matching+ .map { (key: AsterismSchemaV23.WorkSiteMembership.OrderKey($0), row: $0) }+ .sorted { $0.key < $1.key }+ .map(\.row)+ }++ /// The survivor of `memberships(in:forHostMatching:)` — the row every+ /// caller that wants one gets handed.+ static func membership(+ in rows: [AsterismSchemaV23.WorkSiteMembership], forHostMatching hostname: String+ ) -> AsterismSchemaV23.WorkSiteMembership? {+ memberships(in: rows, forHostMatching: hostname).first+ }+}++@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]?+ /// Inverse of `Entry.site`, present only because CloudKit requires every+ /// relationship to have one (Req 1.3). **Deliberately `internal`** while+ /// `Site` is `public`, so the app target cannot reach it: traversing this+ /// faults every Entry for a hostname — roughly 125× the fan-out of+ /// `Work.entries` — which the Req 5.1 budgets would pay for (Q17). No+ /// `entryValues` accessor exists, for the same reason.+ @Relationship(deleteRule: .nullify, inverse: \Entry.site)+ var entries: [Entry]?+ /// V8: inverse of `WorkSiteMembership.site`, present because CloudKit+ /// requires every relationship to have one. Internal for the same reason+ /// `works` is (Q17): traversing it faults every membership for a hostname,+ /// and the repository fetches memberships by predicate instead.+ @Relationship(deleteRule: .nullify, inverse: \AsterismSchemaV23.WorkSiteMembership.site)+ var workMemberships: [AsterismSchemaV23.WorkSiteMembership]?+ // `junkSuffixRule` stood here: the reader-taught title cleaner articles mode+ // applied. It went with the mode at V16 (`remove-article-mode` Req 4.1). The+ // `JunkSuffixRule` remains in `ValueObjects.swift` for historical contract+ // tests; the live schema has no consumer.++ public init(hostname: String, displayName: String? = nil) {+ self.hostname = hostname+ self.displayName = displayName ?? hostname+ }++ public var mode: SiteMode {+ get { ToleratedEnum.read(modeRaw, default: .untaught) }+ set { modeRaw = newValue.rawValue }+ }++ /// The Site's active title pattern (Decision 5: a taught Site always holds+ /// exactly one). Nil for an untaught Site.+ ///+ /// One of the two accessors every reader of a current rule goes through+ /// (T-2281 Req 4.2, Q11): `RuleSelection.current` carries the Decision 1+ /// tiebreak for the double-marked Site the version invariant's retirement+ /// leaves readable until the next reconcile repairs it.+ public var activePattern: TitlePattern? { RuleSelection.current(patternValues) }++ /// The Site's current URL rule, by the same rule as `activePattern`. Nil+ /// where the Site holds no marked URL rule.+ public var currentURLRule: URLRulePattern? { RuleSelection.current(urlRuleValues) }++ public var patternValues: [TitlePattern] { patterns ?? [] }+ public var urlRuleValues: [URLRulePattern] { urlRules ?? [] }+}++@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)+ /// V8: the pattern's whole definition surface — the arm *and* both trims —+ /// as one `StoredPatternDefinition` blob (Q25), and since V9 the only home+ /// it has: the ten decomposed columns it superseded are gone.+ ///+ /// Nil means a row a V8 build wrote that nothing has rewritten since; no+ /// pass converts one, because the ten columns it would be derived from are+ /// gone. `storedDefinition` throws for one, the validator reports it as+ /// `unreadableTitlePattern`, and `GroupOrdering` gives it its own constant+ /// ordering key (Q11).+ public var definitionData: Data?+ public var site: Site?++ /// The trims are initializer parameters rather than columns a caller+ /// assigns afterwards: V8 stores the whole definition surface as one blob+ /// (Q25), so a trim written after construction would have to re-encode it.+ public init(+ id: UUID = UUID(),+ version: Int,+ isActive: Bool = false,+ createdAt: Date,+ definition: PatternDefinition,+ trimPrefix: String? = nil,+ trimSuffix: String? = nil,+ site: Site? = nil+ ) throws {+ guard version > 0 else {+ throw ModelInvariantError.nonPositiveVersion(field: "title pattern version")+ }+ self.id = id+ self.version = version+ self.isActive = isActive+ self.createdAt = createdAt+ // **Before the relationship, deliberately.** Assigning `site` to a row+ // that is already in a context registers this object with that context+ // there and then, and SwiftData snapshots the backing data at that+ // point: a `definitionData` written afterwards is dropped on an+ // SQLite-backed store (it survives an in-memory one, which is how this+ // hid). Every stored value goes in first, the relationship last.+ try setDefinition(+ StoredPatternDefinition(+ definition: try definition.validated(),+ trimPrefix: trimPrefix, trimSuffix: trimSuffix))+ self.site = site+ }++ /// Compatibility initializer for V1-shaped tests and migration mapping. It+ /// always creates the V2 segment arm; runtime callers still validate it+ /// against the injected gate before persistence.+ public convenience init(+ id: UUID = UUID(),+ version: Int,+ isActive: Bool = false,+ createdAt: Date,+ workAnchor: SegmentRangeSpec,+ junkAnchors: [SegmentPositionSpec] = [],+ site: Site? = nil+ ) {+ do {+ try self.init(+ id: id,+ version: version,+ isActive: isActive,+ createdAt: createdAt,+ definition: .segment(work: workAnchor, ignored: junkAnchors),+ site: site+ )+ } catch {+ preconditionFailure("Invalid compatibility pattern initializer: \(error)")+ }+ }++ /// The pattern's whole definition surface, read from the blob (Q25) — the+ /// only home it has since V9.+ ///+ /// Throws rather than substituting a rule the reader never taught (Req 4.3),+ /// exactly as `URLRulePattern.definition` does and for the same reason: a+ /// fabricated definition validates cleanly and blames the captures. **A nil+ /// blob throws for that reason too**: it used to fall back to the ten legacy+ /// columns, and with those unwritten there is nothing behind it. The+ /// validator reports such a row as `unreadableTitlePattern` and+ /// `GroupOrdering` gives it its own constant ordering key (Q11).+ public var storedDefinition: StoredPatternDefinition {+ get throws {+ guard let definitionData else {+ throw ModelInvariantError.invalidCombination(field: "title pattern definition")+ }+ return try JSONBlob.decode(StoredPatternDefinition.self, from: definitionData)+ }+ }++ /// The arm alone. Every caller that also needs the trims reads+ /// `storedDefinition` once instead, because this decodes on every access.+ public var definition: PatternDefinition {+ get throws { try storedDefinition.definition }+ }++ /// Writes the whole definition surface, leaving the stored bytes untouched+ /// when encoding fails (Req 4.6) — the `URLRulePattern.setDefinition`+ /// guarantee, for the same reason: one failed write must not leave bytes+ /// behind that will not decode on the next read.+ public func setDefinition(_ definition: StoredPatternDefinition) throws {+ try setDefinition(definition) { try JSONBlob.encode($0) }+ }++ /// The seam the "a failed encode changes nothing" test drives. The+ /// assignment happens only after `encode` returns, which is the whole+ /// guarantee.+ internal func setDefinition(+ _ definition: StoredPatternDefinition,+ encode: (StoredPatternDefinition) throws -> Data+ ) throws {+ definitionData = try encode(definition)+ }++ /// Writes a definition only where it differs from the one already stored,+ /// and reports whether anything changed.+ ///+ /// The value guard is what makes a second reconciliation pass over a+ /// converged rule group export no transaction (Req 2.4 of+ /// `relational-references`). It compares the **whole** surface, trims+ /// included: two rows agreeing on the arm and differing in a trim derive+ /// different chapter titles, so a group "converged" without them would still+ /// replay two answers (Q63).+ @discardableResult+ internal func applyStoredDefinition(_ definition: StoredPatternDefinition) throws -> Bool {+ let validated = StoredPatternDefinition(+ definition: try definition.definition.validated(),+ trimPrefix: definition.trimPrefix,+ trimSuffix: definition.trimSuffix)+ guard (try? storedDefinition) != validated else { return false }+ try setDefinition(validated)+ return true+ }+}++@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(+ id: UUID = UUID(),+ version: Int,+ isCurrent: Bool,+ createdAt: Date,+ origin: URLRuleOrigin,+ definition: URLRuleDefinition,+ site: Site? = nil+ ) throws {+ guard version > 0 else {+ throw ModelInvariantError.nonPositiveVersion(field: "URL rule version")+ }+ try definition.validate(origin: origin, isCurrent: isCurrent)+ self.id = id+ self.version = version+ self.isCurrent = isCurrent+ self.createdAt = createdAt+ originRaw = origin.rawValue+ self.definitionData = try JSONBlob.encode(definition)+ self.site = site+ }++ public var origin: URLRuleOrigin? { URLRuleOrigin(rawValue: originRaw) }++ /// Throws rather than substituting a rule the reader never taught (Req 4.3),+ /// mirroring `TitlePattern.definition`.+ ///+ /// It used to answer a decode failure with+ /// `.work(locator: .query(name: "identity"))`. No URL in a real library+ /// carries an `identity` query item, so every extraction against the+ /// substitute failed with `missingComponent`, the citing Works' evidence+ /// became `.failed`, and their URL identity was cleared — while the+ /// diagnosis blamed the captures, because the *fabricated* definition+ /// validates cleanly (Decision 5).+ public var definition: URLRuleDefinition {+ get throws {+ try JSONBlob.decode(URLRuleDefinition.self, from: definitionData)+ }+ }++ /// Writes a definition, leaving the stored bytes untouched when encoding+ /// fails (Req 4.6).+ ///+ /// A Swift computed-property setter cannot throw, and the one this replaced+ /// wrote `Data()` on an encoding failure — itself a route to bytes that will+ /// not decode, so one failed write produced an unreadable rule on the next+ /// read with no version skew involved. Leaving the old bytes in place is+ /// also what keeps the rule recoverable rather than overwritten.+ public func setDefinition(_ definition: URLRuleDefinition) throws {+ try setDefinition(definition) { try JSONBlob.encode($0) }+ }++ /// The seam the "a failed encode changes nothing" test drives. Production+ /// goes through the public overload; the assignment happens only after+ /// `encode` returns, which is the whole guarantee.+ internal func setDefinition(+ _ definition: URLRuleDefinition,+ encode: (URLRuleDefinition) throws -> Data+ ) throws {+ definitionData = try encode(definition)+ }+}++/// V6: one entry in the configured work-type list (Decision 3). Works cite it by+/// `Work.workTypeID`; it cites nothing back, so it declares **no relationships**+/// at all (Decision 8).+///+/// Removal is a state change, never a delete: the additive-only CloudKit posture+/// this project holds to means a removed entry stays in the store so works can+/// keep displaying it (Req 5.1) and so restoring it is the same identity again+/// (Req 5.3). `merged` marks an entry convergence redirected to `canonicalID`+/// (Req 6.2/6.3).+///+/// **The per-field timestamps are load-bearing** (Decision 10). Duplicate rows of+/// one identity are permanent — concurrent seeding creates them and nothing ever+/// deletes them — so two devices' edits can land on *different rows* of the same+/// UUID. Only a field-wise fold combines a remove written to one row with a+/// rename written to another (Req 6.6), which is what `WorkTypeDirectory` does;+/// `modifiedAt` is derived from the two, the max.+///+/// Epoch (`Date(timeIntervalSince1970: 0)`) field timestamps are the *pristine*+/// sentinel: a seeded row nobody has touched never asserts its spelling or state+/// against a user-touched row (Decision 9). Anything that stamps a seed row's+/// timestamps without a user action silently promotes it.+@Model+public final class WorkTypeEntity {+ public var id: UUID = UUID()+ /// The stored spelling, trimmed, as the user entered it. Normalized names+ /// are computed in the directory and never stored (Q30).+ 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)+ /// The identity this entry merged into, set when `state == .merged`. Never+ /// rewritten after the marking: the chase is total instead (Q31).+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// `max(nameModifiedAt, stateModifiedAt)`, maintained by the shared writer.+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ /// Every parameter is defaulted so the memberwise construction and the+ /// stored defaults are the same thing — a row created with no arguments is+ /// the pristine empty active entry CloudKit would materialize.+ public init(+ id: UUID = UUID(),+ name: String = "",+ state: WorkTypeState = .active,+ canonicalID: UUID? = nil,+ timestamp: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.name = name+ stateRaw = state.rawValue+ self.canonicalID = canonicalID+ createdAt = timestamp+ modifiedAt = timestamp+ nameModifiedAt = timestamp+ stateModifiedAt = timestamp+ }++ /// Unknown raw values read as `.active`, matching every other enum column in+ /// this schema: an unrecognised state is tolerated data, not corruption.+ public var state: WorkTypeState {+ get { ToleratedEnum.read(stateRaw, default: .active) }+ set { stateRaw = newValue.rawValue }+ }+}++/// V7: one character of one work — accepted from an extraction proposal or+/// created by hand (Decision 1). Reader-authored throughout: the name, the+/// aliases, the note and the facts' statements are all editable, so the record+/// participates in the duplicate/torn machinery like an Entry or a Work.+///+/// Facts are a Codable blob rather than a table (Q57), on the+/// `URLRulePattern.definitionData` precedent: a fact edit is a character-level+/// authored change, so a character tears at character granularity, and the+/// entry-detail lookup scans a work's characters, where N is small.+///+/// `nameKey` is **retained**: minted once at accept or creation commit (Q19/Q46)+/// and never re-derived from a rename, so a renamed character keeps attracting+/// the proposals that named it before (Req 2.3's second matching tier).+///+/// Every property is defaulted or optional and nothing is unique: this is a+/// CloudKit-mirrored table like the rest.+@Model+public final class Character {+ public var id: UUID = UUID()+ public var name: String = ""+ /// The key the character was accepted or created under, retained through+ /// renames (Q19/Q46). Normalised by `RecordNameKey.normalize`.+ public var nameKey: String = ""+ /// Extra match keys, reader-editable (Q56) and grown by the combine+ /// (Decision 4). Stored as the reader's spellings; matching normalises.+ public var aliases: [String] = []+ public var note: String = ""+ /// `[RecordFact]` in the canonical encoding (Q75). Optional rather than+ /// defaulted-empty because CloudKit materialises a missing column as nil,+ /// and "no facts yet" and "column not synced" are the same thing to a+ /// reader.+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The Work this character belongs to. Nil is a **tolerated** in-flight+ /// state (Req 6.7, Q70): a character that synced ahead of its work is inert+ /// — reachable only through the work — and appears when the work lands.+ public var work: Work?++ /// Every parameter defaulted, so memberwise construction and the stored+ /// defaults are the same value CloudKit would materialise.+ public init(+ id: UUID = UUID(),+ name: String = "",+ nameKey: String = "",+ aliases: [String] = [],+ note: String = "",+ facts: [RecordFact] = [],+ timestamp: Date = Date(timeIntervalSince1970: 0),+ work: Work? = nil+ ) {+ self.id = id+ self.name = name+ self.nameKey = nameKey+ self.aliases = aliases+ self.note = note+ factsData = RecordFactCodec.encode(facts)+ createdAt = timestamp+ modifiedAt = timestamp+ self.work = work+ }++ // `facts` is `RecordRow`'s (RecordRow.swift): the decode is the same for+ // every record table, so it is written once rather than per model.+}++/// V7: one remembered decision not to re-propose something (Q60/Q72).+///+/// A **system record**, never reader-authored (Q40): it never tears, never+/// blocks an export, and converges to the reader's most recent action rather+/// than by set union — which is what makes a clear (Req 2.5) representable at+/// all. Writes update the local row in place, keyed by+/// (work, kind, nameKey, source, evidence); rows duplicated by sync are read+/// through by latest `actionAt`, tie-broken cleared-wins then lowest row UUID+/// (Q82).+@Model+public final class CharacterSuppression {+ public var id: UUID = UUID()+ /// Nil is tolerated for the same reason `Character.work` tolerates it.+ public var work: Work?+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ /// Present on fact rows only; nil on candidate rows. Explicit rather than+ /// inferred from a nil `sourceEntryID`, so a malformed row is+ /// distinguishable from a generic-notes citation (Q72).+ public var sourceKindRaw: String?+ /// Set only where `sourceKind == .entry`.+ public var sourceEntryID: UUID?+ /// The fact's evidence span, on fact rows only. The third component of the+ /// identity triple (Q29).+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ /// When the reader acted. The comparable Q52 convergence needs (Q60).+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ work: Work? = nil,+ kind: CharacterSuppressionKind = .candidate,+ nameKey: String = "",+ source: SourceRef? = nil,+ evidence: String? = nil,+ status: CharacterSuppressionStatus = .active,+ actionAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.work = work+ kindRaw = kind.rawValue+ self.nameKey = nameKey+ sourceKindRaw = source?.kindRaw+ sourceEntryID = source?.entryID+ self.evidence = evidence+ statusRaw = status.rawValue+ self.actionAt = actionAt+ }++ /// An unknown raw value reads as `.candidate`, matching every other enum+ /// column in this schema: unrecognised data is tolerated, not corruption.+ public var kind: CharacterSuppressionKind {+ get { ToleratedEnum.read(kindRaw, default: .candidate) }+ set { kindRaw = newValue.rawValue }+ }++ public var status: CharacterSuppressionStatus {+ get { ToleratedEnum.read(statusRaw, default: .active) }+ set { statusRaw = newValue.rawValue }+ }++ /// The cited source on a fact row, or nil on a candidate row — and nil for a+ /// malformed row, which is why `sourceKindRaw` is stored explicitly.+ public var source: SourceRef? {+ get { SourceRef(kindRaw: sourceKindRaw, entryID: sourceEntryID) }+ set {+ sourceKindRaw = newValue?.kindRaw+ sourceEntryID = newValue?.entryID+ }+ }+}++/// V8: a Work's presence on one site (Q3).+///+/// The row a Work's site presence moved into: one per hostname, carrying that+/// site's URL identity, the identity state, the rule that derived it and the+/// confirmed Work URL for that site. A Work holds at least one (Req 1.3) and+/// never two on one hostname (Req 1.1) — though sync can produce a duplicate+/// until reconciliation resolves it (Req 2.6, 8.2).+///+/// `workID` sits beside the `work` relationship deliberately (Q37): an import-+/// or sync-orphaned row must be able to re-attach when its Work arrives, and a+/// nullified relationship alone loses the intent. A membership whose Work has+/// not arrived is tolerated indefinitely and deleted only with its Work+/// (Req 8.3, Q22).+///+/// Every property is defaulted or optional, nothing is unique, and both+/// relationships are `.nullify` with their inverse on the to-many side: this is+/// a CloudKit-mirrored table like the rest.+@Model+public final class WorkSiteMembership {+ public var id: UUID = UUID()+ public var hostname: String = ""+ /// Req 1.2's ordering key, paired with `id`. A membership minted by the+ /// population pass copies its Work's `createdAt`, so a migrated single-site+ /// Work orders exactly as it did before.+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var urlIdentity: String?+ public var urlIdentityStateRaw: String = WorkURLIdentityState.none.rawValue+ /// The rule row that derived `urlIdentity`, **by UUID only** (Req 10.4,+ /// Q28): the citation names the row and carries no version.+ public var urlIdentityRuleID: UUID?+ public var workURLString: String?+ /// The Work this row belongs to, kept while `work` is nil (Q37).+ public var workID: UUID?+ public var work: Work?+ /// The Site row for `hostname`, nil while it has not arrived — the same+ /// tolerance `Entry.site` carries (Req 1.5).+ public var site: Site?++ /// Every parameter defaulted, so memberwise construction and the stored+ /// defaults are the value CloudKit would materialise.+ public init(+ id: UUID = UUID(),+ hostname: String = "",+ createdAt: Date = Date(timeIntervalSince1970: 0),+ urlIdentity: String? = nil,+ urlIdentityState: WorkURLIdentityState = .none,+ urlIdentityRuleID: UUID? = nil,+ workURLString: String? = nil,+ workID: UUID? = nil,+ work: Work? = nil,+ site: Site? = nil+ ) {+ self.id = id+ self.hostname = hostname+ self.createdAt = createdAt+ self.urlIdentity = urlIdentity+ urlIdentityStateRaw = urlIdentityState.rawValue+ self.urlIdentityRuleID = urlIdentityRuleID+ self.workURLString = workURLString+ self.workID = workID ?? work?.id+ self.work = work+ self.site = site+ }++ /// An unrecognised spelling reads as `.none`, matching every other enum+ /// column in this schema.+ public var urlIdentityState: WorkURLIdentityState {+ get { ToleratedEnum.read(urlIdentityStateRaw, default: .none) }+ set { urlIdentityStateRaw = newValue.rawValue }+ }++ /// The Work this row belongs to, by identifier: the column where a writer+ /// set it, the relationship where a lagging one did not (Q37).+ ///+ /// Reading the relationship faults it, so a caller walking the whole table+ /// on the capture path reads `workID` alone (Q84) and does not come through+ /// here. This is for the callers that must not miss a row an older writer+ /// attached without the column.+ public var resolvedWorkID: UUID? { workID ?? work?.id }++ /// Every membership in the store, indexed by the Work it names, **by+ /// `workID` alone**.+ ///+ /// Nothing here reads `membership.work`: that faults one relationship per+ /// row, on passes that run on every foreground and every arrival, which is+ /// the cost Q84 is written around. A row naming no Work is an orphan+ /// awaiting one (Req 8.3) and belongs to no Work's list; a row with a blank+ /// hostname is on no site (Q30) and contributes no relation.+ ///+ /// Each Work's list comes back in **survivor order** — the order membership+ /// de-duplication keeps a survivor by, and the order the wrong-host Work URL+ /// heal takes its candidates in (Q35). Without it, a caller asking "which+ /// value does this Work hold on this hostname" would be answered by fetch+ /// order, which two devices need not agree on, and the foreground pass and+ /// the full validator could name different hosts for one torn group. The+ /// ordering columns are read as three scalars beside the ones the basis+ /// carries; the rows themselves are still not retained.+ static func indexByWorkID(+ context: ModelContext, batchSize: Int+ ) throws -> [UUID: [WorkMembershipBasis]] {+ // The ordering columns are carried as raw scalars, not as an `OrderKey`:+ // the key is built below for the groups that actually have rows to sort,+ // so the common single-membership Work pays no key at all (Q60).+ struct Row {+ let state: WorkURLIdentityState+ let createdAt: Date+ let id: UUID+ let basis: WorkMembershipBasis+ }+ var index: [UUID: [Row]] = [:]+ try context.enumerate(+ FetchDescriptor<AsterismSchemaV23.WorkSiteMembership>(), batchSize: batchSize+ ) { membership in+ // The same blankness test `LibraryValidator.validate(membership:)`+ // applies, so a whitespace-only hostname is on no site here either.+ guard let workID = membership.workID, !M2Unicode.isBlank(membership.hostname)+ else { return }+ index[workID, default: []].append(Row(+ state: membership.urlIdentityState, createdAt: membership.createdAt,+ id: membership.id, basis: WorkMembershipBasis(+ hostname: membership.hostname, urlIdentity: membership.urlIdentity,+ workURLString: membership.workURLString)))+ }+ return index.mapValues { rows in+ guard rows.count > 1 else { return rows.map(\.basis) }+ return rows+ .map { (key: OrderKey($0.state, $0.createdAt, $0.id), basis: $0.basis) }+ .sorted { $0.key < $1.key }+ .map(\.basis)+ }+ }++ /// Q23's survivor order as three scalars, so a caller that must not retain+ /// the rows can still sort by it — and so the one order has one spelling.+ ///+ /// `indexByWorkID` walks the whole table under `enumerate` and yields value+ /// snapshots; `wrong-host-work-url-heal` Q35 makes the two derivations of+ /// the wrong-host diagnosis agree only because they take their candidates in+ /// **one** order. `MembershipReconciler.survivorFirst` sorts on it too.+ ///+ /// The identifier is kept as a `UUID` and stringified only inside `<`+ /// (Q60): the key is built on the foreground scan and the arrival duplicate+ /// phase, and a `uuidString` per membership there is an allocation on a path+ /// this repo already keeps keys out of.+ struct OrderKey: Comparable {+ let identityRank: Int+ let createdAt: Date+ let id: UUID++ init(_ membership: AsterismSchemaV23.WorkSiteMembership) {+ self.init(membership.urlIdentityState, membership.createdAt, membership.id)+ }++ init(_ state: WorkURLIdentityState, _ createdAt: Date, _ id: UUID) {+ identityRank = Self.rank(state)+ self.createdAt = createdAt+ self.id = id+ }++ /// The strongest identity state first, then the earliest created, then+ /// the lowest identifier.+ ///+ /// State leads because earliest-created alone would let a healed+ /// state-`none` row discard a rule-derived identity — the exact pair+ /// `multi-site-works` Req 2.6 produces when one device heals a Work the+ /// other had already migrated.+ static func < (left: OrderKey, right: OrderKey) -> Bool {+ if left.identityRank != right.identityRank {+ return left.identityRank > right.identityRank+ }+ if left.createdAt != right.createdAt { return left.createdAt < right.createdAt }+ return UUID.bytesPrecede(left.id, right.id)+ }++ private static func rank(_ state: WorkURLIdentityState) -> Int {+ switch state {+ case .rule: 2+ case .legacyUnverified: 1+ case .none: 0+ }+ }+ }+}++/// V8: the reader's "not the same work" over an unordered pair of Works+/// (Req 5.5, Q20).+///+/// Two UUID columns rather than relationships (Q27): a pair must outlive the+/// absence of either Work and re-point by rewriting a column, where a+/// relationship would nullify silently. `lowerWorkID` and `higherWorkID` are the+/// two identifiers sorted, so the unordered pair has one spelling and duplicate+/// detection is a group-by (Req 5.8).+@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(+ id: UUID = UUID(),+ lowerWorkID: UUID = UUID(),+ higherWorkID: UUID = UUID(),+ recordedAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.lowerWorkID = lowerWorkID+ self.higherWorkID = higherWorkID+ self.recordedAt = recordedAt+ }++ /// The canonical spelling of an unordered pair: the two ids sorted by their+ /// string form, which is the ordering every writer and every group-by uses.+ public static func sortedIDs(_ firstID: UUID, _ secondID: UUID) -> (lower: UUID, higher: UUID) {+ firstID.uuidString <= secondID.uuidString ? (firstID, secondID) : (secondID, firstID)+ }+}++/// V11: a reader-named collection a work belongs to at a position+/// (`series-and-related-works` Decision 1).+///+/// **No relationships**, on `WorkDistinctPair`'s grounds (its Q27) and+/// Decision 6's: a work names its series by `Work.seriesID`, so a series+/// outlives the absence of any member and a member outlives the absence of its+/// series. An inverse would fault every work in the series to answer a count,+/// and would nullify a membership that must survive a target still in transit.+///+/// Names are **not** unique (Q11): two devices may create "Foo" concurrently,+/// and the reader resolves it by moving works rather than by a convergence rule.+/// Where two listed series share a name, `SeriesDirectory` qualifies them.+///+/// Every column is defaulted, non-optional and non-unique — the CloudKit+/// -mirrored shape every other column here already has.+@Model+public final class Series {+ public var id: UUID = UUID()+ /// Stored trimmed, with no length limit (Req 1.1).+ public var name: String = ""+ /// The reader's notes about the set rather than about any one work (Q7).+ /// Stored trimmed; may be empty.+ public var notes: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// Stamped by every writer with the quantized clock. No convergence rule+ /// reads it — a rename is not a convergence question, because names need+ /// not be unique — but archive import does: `commitSeries` keeps the row+ /// unless the record is at least as recent (`series-and-related-works`+ /// Req 13.4).+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ name: String = "",+ notes: String = "",+ createdAt: Date = Date(timeIntervalSince1970: 0),+ modifiedAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.name = name+ self.notes = notes+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// V11: an undirected, typed connection between two distinct works+/// (`series-and-related-works` Decision 5).+///+/// The shape is `WorkDistinctPair`'s, for the same reasons: two UUID columns+/// rather than relationships, so a link outlives the absence of either end and+/// re-points by rewriting a column; `lowerWorkID` and `higherWorkID` are the two+/// identifiers sorted through `WorkDistinctPair.sortedIDs`, so the unordered+/// pair has one spelling and duplicate detection is a group-by.+///+/// What it adds over a distinct pair is content the reader owns — a free-text+/// `linkType` — and therefore a `modifiedAt` a convergence rule reads: when more+/// than one row exists over a pair after sync, every device keeps the latest+/// modification, then the lowest identifier (Q27, Req 11.4).+@Model+public final class WorkLink {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ /// Free text, stored trimmed and non-empty (Req 6.4). Not a managed+ /// vocabulary: the suggestions are derived from the rows that exist.+ public var linkType: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// The survivor key over a duplicated pair, latest first (Req 11.4).+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ lowerWorkID: UUID = UUID(),+ higherWorkID: UUID = UUID(),+ linkType: String = "",+ createdAt: Date = Date(timeIntervalSince1970: 0),+ modifiedAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.lowerWorkID = lowerWorkID+ self.higherWorkID = higherWorkID+ self.linkType = linkType+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// V12: a person a work is credited to (`work-creators` Decision 2).+///+/// The shape is `WorkTypeEntity`'s (`:814`), for its reasons: **no+/// relationships** at all — a `WorkCredit` names a creator by identifier — and+/// **one timestamp per independently converging field**, because duplicate rows+/// of one identity are permanent under CloudKit and two devices' edits can land+/// on different rows of the same UUID. Only a field-wise fold combines a rename+/// written to one row with a merge written to another (Q26). `modifiedAt` is+/// derived from the field timestamps, the max, and exists for the archive guard+/// and the list rather than for the fold.+///+/// Epoch (`Date(timeIntervalSince1970: 0)`) field timestamps are the *pristine*+/// sentinel (Q36): a record nobody has touched never asserts its spelling or+/// state against a reader-touched row.+///+/// There is **no `removed` state**: a creator the reader deletes is really+/// deleted, along with the credits naming it (Decision 4, Q16). `merged` marks+/// the loser of a name collision, redirected to `canonicalID`.+///+/// Every column is defaulted, non-optional and non-unique — the+/// CloudKit-mirrored shape. `stateRaw` defaults to the **literal** `"active"`+/// rather than to a case's `rawValue`, so the next freeze inherits one fewer+/// frozen enum spelling; it is read through `ToleratedEnum` at the call sites.+@Model+public final class Creator {+ public var id: UUID = UUID()+ /// The stored spelling, trimmed, as the reader entered it. Normalized names+ /// are computed in the directory and never stored.+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// Free text — "also publishes as X" and the like (Q7). Stored trimmed; may+ /// be empty. Convergence appends a loser's notes to the survivor's.+ public var notes: String = ""+ public var notesModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The identity this record merged into, set when the state is `merged`.+ /// Never rewritten after the marking: the chase is total instead.+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// `max(nameModifiedAt, notesModifiedAt, stateModifiedAt)`, maintained by+ /// the shared writer.+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ /// Every parameter is defaulted so the memberwise construction and the+ /// stored defaults are the same thing — a row created with no arguments is+ /// the pristine empty active record CloudKit would materialize.+ public init(+ id: UUID = UUID(),+ name: String = "",+ notes: String = "",+ stateRaw: String = "active",+ canonicalID: UUID? = nil,+ timestamp: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.name = name+ self.notes = notes+ self.stateRaw = stateRaw+ self.canonicalID = canonicalID+ createdAt = timestamp+ modifiedAt = timestamp+ nameModifiedAt = timestamp+ notesModifiedAt = timestamp+ stateModifiedAt = timestamp+ }+}++/// V12: one entry in the reader-managed, ordered role list credits reference by+/// identity (`work-creators` Decision 1).+///+/// `Creator`'s shape with `position` in place of `notes`, and a third state:+/// removal is a state change, never a delete, so a credit keeps the identifier+/// and simply does not show it, and adding the name again restores the same+/// identity (Decision 4).+///+/// A seeded role's `positionModifiedAt` is the pristine sentinel, so a reader's+/// reorder on another device — which stamps every shifted role — beats it in the+/// fold.+@Model+public final class CreatorRole {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The reader's order, 0-based over the active roles. It is also the first+ /// key a work's credits are ordered by (Q10).+ 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)+ /// `max(nameModifiedAt, positionModifiedAt, stateModifiedAt)`.+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ name: String = "",+ position: Int = 0,+ stateRaw: String = "active",+ canonicalID: UUID? = nil,+ timestamp: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.name = name+ self.position = position+ self.stateRaw = stateRaw+ self.canonicalID = canonicalID+ createdAt = timestamp+ modifiedAt = timestamp+ nameModifiedAt = timestamp+ positionModifiedAt = timestamp+ stateModifiedAt = timestamp+ }+}++/// V12: one work-and-creator pairing, carrying the roles that creator holds on+/// that work (`work-creators` Decision 6).+///+/// The shape is `WorkLink`'s: plain UUID columns rather than relationships, so a+/// credit outlives the absence of the work, the creator or any role it names —+/// which is the tolerated unresolved state the sync rules are written around,+/// not damage. Nothing prunes a row for naming an absent target.+///+/// `roleIDs` is a plain SwiftData `[String]` on the `genreTags` shape, holding+/// role identifiers as `uuidString`. It is **`[String]` rather than `[UUID]` on+/// purpose** (Q47): every array column this CloudKit-mirrored schema carries is+/// `[String]`, and a `[UUID]` array would be the first of its kind under+/// mirroring. It is stored sorted and deduplicated at every write, so equal sets+/// are equal arrays; an entry that does not parse as a UUID is ignored on read.+@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)+ /// Stamped when the role set changes. The dedupe over a duplicated pair+ /// keeps the *earliest* created row rather than the latest modified one+ /// (Q42), so this is the archive guard rather than the survivor key.+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ workID: UUID = UUID(),+ creatorID: UUID = UUID(),+ roleIDs: [String] = [],+ createdAt: Date = Date(timeIntervalSince1970: 0),+ modifiedAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.workID = workID+ self.creatorID = creatorID+ self.roleIDs = roleIDs+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// V13: one named place of one work — accepted from an extraction proposal or+/// created by hand (`place-extraction` Decision 3, Q3).+///+/// The shape is `Character`'s, field for field, because the two are one record+/// type to every piece of store code: `RecordRow` is written once and both+/// tables conform (Decision 3). What differs is the single column below.+///+/// **The owning work is a `UUID` column, not a relationship** — the `WorkCredit`+/// shape, and AGENTS.md's standing rule made a fourth time. An inverse would+/// fault every place of a work to answer a count, and a `.nullify` on an absent+/// target would erase a value that has to survive while the work is still in+/// transit. `workID` is non-optional and defaulted (Q44): the value is always+/// known at insert, and an orphan keeps the id it will re-attach by, so nothing+/// needs to be nullable. Orphan-ness is "no work resolves", never nil (Req 5.5).+///+/// `nameKey` is **retained**: minted once at accept or creation commit and never+/// re-derived from a rename, so a renamed place keeps attracting the proposals+/// that named it before. A place converted from a character carries the+/// character's retained key (Q34).+///+/// Every property is defaulted or optional and nothing is unique: this is a+/// CloudKit-mirrored table like the rest.+@Model+public final class Place {+ public var id: UUID = UUID()+ public var name: String = ""+ /// The key the place was accepted, created or converted under, retained+ /// through renames. Normalised by `RecordNameKey.normalize`.+ public var nameKey: String = ""+ /// Extra match keys, reader-editable and grown by the combine. Stored as the+ /// reader's spellings; matching normalises.+ public var aliases: [String] = []+ public var note: String = ""+ /// `[RecordFact]` in the canonical encoding. Optional rather than+ /// defaulted-empty because CloudKit materialises a missing column as nil,+ /// and "no facts yet" and "column not synced" are the same thing to a+ /// reader.+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The Work this place belongs to, by identifier. A value naming no Work is+ /// a **tolerated** orphan: displayed nowhere, never validated, exported+ /// as-is, and found by the predicate the moment the work arrives (Req 5.5).+ public var workID: UUID = UUID()++ /// Every parameter defaulted, so memberwise construction and the stored+ /// defaults are the same value CloudKit would materialise.+ public init(+ id: UUID = UUID(),+ name: String = "",+ nameKey: String = "",+ aliases: [String] = [],+ note: String = "",+ facts: [RecordFact] = [],+ timestamp: Date = Date(timeIntervalSince1970: 0),+ workID: UUID = UUID()+ ) {+ self.id = id+ self.name = name+ self.nameKey = nameKey+ self.aliases = aliases+ self.note = note+ factsData = RecordFactCodec.encode(facts)+ createdAt = timestamp+ modifiedAt = timestamp+ self.workID = workID+ }++ // `facts` is `RecordRow`'s (RecordRow.swift): the decode is the same for+ // every record table, so it is written once rather than per model.+}++/// V13: one remembered decision not to re-propose a **place**+/// (`place-extraction` Decision 2).+///+/// A separate record type rather than a record-kind column on+/// `CharacterSuppression`, because both configurations mirror to CloudKit and a+/// pre-feature build sharing the container cannot see a new column: to that+/// build a place suppression would be a character suppression with the same+/// converging tuple, and accepting a character would *clear* it (Req 5.2). A+/// record type it does not know is ignored entirely.+///+/// A **system record**, like its character twin: it never tears, never blocks an+/// export, and converges to the reader's most recent action rather than by set+/// union. The two enum columns store the raw strings `CharacterSuppressionKind`+/// and `CharacterSuppressionStatus` spell — the enums are shared across kinds+/// (Q27) — and the defaults name those cases rather than restating their+/// spellings, exactly as `CharacterSuppression` does.+///+/// The work is a `UUID` column for `Place`'s reasons.+@Model+public final class PlaceSuppression {+ public var id: UUID = UUID()+ /// The Work this suppression belongs to, by identifier. An unresolved value+ /// is the same tolerated orphan `Place.workID` describes.+ public var workID: UUID = UUID()+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ /// Present on fact rows only; nil on candidate rows. Explicit rather than+ /// inferred from a nil `sourceEntryID`, so a malformed row is+ /// distinguishable from a generic-notes citation.+ public var sourceKindRaw: String?+ /// Set only where `sourceKind == .entry`.+ public var sourceEntryID: UUID?+ /// The fact's evidence span, on fact rows only. The third component of the+ /// identity triple.+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ /// When the reader acted. The comparable convergence needs.+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ workID: UUID = UUID(),+ kind: CharacterSuppressionKind = .candidate,+ nameKey: String = "",+ source: SourceRef? = nil,+ evidence: String? = nil,+ status: CharacterSuppressionStatus = .active,+ actionAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.workID = workID+ kindRaw = kind.rawValue+ self.nameKey = nameKey+ sourceKindRaw = source?.kindRaw+ sourceEntryID = source?.entryID+ self.evidence = evidence+ statusRaw = status.rawValue+ self.actionAt = actionAt+ }++ /// An unknown raw value reads as `.candidate`, matching every other enum+ /// column in this schema: unrecognised data is tolerated, not corruption.+ public var kind: CharacterSuppressionKind {+ get { ToleratedEnum.read(kindRaw, default: .candidate) }+ set { kindRaw = newValue.rawValue }+ }++ public var status: CharacterSuppressionStatus {+ get { ToleratedEnum.read(statusRaw, default: .active) }+ set { statusRaw = newValue.rawValue }+ }++ /// The cited source on a fact row, or nil on a candidate row — and nil for a+ /// malformed row, which is why `sourceKindRaw` is stored explicitly.+ public var source: SourceRef? {+ get { SourceRef(kindRaw: sourceKindRaw, entryID: sourceEntryID) }+ set {+ sourceKindRaw = newValue?.kindRaw+ sourceEntryID = newValue?.entryID+ }+ }+}++} // extension AsterismSchemaV23++extension AsterismSchemaV23.TitlePattern: MarkableRule {+ var isMarked: Bool { isActive }+}++extension AsterismSchemaV23.URLRulePattern: MarkableRule {+ var isMarked: Bool { isCurrent }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV24.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV24.swiftnew file mode 100644index 00000000..6be816f2--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV24.swift@@ -0,0 +1,117 @@+import Foundation+import SwiftData++/// Live V24 adds defaulted plain-text general notes and authored timestamps to groups.+/// V16–V23 are frozen snapshots; the V23→V24 stage is lightweight.+public enum AsterismSchemaV24: VersionedSchema {+ public static let versionIdentifier = Schema.Version(24, 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, ChapterCheckRecord.self]+ }+}++public enum AsterismV24MigrationPlan: SchemaMigrationPlan {+ public static var schemas: [any VersionedSchema.Type] {+ [AsterismSchemaV16.self, AsterismSchemaV17.self, AsterismSchemaV18.self,+ AsterismSchemaV19.self, AsterismSchemaV20.self, AsterismSchemaV21.self,+ AsterismSchemaV22.self, AsterismSchemaV23.self, AsterismSchemaV24.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),+ .lightweight(fromVersion: AsterismSchemaV22.self, toVersion: AsterismSchemaV23.self),+ .lightweight(fromVersion: AsterismSchemaV23.self, toVersion: AsterismSchemaV24.self)]+ }+}++extension AsterismSchemaV24 {+ @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 var note: String = ""+ public var noteModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public init(id: UUID = UUID(), workID: UUID, note: String = "",+ noteModifiedAt: Date = Date(timeIntervalSince1970: 0)) {+ self.id = id; self.workID = workID+ self.note = note; self.noteModifiedAt = noteModifiedAt+ }+ }++ @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 = AsterismSchemaV24.CharacterGroup+public typealias GroupFactEvent = AsterismSchemaV24.GroupFactEvent+public typealias GroupTransition = AsterismSchemaV24.GroupTransition
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swiftindex 242328c7..216db658 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift@@ -17,6 +17,7 @@ import OSLog /// upsert learning its envelope. public struct BackupImportPayload: Sendable, Equatable { public let groups: [GroupRawIdentity]+ public let groupNoteStates: [GroupRawV23NoteState] public let groupFacts: [GroupRawFact] public let groupTransitions: [GroupRawTransition] /// Raw chapter-check rows, exactly as archived; empty for every predecessor archive.@@ -68,12 +69,14 @@ public struct BackupImportPayload: Sendable, Equatable { workCaptureDefaults: [UUID: ChapterCaptureDefault] = [:], entrySources: [BackupV19EntrySource] = [], associationEvents: [AssociationRawEvent] = [], pairNoteVersions: [AssociationRawNote] = [],- groups: [GroupRawIdentity] = [], groupFacts: [GroupRawFact] = [],+ groups: [GroupRawIdentity] = [], groupNoteStates: [GroupRawV23NoteState] = [],+ groupFacts: [GroupRawFact] = [], groupTransitions: [GroupRawTransition] = [], checks: [ChapterCheckRawRecord] = [] ) { self.checks = checks self.groups = groups+ self.groupNoteStates = groupNoteStates self.groupFacts = groupFacts self.groupTransitions = groupTransitions self.associationEvents = associationEvents@@ -162,6 +165,19 @@ public struct BackupImportPayload: Sendable, Equatable { groups: payload.groups, groupFacts: payload.groupFacts, groupTransitions: payload.groupTransitions) }+ public init(_ payload: BackupV23Payload) {+ let base = BackupImportPayload(payload.predecessor)+ self.init(entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns,+ urlRules: base.urlRules, workTypes: base.workTypes, memberships: base.memberships,+ distinctPairs: base.distinctPairs, characters: base.characters, suppressions: base.suppressions,+ places: base.places, placeSuppressions: base.placeSuppressions, series: base.series,+ links: base.links, creators: base.creators, creatorRoles: base.creatorRoles, credits: base.credits,+ noEpisodeActions: base.noEpisodeActions, chapterEntries: base.chapterEntries,+ workCaptureDefaults: base.workCaptureDefaults, entrySources: base.entrySources,+ associationEvents: base.associationEvents, pairNoteVersions: base.pairNoteVersions,+ groups: base.groups, groupNoteStates: payload.groupNoteStates,+ groupFacts: base.groupFacts, groupTransitions: base.groupTransitions, checks: base.checks)+ } public init(_ payload: BackupV22Payload) { let base = BackupImportPayload(payload.predecessor) self.init(entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns,@@ -333,7 +349,7 @@ public enum BackupImporter { /// constants, so the accepted pair moves with the generation rather than /// being restated here. private static let supportedVersions = (- format: BackupV22Document.formatVersion, schema: BackupV22Document.schemaVersion+ format: BackupV23Document.formatVersion, schema: BackupV23Document.schemaVersion ) // MARK: - Plan Dispatch (Req 5.1, 5.2, Decision 2)@@ -346,7 +362,7 @@ public enum BackupImporter { let (formatVersion, schemaVersion) = try detectVersions(data) logger.debug("Detected format=\(formatVersion) schema=\(schemaVersion)") - let supported = [supportedVersions, (21, 22), (20, 21), (19, 20), (18, 19)]+ let supported = [supportedVersions, (22, 23), (21, 22), (20, 21), (19, 20), (18, 19)] guard supported.contains(where: { $0 == (formatVersion, schemaVersion) }) else { // The pair is named, always. An older archive was restorable until // its read path was retired, so a reader meeting this has done@@ -365,9 +381,9 @@ public enum BackupImporter { } private static func planFromArchive(_ data: Data) throws -> BackupImportPlan {- let compatible: CompatibleBackupV22Document+ let compatible: CompatibleBackupV23Document do {- compatible = try BackupV22Codec.decodeCompatible(data)+ compatible = try BackupV23Codec.decodeCompatible(data) } catch { throw BackupImportError.decodingFailed(reason: String(describing: error)) }@@ -380,6 +396,9 @@ public enum BackupImporter { case .current(let document): payload = BackupImportPayload(document.payload) metadata = Self.metadata(of: document)+ case .v22(let document):+ payload = BackupImportPayload(document.payload)+ metadata = Self.metadata(of: document) case .v21(let document): payload = BackupImportPayload(document.payload) metadata = Self.metadata(of: document)@@ -398,6 +417,11 @@ public enum BackupImporter { metadata: metadata, payload: payload, counts: counts) } + private static func metadata(of document: BackupV23Document) -> BackupImportMetadata {+ BackupImportMetadata(formatVersion: document.backupFormatVersion, schemaVersion: document.databaseSchemaVersion,+ appBuild: document.appBuild, exportedAt: document.exportedAt, capabilityGate: document.capabilityGate,+ entryCount: document.entryCount, workCount: document.workCount)+ } private static func metadata(of document: BackupV22Document) -> BackupImportMetadata { BackupImportMetadata(formatVersion: document.backupFormatVersion, schemaVersion: document.databaseSchemaVersion, appBuild: document.appBuild, exportedAt: document.exportedAt, capabilityGate: document.capabilityGate,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV23Codec.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV23Codec.swiftnew file mode 100644index 00000000..0b294b81--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV23Codec.swift@@ -0,0 +1,175 @@+import Foundation++/// Current archive codec; released predecessor codecs remain frozen.+public enum BackupV23Codec {+ /// Pinned literally. 23/24 ships at the multi-site gate; group notes add+ /// persisted data without changing the runtime capability set. A future+ /// capability or archive generation cannot retroactively change this value.+ static let gate = "multi-site"++ /// The generation this codec speaks, as it appears in decode diagnostics.+ static let label = "V23"++ // 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 `BackupV23Document.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: BackupV23Payload,+ 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: BackupV23Document.formatVersion,+ capabilityGate: Self.gate,+ checksum: checksum,+ databaseSchemaVersion: BackupV23Document.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++ /// Exact 23/24 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 -> BackupV23Document {+ do {+ let rootKeys = try DuplicateJSONKeyValidator.validate(data)+ try BackupArchiveShapeValidator.validate(rootKeys: rootKeys)++ let document = try BackupCanonicalJSON.decoder()+ .decode(BackupV23Document.self, from: data)++ guard document.backupFormatVersion == BackupV23Document.formatVersion else {+ throw BackupCodecError.invalidFormatVersion(document.backupFormatVersion)+ }+ guard document.databaseSchemaVersion == BackupV23Document.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)+ let identities = Set(document.payload.groups.map { "\($0.id.uuidString)/\($0.workID.uuidString)" })+ guard document.payload.groupNoteStates.allSatisfy({+ identities.contains("\($0.id.uuidString)/\($0.workID.uuidString)")+ }) else {+ throw BackupCodecError.decodingFailed(reason: "group note state has no matching group identity")+ }++ return document+ } catch let error as BackupCodecError { throw error } catch {+ throw BackupCodecError.decodingFailed(reason: String(describing: error))+ }+ }+}+++public enum CompatibleBackupV23Document: Sendable {+ case current(BackupV23Document)+ case v22(BackupV22Document)+ case v21(BackupV21Document)+ case v20(BackupV20Document)+ case v19(BackupV19Document)+ case v18(BackupV18Document)+ /// The payload in the current shape; a predecessor carries no checks.+ public var payload: BackupV23Payload {+ switch self {+ case .current(let document): document.payload+ case .v22(let document): .init(predecessor: document.payload)+ case .v21(let document): .init(predecessor: .init(predecessor: document.payload))+ case .v20(let document): .init(predecessor: .init(predecessor: .init(predecessor: document.payload)))+ case .v19(let document): .init(predecessor: .init(predecessor: .init(predecessor: .init(library: document.payload))))+ case .v18(let document):+ .init(predecessor: .init(predecessor: .init(predecessor: .init(library: .init(predecessor: document.payload)))))+ }+ }+}++extension BackupV23Codec {+ public static func decodeCompatible(_ data: Data) throws -> CompatibleBackupV23Document {+ 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 (23, 24): return .current(try decode(data))+ case (22, 23): return .v22(try BackupV22Codec.decode(data))+ case (21, 22): return .v21(try BackupV21Codec.decode(data))+ case (20, 21): return .v20(try BackupV20Codec.decode(data))+ case (19, 20): return .v19(try BackupV19Codec.decode(data))+ case (18, 19): return .v18(try BackupV18Codec.decode(data))+ default: throw BackupCodecError.invalidFormatVersion(versions.backupFormatVersion)+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV23Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV23Exporter.swiftnew file mode 100644index 00000000..bd905ae2--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV23Exporter.swift@@ -0,0 +1,102 @@+import Foundation+import SwiftData++public protocol BackupV23SnapshotProviding: Sendable {+ func backupV23Snapshot() async throws -> BackupV23Payload+}++extension LibraryRepository: BackupV23SnapshotProviding {+ public func backupV23Snapshot() async throws -> BackupV23Payload {+ let outcome: Result<BackupV23Payload, BackupV18ExportError> =+ try await withLockedBackupContext { context in+ do {+ let predecessor = try Self.projectV21Payload(context: context)+ let checks = try context.fetch(FetchDescriptor<ChapterCheckRecord>()).map(\.raw)+ .sorted(by: ChapterCheckRawRecord.archiveOrder)+ let base = BackupV22Payload(predecessor: predecessor, checks: checks)+ let notes = try context.fetch(FetchDescriptor<NamedCharacterGroup>())+ .map(GroupRawV23NoteState.init).sorted {+ if $0.id != $1.id { return $0.id.uuidString < $1.id.uuidString }+ if $0.workID != $1.workID { return $0.workID.uuidString < $1.workID.uuidString }+ if $0.modifiedAt != $1.modifiedAt { return $0.modifiedAt < $1.modifiedAt }+ return $0.note < $1.note+ }+ return .success(.init(predecessor: base, groupNoteStates: notes))+ } catch let error as BackupV18ExportError { return .failure(error) }+ }+ return try outcome.get()+ }+}++public final class BackupV23Exporter: Sendable {+ private let repository: any BackupV23SnapshotProviding+ private let stagingDirectory: URL++ public init(+ repository: any BackupV23SnapshotProviding,+ stagingDirectory: URL+ ) {+ self.repository = repository+ self.stagingDirectory = stagingDirectory+ }++ public func export(metadata: BackupV23Metadata) async throws -> BackupExportResult {+ let payload: BackupV23Payload+ do {+ payload = try await repository.backupV23Snapshot()+ } catch let error as BackupV18ExportError {+ throw error+ } catch {+ throw BackupV18ExportError.snapshotFailed(reason: String(describing: error))+ }++ let encoded: Data+ do {+ encoded = try BackupV23Codec.encode(payload: payload, metadata: metadata)+ } catch {+ throw BackupV18ExportError.encodingFailed(reason: String(describing: error))+ }++ do {+ let decoded = try BackupV23Codec.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\(BackupV23Document.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/BackupV23Types.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV23Types.swiftnew file mode 100644index 00000000..7b75d112--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV23Types.swift@@ -0,0 +1,50 @@+import Foundation++/// Archive 23/schema 24 adds authored group-note states while preserving every+/// predecessor payload and raw identity encoding.+public struct BackupV23Document: Codable, Equatable, Sendable {+ public static let formatVersion = 23+ public static let schemaVersion = 24+ 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: BackupV23Payload+ public init(appBuild: String, exportedAt: Date, capabilityGate: String,+ entryCount: Int, workCount: Int, checksum: String, payload: BackupV23Payload) {+ 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 BackupV23Metadata = BackupV19Metadata++/// Flat Codable composition: released V22 payload fields retain their original+/// shape, with one new array for current group-note variants.+public struct BackupV23Payload: Codable, Equatable, Sendable {+ public var predecessor: BackupV22Payload+ public var groupNoteStates: [GroupRawV23NoteState]+ public var library: BackupV19Payload { predecessor.library }+ public var groups: [GroupRawIdentity] { predecessor.groups }+ public var groupFacts: [GroupRawFact] { predecessor.groupFacts }+ public var groupTransitions: [GroupRawTransition] { predecessor.groupTransitions }+ public init(predecessor: BackupV22Payload, groupNoteStates: [GroupRawV23NoteState] = []) {+ self.predecessor = predecessor; self.groupNoteStates = groupNoteStates+ }+ private enum CodingKeys: String, CodingKey { case groupNoteStates }+ public init(from decoder: any Decoder) throws {+ predecessor = try BackupV22Payload(from: decoder)+ let container = try decoder.container(keyedBy: CodingKeys.self)+ groupNoteStates = try container.decode([GroupRawV23NoteState].self, forKey: .groupNoteStates)+ }+ public func encode(to encoder: any Encoder) throws {+ try predecessor.encode(to: encoder)+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(groupNoteStates, forKey: .groupNoteStates)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ChapterCheckModels.swift b/Packages/AsterismCore/Sources/AsterismCore/ChapterCheckModels.swiftindex 542af34e..32c221c0 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ChapterCheckModels.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ChapterCheckModels.swift@@ -1,9 +1,9 @@ import Foundation import SwiftData -public typealias ChapterCheckRecord = AsterismSchemaV23.ChapterCheckRecord+public typealias ChapterCheckRecord = AsterismSchemaV24.ChapterCheckRecord -extension AsterismSchemaV23 {+extension AsterismSchemaV24 { /// One immutable chapter-check row: a complete grounded outcome, or a review /// receipt. Relationship-free, defaulted, never unique and never deleted by a /// sync-side sweep; an orphan simply stays unusable. The compact header is a
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupImportPreparation.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupImportPreparation.swiftindex 4fd9febe..d5a44475 100644--- a/Packages/AsterismCore/Sources/AsterismCore/GroupImportPreparation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupImportPreparation.swift@@ -7,13 +7,25 @@ enum GroupImportPreparation { context: ModelContext) throws { var existingGroups = Set(try context.fetch(FetchDescriptor<NamedCharacterGroup>()) .map(GroupRawIdentity.init))+ var existingNoteStates = Set(try context.fetch(FetchDescriptor<NamedCharacterGroup>())+ .map(GroupRawV23NoteState.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 {+ // A V23 archive carries the legacy identity projection and the authored+ // note variants for the same physical rows. Insert the note-bearing row+ // once, rather than creating a blank identity twin alongside it.+ let noteIdentities = Set(payload.groupNoteStates.map {+ "\($0.id.uuidString)/\($0.workID.uuidString)"+ })+ for raw in payload.groups where existingGroups.insert(raw).inserted &&+ !noteIdentities.contains("\(raw.id.uuidString)/\(raw.workID.uuidString)") { context.insert(NamedCharacterGroup(raw: raw)) }+ for raw in payload.groupNoteStates where existingNoteStates.insert(raw).inserted {+ context.insert(NamedCharacterGroup(rawNoteState: raw))+ } for raw in payload.groupFacts where existingFacts.insert(raw).inserted { context.insert(GroupFactEvent(raw: raw)) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupRawRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupRawRecords.swiftindex a7f89477..f0083627 100644--- a/Packages/AsterismCore/Sources/AsterismCore/GroupRawRecords.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupRawRecords.swift@@ -11,6 +11,26 @@ public struct GroupRawIdentity: Codable, Hashable, Sendable { } } ++/// V23 archive extension for authored group-note state. Kept separate from the+/// released GroupRawIdentity encoding so predecessor payload checksums remain stable.+public struct GroupRawV23NoteState: Codable, Hashable, Sendable {+ public let id: UUID+ public let workID: UUID+ public let note: String+ public let modifiedAtBits: UInt64+ public init(id: UUID, workID: UUID, note: String, modifiedAt: Date) {+ self.id = id; self.workID = workID; self.note = note+ modifiedAtBits = modifiedAt.timeIntervalSinceReferenceDate.bitPattern+ }+ public init(_ row: NamedCharacterGroup) {+ self.init(id: row.id, workID: row.workID, note: row.note, modifiedAt: row.noteModifiedAt)+ }+ public var modifiedAt: Date {+ Date(timeIntervalSinceReferenceDate: Double(bitPattern: modifiedAtBits))+ }+}+ public struct GroupRawFact: Codable, Hashable, Sendable { public let id: UUID public let workID: UUID@@ -44,6 +64,9 @@ public struct GroupRawTransition: Codable, Hashable, Sendable { extension NamedCharacterGroup { convenience init(raw: GroupRawIdentity) { self.init(id: raw.id, workID: raw.workID) }+ convenience init(rawNoteState raw: GroupRawV23NoteState) {+ self.init(id: raw.id, workID: raw.workID, note: raw.note, noteModifiedAt: raw.modifiedAt)+ } } extension GroupFactEvent {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupRoster.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupRoster.swiftindex 980f7120..a8c58734 100644--- a/Packages/AsterismCore/Sources/AsterismCore/GroupRoster.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupRoster.swift@@ -67,6 +67,8 @@ public struct MembershipRange: Codable, Equatable, Sendable { public struct GroupSummary: Codable, Equatable, Sendable { public let groupID: UUID public let name: String?+ public let note: String+ public let noteModifiedAt: Date public let aliases: [String] public let members: [UUID: [MembershipRange]] public let factEventIDs: [UUID]@@ -75,12 +77,34 @@ public struct GroupSummary: Codable, Equatable, Sendable { /// 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] = [],+ private enum CodingKeys: String, CodingKey {+ case groupID, name, note, noteModifiedAt, aliases, members, factEventIDs+ case transitions, conflictedTransitions, transitionEventIDs+ }+ public init(from decoder: any Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ groupID = try container.decode(UUID.self, forKey: .groupID)+ name = try container.decodeIfPresent(String.self, forKey: .name)+ // Legacy pending edits have no note keys. They decode to pristine state;+ // CharacterGroupDraft's optional note separately preserves "not edited".+ note = try container.decodeIfPresent(String.self, forKey: .note) ?? ""+ noteModifiedAt = try container.decodeIfPresent(Date.self, forKey: .noteModifiedAt)+ ?? Date(timeIntervalSince1970: 0)+ aliases = try container.decode([String].self, forKey: .aliases)+ members = try container.decode([UUID: [MembershipRange]].self, forKey: .members)+ factEventIDs = try container.decode([UUID].self, forKey: .factEventIDs)+ transitions = try container.decode([GroupTransitionFact].self, forKey: .transitions)+ conflictedTransitions = try container.decode([GroupTransitionConflict].self, forKey: .conflictedTransitions)+ transitionEventIDs = try container.decode([UUID: [UUID]].self, forKey: .transitionEventIDs)+ }+ public init(groupID: UUID, name: String?, note: String = "",+ noteModifiedAt: Date = Date(timeIntervalSince1970: 0), aliases: [String] = [], members: [UUID: [MembershipRange]] = [:], factEventIDs: [UUID] = [], transitions: [GroupTransitionFact] = [], conflictedTransitions: [GroupTransitionConflict] = [], transitionEventIDs: [UUID: [UUID]] = [:]) {- self.groupID = groupID; self.name = name; self.aliases = aliases+ self.groupID = groupID; self.name = name; self.note = note+ self.noteModifiedAt = noteModifiedAt; self.aliases = aliases self.members = members; self.factEventIDs = factEventIDs; self.transitions = transitions self.conflictedTransitions = conflictedTransitions self.transitionEventIDs = transitionEventIDs
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupRosterStorage.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupRosterStorage.swiftindex 9adbc87b..056f3622 100644--- a/Packages/AsterismCore/Sources/AsterismCore/GroupRosterStorage.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupRosterStorage.swift@@ -98,7 +98,10 @@ extension GroupRoster { 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,+ let noteState = electedNoteState(groupRows.filter { $0.id == group.groupID })+ return GroupSummary(groupID: group.groupID, name: group.name,+ note: noteState.note, noteModifiedAt: noteState.modifiedAt,+ aliases: group.aliases, members: group.members.filter { !quarantinedMembers[group.groupID, default: []].contains($0.key) },@@ -128,4 +131,21 @@ extension GroupRoster { unresolvedSpellings: projected.unresolvedSpellings, disputedMembers: disputedMembers) }++ /// Elect one authored note independent of SwiftData fetch order. Epoch rows+ /// represent the schema default and cannot override authored state.+ private static func electedNoteState(_ rows: [NamedCharacterGroup])+ -> (note: String, modifiedAt: Date) {+ let epoch = Date(timeIntervalSince1970: 0)+ let authored = rows.filter { $0.noteModifiedAt > epoch }+ let candidates = authored.isEmpty ? rows : authored+ let winner = candidates.max {+ if $0.noteModifiedAt != $1.noteModifiedAt {+ return $0.noteModifiedAt < $1.noteModifiedAt+ }+ return $0.note < $1.note+ }+ return (winner?.note ?? "", winner?.noteModifiedAt ?? epoch)+ }+ }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupWorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupWorkMerge.swiftindex 2d7e2b57..0d871011 100644--- a/Packages/AsterismCore/Sources/AsterismCore/GroupWorkMerge.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupWorkMerge.swift@@ -90,7 +90,7 @@ enum GroupWorkMerge { } let destinationID = UUID() context.insert(NamedCharacterGroup(id: destinationID,- workID: targetWorkID))+ workID: targetWorkID, note: summary.note, noteModifiedAt: summary.noteModifiedAt)) let inheritedFactIDs = sourceFacts.filter { $0.groupID == summary.groupID } .map(\.id) let create = GroupFact(groupID: destinationID, workID: targetWorkID,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swiftindex d8f435cc..c29a44ae 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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 69aa3441..e7e47d50 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift@@ -170,13 +170,13 @@ public extension LibraryRepository { return Certification(result: .ready(counts), diagnostics: diagnostics) case .markerLagging(let generation):- // Convert the supported V16–V18 schemas, validate, then publish 19.- // V19 adds only an optional Work blob, so existing rows retain nil.+ // Convert any supported predecessor through V24, validate, then publish 24.+ // V24 adds optional note state with deterministic epoch defaults. // A failure leaves the previous marker and residual evidence intact. let container = try openCertificationContainer(configuration, hooks: hooks) let context = ModelContext(container) bootstrapLogger.debug(- "Marker generation \(generation, privacy: .public) is lagging; certifying the V19 conversion")+ "Marker generation \(generation, privacy: .public) is lagging; certifying the V24 conversion") let diagnostics = try validateStore(context: context) try publishReadiness(at: configuration.readinessMarkerURL) clearResidualEvidence(configuration)@@ -394,7 +394,7 @@ extension LibraryRepository { at storeURL: URL, mirroring cloudKitDatabase: ModelConfiguration.CloudKitDatabase = .none ) throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let storeConfiguration = ModelConfiguration( // **Frozen persisted state (Req 3.5).** This names the store // configuration *inside* the container, not the file — `url:` below is@@ -408,7 +408,7 @@ extension LibraryRepository { ) return try ModelContainer( for: schema,- migrationPlan: AsterismV23MigrationPlan.self,+ migrationPlan: AsterismV24MigrationPlan.self, configurations: [storeConfiguration] ) }@@ -561,7 +561,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", "21", "22", extensionOpenableMarkerVersion,+ laggingOpenableMarkerVersion, "17", "18", "19", "20", "21", "22", "23", extensionOpenableMarkerVersion, ] /// The one lagging generation the app still opens: a library certified by a@@ -574,7 +574,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 = "23"+ static let extensionOpenableMarkerVersion = "24" // 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.swiftindex 7b35c1b2..451778c3 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CharacterGroups.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CharacterGroups.swift@@ -32,6 +32,7 @@ public struct GroupSuggestionApproval: Sendable, Equatable { public enum GroupEditOperation: Sendable, Equatable { case create(groupID: UUID, name: String) case fact(groupID: UUID, expectedEventIDs: [UUID], operation: GroupFactOperation)+ case note(groupID: UUID, expectedNote: String, expectedModifiedAt: Date, value: String) case transition(rootID: UUID, groupID: UUID, characterID: UUID, chapterID: UUID, action: GroupTransitionAction) case reviseTransition(rootID: UUID, expectedEventIDs: [UUID],@@ -241,18 +242,6 @@ extension LibraryRepository { 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):@@ -286,8 +275,8 @@ extension LibraryRepository { } } 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) }+ if approval.action == .leave &&+ (names.isEmpty || approval.characterName == nil) { return refuse(.stale) } let resolvedGroupID: UUID if let existing = names.first { if approval.characterName == nil { return refuse(.stale) }@@ -360,6 +349,14 @@ extension LibraryRepository { operation: .create(name: name)), recordedAt: timestamp) context.insert(row); context.insert(fact) groupRows.append(row); factRows.append(fact); created.append(groupID)+ case .note(let groupID, let expectedNote, let expectedModifiedAt, let value):+ let basis = GroupNoteEditBasis(workID: workID,+ groupRows: groupRows, factRows: factRows,+ transitionRows: transitionRows,+ timestamp: timestamp)+ if let refusal = applyGroupNoteEdit(basis: basis, groupID: groupID,+ expectedNote: expectedNote, expectedModifiedAt: expectedModifiedAt,+ value: value, validateGroup: validateGroup) { return refuse(refusal) } case .fact(let groupID, let expected, let factOperation): guard case .create = factOperation else { if let refusal = validateGroup(groupID) { return refuse(refusal) }@@ -388,7 +385,10 @@ extension LibraryRepository { 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) }+ if let refusal = try validateGroupEditMember(workID: workID,+ characterID: characterID, chapterID: chapterID, context: context) {+ 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)@@ -444,7 +444,8 @@ extension LibraryRepository { return refuse(.stale) } if let refusal = validateGroup(groupID) { return refuse(refusal) }- if let refusal = try validateMember(characterID, chapterID: chapterID) {+ if let refusal = try validateGroupEditMember(workID: workID,+ characterID: characterID, chapterID: chapterID, context: context) { return refuse(refusal) } touchedChapters.formUnion(chain.filter { $0.workID == workID }.map(\.chapterID))
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupNoteWrites.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupNoteWrites.swiftnew file mode 100644index 00000000..ded7ba7a--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+GroupNoteWrites.swift@@ -0,0 +1,57 @@+import Foundation+import SwiftData++struct GroupNoteEditBasis {+ let workID: UUID+ let groupRows: [NamedCharacterGroup]+ let factRows: [GroupFactEvent]+ let transitionRows: [GroupTransition]+ let timestamp: Date+}++func applyGroupNoteEdit(+ basis: GroupNoteEditBasis,+ groupID: UUID,+ expectedNote: String,+ expectedModifiedAt: Date,+ value: String,+ validateGroup: (UUID) -> GroupEditRefusal?+) -> GroupEditRefusal? {+ let rows = basis.groupRows.filter { $0.id == groupID }+ guard !rows.isEmpty else { return .groupGone }+ if let refusal = validateGroup(groupID) { return refusal }+ let summary = GroupRoster.project(workID: basis.workID, chapters: [],+ groupRows: rows, factRows: basis.factRows, transitionRows: basis.transitionRows)+ .groups.first { $0.groupID == groupID }+ guard let summary else { return .groupTorn }+ if summary.note == value { return nil }+ guard summary.note == expectedNote && summary.noteModifiedAt == expectedModifiedAt else {+ return .stale+ }+ let nextTimestamp = max(basis.timestamp, expectedModifiedAt.addingTimeInterval(0.001))+ for row in rows where row.workID == basis.workID {+ row.note = value+ row.noteModifiedAt = MillisecondInstant.quantize(nextTimestamp)+ }+ return nil+}++extension LibraryRepository {+ func validateGroupEditMember(+ workID: UUID,+ characterID: UUID,+ chapterID: UUID,+ context: ModelContext+ ) 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+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Models.swift b/Packages/AsterismCore/Sources/AsterismCore/Models.swiftindex a065eaeb..7c959193 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 V22's, nested inside `AsterismSchemaV23`+// The live model classes are V24's, nested inside `AsterismSchemaV24` // (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 = AsterismSchemaV23.Entry-public typealias Work = AsterismSchemaV23.Work-public typealias Site = AsterismSchemaV23.Site-public typealias TitlePattern = AsterismSchemaV23.TitlePattern-public typealias URLRulePattern = AsterismSchemaV23.URLRulePattern-public typealias WorkTypeEntity = AsterismSchemaV23.WorkTypeEntity+public typealias Entry = AsterismSchemaV24.Entry+public typealias Work = AsterismSchemaV24.Work+public typealias Site = AsterismSchemaV24.Site+public typealias TitlePattern = AsterismSchemaV24.TitlePattern+public typealias URLRulePattern = AsterismSchemaV24.URLRulePattern+public typealias WorkTypeEntity = AsterismSchemaV24.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 = AsterismSchemaV23.WorkSiteMembership+public typealias WorkSiteMembership = AsterismSchemaV24.WorkSiteMembership /// V8: a reader's "not the same work" over an unordered pair of Works (Q20).-public typealias WorkDistinctPair = AsterismSchemaV23.WorkDistinctPair+public typealias WorkDistinctPair = AsterismSchemaV24.WorkDistinctPair /// V11: a reader-named, ordered collection a Work belongs to at most once /// (`series-and-related-works` Decision 1).-public typealias Series = AsterismSchemaV23.Series+public typealias Series = AsterismSchemaV24.Series /// V11: an undirected, typed connection between two distinct Works /// (`series-and-related-works` Decision 5).-public typealias WorkLink = AsterismSchemaV23.WorkLink+public typealias WorkLink = AsterismSchemaV24.WorkLink /// V12: a person a work is credited to, a reader-managed directory record /// (`work-creators` Decision 2).-public typealias Creator = AsterismSchemaV23.Creator+public typealias Creator = AsterismSchemaV24.Creator /// V12: one entry in the ordered role list credits reference by identity /// (`work-creators` Decision 1).-public typealias CreatorRole = AsterismSchemaV23.CreatorRole+public typealias CreatorRole = AsterismSchemaV24.CreatorRole /// V12: one work-and-creator pairing, carrying the roles that creator holds on /// that work (`work-creators` Decision 6).-public typealias WorkCredit = AsterismSchemaV23.WorkCredit+public typealias WorkCredit = AsterismSchemaV24.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 = AsterismSchemaV23.Character-public typealias CharacterSuppression = AsterismSchemaV23.CharacterSuppression+public typealias CharacterRecord = AsterismSchemaV24.Character+public typealias CharacterSuppression = AsterismSchemaV24.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 = AsterismSchemaV23.Place+public typealias Place = AsterismSchemaV24.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 = AsterismSchemaV23.PlaceSuppression-public typealias EntrySource = AsterismSchemaV23.EntrySource-public typealias NoEpisodeAction = AsterismSchemaV23.NoEpisodeAction+public typealias PlaceSuppression = AsterismSchemaV24.PlaceSuppression+public typealias EntrySource = AsterismSchemaV24.EntrySource+public typealias NoEpisodeAction = AsterismSchemaV24.NoEpisodeAction /// The presentation-enum tolerance policy for the **model accessors**, in one /// place (Q2).@@ -137,7 +137,7 @@ enum JSONBlob { } } -extension AsterismSchemaV23 {+extension AsterismSchemaV24 { @Model public final class Entry {@@ -1770,7 +1770,7 @@ public final class PlaceSuppression { } } -} // extension AsterismSchemaV23+} // extension AsterismSchemaV24 /// 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/ShareWorkContext.swift b/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swiftindex 3efe4a13..83fac337 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift@@ -19,8 +19,8 @@ import SwiftData private let shareWorkContextLogger = Logger( subsystem: "AsterismCore", category: "ShareWorkContext") -/// One character of a work on a capture sheet: what to call them, what else-/// they are called, and what the reader wrote down about them.+/// One character or group of a work on a capture sheet: what to call them,+/// what else they are called, and what the reader wrote down about them. /// /// No facts (Q2). A fact cites an entry anywhere in the work, including chapters /// ahead of the one being shared, and the sheet has no spoiler boundary to keep@@ -34,8 +34,9 @@ public struct ShareCharacter: Sendable, Equatable, Identifiable { /// In the order `RecordAuthoredContent` holds them, which is sorted at /// construction — the order the work page shows too. public let aliases: [String]- /// The note the work page shows for this character, trimmed of surrounding- /// whitespace by the read; `""` where there is none.+ /// The authored general note. Character notes are trimmed of surrounding+ /// whitespace by the existing read; group notes retain their exact text.+ /// `""` where there is no note. public let note: String public let memberships: [String] @@ -294,11 +295,13 @@ extension LibraryRepository { 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())+ let memberships = group.members.compactMap { id, ranges in+ characterNames[id].map { GroupMembershipText.membership(name: $0, ranges: ranges) }+ }.sorted()+ return ShareCharacter(id: group.groupID, name: group.name ?? "Unresolved group", aliases: group.aliases,+ note: group.note,+ // This is roster presentation, not authored general-note text.+ memberships: memberships.isEmpty && group.members.isEmpty ? ["No members"] : memberships) } // Bucketed once, for both halves: the index below is one input per // logical entry, and the last-note selection walks the same buckets to
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationGroupSupportTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationGroupSupportTests.swiftindex 1d759851..2503e74c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationGroupSupportTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationGroupSupportTests.swift@@ -154,7 +154,7 @@ struct AssociationGroupSupportTests { @Test("A group-only pair passes the real endpoint gate only with saved complete evidence") func groupOnlyEndpoint() throws {- let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let container = try ModelContainer(for: schema, configurations: [ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)]) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationSelectionSupportTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationSelectionSupportTests.swiftindex 39c0dddc..203b0336 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationSelectionSupportTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationSelectionSupportTests.swift@@ -47,7 +47,7 @@ struct AssociationSelectionSupportTests { @Test("Independent membership still requires coherent live endpoints") func coherentEndpoints() throws {- let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let container = try ModelContainer(for: schema, configurations: [ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)]) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swiftindex 30652f98..025beede 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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 1bd7c793..4be0b159 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift@@ -898,7 +898,7 @@ struct BackupExportDegradedRefusalTests { metadata: BackupV18Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch)) let decoded = try BackupV18Codec.decode(encoded) - let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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 62912150..095d917f 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismV23MigrationPlan.self,+ migrationPlan: AsterismV24MigrationPlan.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -715,7 +715,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV23MigrationPlan.self,+ migrationPlan: AsterismV24MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -758,7 +758,7 @@ private func createReadySiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -767,7 +767,7 @@ private func createReadySiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV23MigrationPlan.self,+ migrationPlan: AsterismV24MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -802,7 +802,7 @@ private func createReadyDuplicateSiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -811,7 +811,7 @@ private func createReadyDuplicateSiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV23MigrationPlan.self,+ migrationPlan: AsterismV24MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swiftindex 934d3c67..04b96fa1 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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("(\(BackupV22Document.formatVersion)/\(BackupV22Document.schemaVersion))"))+ #expect(reason.contains("(\(BackupV23Document.formatVersion)/\(BackupV23Document.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swiftindex ff05c0d4..d50d041c 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("(22/23)"))+ #expect(reason.contains("(23/24)")) // 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 f1692902..54a17fc6 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() == "23",+ #expect(try root.markerText() == "24", "a crash between store creation and the marker is repaired, not terminal") withExtendedLifetime(root) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swiftindex 64abaf48..20a4ac90 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("23\n")+ try root.writeMarker("24\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("23\n")+ try root.writeMarker("24\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("23\n")+ try root.writeMarker("24\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("23\n")+ case .twenty: try root.writeMarker("24\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 2500f631..9fccb71f 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 = "23\n"+private let readyMarkerBytes = "24\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 f3c51082..d82b7861 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("(22/23)"))+ #expect(reason.contains("(23/24)")) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swiftindex cc88de78..c9336eb9 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) == ["23.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["24.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) == "23",+ #expect(try markerContent(cfg) == "24", "an empty store has nothing to bring forward and is certified at birth (Q26)") withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCheckMarkerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCheckMarkerTests.swiftindex e1083e59..825fda4b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCheckMarkerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCheckMarkerTests.swift@@ -7,14 +7,14 @@ import Testing /// opening every retained generation; the extension opens only the current one. @Suite("Chapter check readiness generation") struct ChapterCheckMarkerTests {- @Test("The extension opens only marker 23 and publishReadiness writes it")- func extensionOpensOnlyTwentyThree() {- #expect(LibraryRepository.extensionOpenableMarkerVersion == "23")+ @Test("The extension opens only marker 24 and publishReadiness writes it")+ func extensionOpensOnlyTwentyFour() {+ #expect(LibraryRepository.extensionOpenableMarkerVersion == "24") } - @Test("The app still opens every retained generation 16 through 23")+ @Test("The app still opens every retained generation 16 through 24") func appOpensRetainedGenerations() {- let expected = Set((16...23).map(String.init))+ let expected = Set((16...24).map(String.init)) #expect(LibraryRepository.appOpenableMarkerVersions == expected) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCheckMigrationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCheckMigrationTests.swiftindex d9f29f23..ba7bd67d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCheckMigrationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCheckMigrationTests.swift@@ -81,8 +81,8 @@ struct ChapterCheckMigrationTests { #expect(identities.7 == seeded.pairNote) #expect(identities.8 == 0, "no check is fabricated from old coverage") await repository.shutdown()- #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "23\n")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["23.0.0"])+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "24\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["24.0.0"]) } @Test("A converted store saves, reopens and keeps a large external payload byte for byte")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swiftindex 912ee3fc..fc7ea224 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(AsterismSchemaV23.models),+ let container = try ModelContainer(for: Schema(AsterismSchemaV24.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 6513480d..cf856115 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swift@@ -213,7 +213,7 @@ private struct ChapterIdentityFixture { let container: ModelContainer let context: ModelContext init() throws {- let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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 fb908bac..146b2cf4 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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) == "23\n")+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "24\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 da372e09..11b25e4e 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swiftindex a195b9c2..c19f501b 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) let container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.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 210a5e52..cad97ca6 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swiftindex 7d6f933c..7585cc4a 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swiftindex de83dab1..af166e3e 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swiftindex 88d0c13a..047e2cdb 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.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 53f055d0..ce10fcee 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swiftindex 6679174b..80f124fe 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift@@ -74,9 +74,9 @@ struct FrozenLibraryPathTests { /// /// The *digit* advances with each marker generation — `configurable-work-types` /// 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 = "23\n"+ /// `"7"` (Q80), and it now reads `"24"`, a two-character generation. What is+ /// frozen is the shape and the filename beside it.+ private static let markerContents = "24\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@@ -305,19 +305,22 @@ struct FrozenLibraryPathTests { /// current generation. let declaresAStoreSchemaOrMarkerGeneration: Set<String> = [ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20",- "AsterismSchemaV21", "AsterismSchemaV22", "AsterismSchemaV23",+ "AsterismSchemaV21", "AsterismSchemaV22", "AsterismSchemaV23", "AsterismSchemaV24", "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "AsterismV19MigrationPlan", "AsterismV20MigrationPlan",- "AsterismV21MigrationPlan", "AsterismV22MigrationPlan", "AsterismV23MigrationPlan",+ "AsterismV21MigrationPlan", "AsterismV22MigrationPlan", "AsterismV23MigrationPlan", "AsterismV24MigrationPlan", "atOrAboveV5", "belowV5", "firstV5Major", ]- /// Current archive 22/23 and the released 21/22, 20/21, 19/20 and 18/19 shapes+ /// Current archive 23/24 and released predecessor 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> = [- // 22/23 adds the raw chapter-check array to the 21/22 payload. The lowercase- // cases name the predecessor archive each compatible document wraps.- "v18", "v19", "v20", "v21",+ // 23/24 adds current group-note states; 22/23 remains an immutable predecessor.+ "v18", "v19", "v20", "v21", "v22",+ "BackupV23Codec", "BackupV23Document", "BackupV23Exporter",+ "BackupV23Metadata", "BackupV23Payload", "BackupV23SnapshotProviding",+ "CompatibleBackupV23Document", "backupV23Snapshot",+ "GroupRawV23NoteState", "BackupV22Codec", "BackupV22Document", "BackupV22Exporter", "BackupV22Metadata", "BackupV22Payload", "BackupV22SnapshotProviding", "CompatibleBackupV22Document", "backupV22Snapshot", "projectV21Payload",@@ -398,25 +401,25 @@ struct FrozenLibraryPathTests { #expect( declared.sorted() == [ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20",- "AsterismSchemaV21", "AsterismSchemaV22", "AsterismSchemaV23",+ "AsterismSchemaV21", "AsterismSchemaV22", "AsterismSchemaV23", "AsterismSchemaV24", ], "the package declares versioned schemas \(declared); Req 3.3 allows only ones a plan references") - let referenced = AsterismV23MigrationPlan.schemas.map { String(describing: $0) }+ let referenced = AsterismV24MigrationPlan.schemas.map { String(describing: $0) } #expect( referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20",- "AsterismSchemaV21", "AsterismSchemaV22", "AsterismSchemaV23"],+ "AsterismSchemaV21", "AsterismSchemaV22", "AsterismSchemaV23", "AsterismSchemaV24"], "the plan references \(referenced), which is not the set of declared schemas") // Retain every released snapshot and its lightweight transition.- // V22 → V23 adds the initially empty chapter-check table.+ // V22 → V23 adds checks; V23 → V24 adds group-note fields. #expect(- AsterismV23MigrationPlan.stages.count == 7,- "the retained V16 → V23 chain has seven lightweight migrations")+ AsterismV24MigrationPlan.stages.count == 8,+ "the retained V16 → V24 chain has eight 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(- AsterismSchemaV23.versionIdentifier == Schema.Version(23, 0, 0),+ AsterismSchemaV24.versionIdentifier == Schema.Version(24, 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 77aa9380..984bd3eb 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupNoteShareContextTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupNoteShareContextTests.swiftnew file mode 100644index 00000000..d95fe994--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupNoteShareContextTests.swift@@ -0,0 +1,43 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Group notes in capture context", .serialized)+struct GroupNoteShareContextTests {+ private static let workID = UUID(uuidString: "A1000000-0000-4000-8000-000000000001")!++ @Test("A group note stays separate from the empty-roster message")+ func groupNoteAndEmptyRosterStaySeparate() async throws {+ let fixture = try await M5Fixture()+ let groupID = UUID()+ let note = " A patient crew.\nKeeps the lamp. "+ let authoredAt = Date(timeIntervalSince1970: 5_000)+ try await fixture.repository.seedM5Rows(+ sites: [M5SeedSite(hostname: "group-note.example")],+ works: [M5SeedWork(id: Self.workID, displayTitle: "The Watch",+ hostname: "group-note.example")])+ let result = try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding shareable group note") { context in+ context.insert(NamedCharacterGroup(id: groupID, workID: Self.workID,+ note: note, noteModifiedAt: authoredAt))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: Self.workID, operation: .create(name: "The Watch")), recordedAt: authoredAt))+ try context.save()+ return try LibraryRepository.shareWorkContext(forWorkID: Self.workID,+ currentChapterSequence: nil, currentChapterTitle: nil, context: context)+ }++ let group = try #require(result.groups.first { $0.id == groupID })+ let spoken = ShareCharacterChips.detailLabel(for: group)+ #expect(group.note == note, "Authored whitespace and line breaks reach the card unchanged")+ #expect(group.memberships == ["No members"], "Empty-roster copy remains a separate field")+ #expect(spoken.contains(note))+ #expect(spoken.contains("No members"))+ #expect(!group.note.contains("No members"), "Roster copy is never authored note text")+ #expect(!spoken.contains(ShareCharacterChips.emptyDetailText),+ "A note-bearing group with an empty roster does not look like an empty character card")+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swiftindex 21e7589e..1e66c2dd 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swiftindex c3a22fb4..694d8889 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swiftindex e7055f72..b70a1544 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swiftindex f08edf38..593822cd 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swiftindex b40ace92..9b8a945b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift@@ -387,7 +387,7 @@ private struct LookupCaptureFixture { _ seed: (ModelContext, String) -> Void ) throws -> LookupCaptureFixture { let url = "https://example.com/chapter-1"- let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swiftindex b18e0b31..401b9303 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) == "23",+ #expect(try markerContent(cfg) == "24", "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) == "23", "and the open leaves the marker as it found it")+ #expect(try markerContent(cfg) == "24", "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) == "23",+ #expect(try markerContent(cfg) == "24", "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) == "23")+ #expect(try markerContent(cfg) == "24") 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, "23\n")+ try writeMarker(cfg, "24\n") _ = try await LibraryRepository.openForExtension(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["23.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["24.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 fef09b81..5f2e5ffd 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("23\n")+ try root.writeMarker("24\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() == "23")+ #expect(try root.markerText() == "24") #expect(try V4RecordedStoreFixture.recordedModelVersions(at: root.configuration.storeURL)- == ["23.0.0"], "the store the arm opened is recorded at the version it converted to")+ == ["24.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() == "23")+ #expect(try root.markerText() == "24") withExtendedLifetime(root) {} } @@ -187,7 +187,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("expected the retry to reach a ready library, got \(result)") return }- #expect(try root.markerText() == "23")+ #expect(try root.markerText() == "24") withExtendedLifetime(root) {} } @@ -224,7 +224,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("a diagnosable library must still open, got \(result)") return }- #expect(try root.markerText() == "23")+ #expect(try root.markerText() == "24") #expect(quarantined != nil, "the broken title rule quarantines its hostname, as on V15") withExtendedLifetime(root) {} }@@ -306,7 +306,7 @@ struct MarkerGenerationSeventeenTests { try root.seedV16Library() let (_, repository) = try await LibraryRepository.openForApp(root.configuration) await repository.shutdown()- #expect(try root.markerText() == "23")+ #expect(try root.markerText() == "24") 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 a1154d75..c08bd163 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swiftindex fdd81d61..58d2da77 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swiftindex ec9d42cc..7ed68523 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 == "23")+ #expect(call.markerVersion == "24") #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 == "23")+ #expect(log.calls.first?.markerVersion == "24") #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 == "23")+ #expect(log.calls.first?.markerVersion == "24") #expect(await repository.mirroring.isMirroring) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swiftindex 25b6b408..b6a62b75 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(AsterismSchemaV23.models.map { String(describing: $0) })+ let declared = Set(AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) var propertiesByEntity: [String: Set<String>] = [:] for entity in schema.entities { propertiesByEntity[entity.name, default: []]@@ -799,7 +799,7 @@ struct ModelContractTests { declaringSnapshots.sorted() == [ "AsterismSchemaV16.swift", "AsterismSchemaV17.swift", "AsterismSchemaV18.swift", "AsterismSchemaV19.swift", "AsterismSchemaV20.swift",- "AsterismSchemaV21.swift", "AsterismSchemaV22.swift", "AsterismSchemaV23.swift",+ "AsterismSchemaV21.swift", "AsterismSchemaV22.swift", "AsterismSchemaV23.swift", "AsterismSchemaV24.swift", ], """ the package declares versioned schemas in \(declaringSnapshots.sorted()); \@@ -1116,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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swiftindex b1434688..d34eb4fc 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift@@ -127,7 +127,7 @@ struct MultiSiteReadPathTests { "AsterismSchemaV16.swift", "AsterismSchemaV17Models.swift", "AsterismSchemaV18Models.swift", "AsterismSchemaV19Models.swift", // Frozen V20 declares the same stored relationship/blob, with no live accessor. "AsterismSchemaV20Models.swift", "AsterismSchemaV21Models.swift",- "AsterismSchemaV22Models.swift",+ "AsterismSchemaV22Models.swift", "AsterismSchemaV23Models.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",@@ -211,12 +211,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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupArchiveTests.swiftindex f8da86bc..2955ca74 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupArchiveTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupArchiveTests.swift@@ -5,6 +5,75 @@ import Testing @Suite("Named group archive", .serialized) struct NamedGroupArchiveTests {+ @Test func v23ArchiveRoundTripsAuthoredGroupNotesAndCannotClearLocalEdits() async throws {+ #expect(BackupV23Document.formatVersion == 23)+ #expect(BackupV23Document.schemaVersion == AsterismSchemaV24.versionIdentifier.major)+ #expect(BackupV23Codec.gate == AsterismCapabilities.current.gate.rawValue)+ let source = try await M5Fixture()+ let workID = UUID(), groupID = UUID()+ let authoredAt = Date(timeIntervalSince1970: 2_000)+ let note = " Unicode 雪\nsecond line "+ try await source.repository.withLockedContext(mode: .exclusive,+ operation: "seeding current group note archive") { context in+ context.insert(Work(id: workID, displayTitle: "Notes", timestamp: authoredAt))+ context.insert(NamedCharacterGroup(id: groupID, workID: workID,+ note: note, noteModifiedAt: authoredAt))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID, workID: workID,+ operation: .create(name: "Readers")), recordedAt: authoredAt))+ try context.save()+ }+ let payload = try await source.repository.backupV23Snapshot()+ #expect(payload.groupNoteStates.count == 1)+ #expect(payload.groupNoteStates.first?.note == note)+ let data = try BackupV23Codec.encode(payload: payload,+ metadata: .init(appBuild: "tests", exportedAt: authoredAt))+ #expect(try BackupV23Codec.decode(data).payload == payload)+ let plan = try BackupImporter.plan(from: data)+ #expect(plan.payload.groupNoteStates == payload.groupNoteStates)+ let restored = try await M5Fixture()+ func currentRawNoteStates() async throws -> [GroupRawV23NoteState] {+ try await restored.repository.withLockedContext(mode: .shared,+ operation: "reading raw imported group-note variants") { context in+ try context.fetch(FetchDescriptor<NamedCharacterGroup>(predicate: #Predicate {+ $0.id == groupID+ })).map { GroupRawV23NoteState($0) }.sorted {+ if $0.note != $1.note { return $0.note < $1.note }+ return $0.modifiedAtBits < $1.modifiedAtBits+ }+ }+ }+ _ = try await restored.repository.confirmImport(plan: plan)+ _ = try await restored.repository.confirmImport(plan: plan)+ var group = try #require(try await restored.repository.characterGroups(workID: workID).first)+ #expect(group.note == note)+ let localEdit = "Local edit survives an older export"+ let edit = GroupEditOperation.note(groupID: groupID, expectedNote: group.note,+ expectedModifiedAt: group.noteModifiedAt, value: localEdit)+ #expect(try await restored.repository.commitGroupEdits(workID: workID,+ operations: [edit]) == .committed(groupIDs: []))+ _ = try await restored.repository.confirmImport(plan: plan)+ let firstEditImport = try await currentRawNoteStates()+ _ = try await restored.repository.confirmImport(plan: plan)+ let secondEditImport = try await currentRawNoteStates()+ #expect(firstEditImport == secondEditImport,+ "Repeating an older exact variant after a local edit adds no further copies")+ group = try #require(try await restored.repository.characterGroups(workID: workID).first)+ #expect(group.note == localEdit)+ #expect(try await restored.repository.commitGroupEdits(workID: workID, operations: [+ .note(groupID: groupID, expectedNote: group.note,+ expectedModifiedAt: group.noteModifiedAt, value: "")+ ]) == .committed(groupIDs: []))+ _ = try await restored.repository.confirmImport(plan: plan)+ let firstClearImport = try await currentRawNoteStates()+ _ = try await restored.repository.confirmImport(plan: plan)+ let secondClearImport = try await currentRawNoteStates()+ #expect(firstClearImport == secondClearImport,+ "Repeating an older exact variant after a local clear adds no further copies")+ group = try #require(try await restored.repository.characterGroups(workID: workID).first)+ #expect(group.note.isEmpty, "An older archive cannot clear an authored local clear")+ withExtendedLifetime((source, restored)) {}+ }+ @Test func predecessorArchiveImportsWithNoInventedGroupRows() async throws { let source = try await M5Fixture() let predecessor = try await source.repository.backupV20Snapshot()@@ -17,6 +86,89 @@ struct NamedGroupArchiveTests { withExtendedLifetime(source) {} } + @Test("V23 archive retains every physical group-note variant")+ func v23ArchivePreservesPhysicalNoteVariants() async throws {+ let source = try await M5Fixture()+ let workID = UUID(), groupID = UUID()+ let first = GroupRawV23NoteState(id: groupID, workID: workID,+ note: "earlier note", modifiedAt: Date(timeIntervalSince1970: 1_000))+ let second = GroupRawV23NoteState(id: groupID, workID: workID,+ note: "later note", modifiedAt: Date(timeIntervalSince1970: 2_000))+ try await source.repository.withLockedContext(mode: .exclusive,+ operation: "seeding physical note variants for archive") { context in+ context.insert(Work(id: workID, displayTitle: "Variants", timestamp: M5Fixture.epoch))+ context.insert(NamedCharacterGroup(rawNoteState: first))+ context.insert(NamedCharacterGroup(rawNoteState: second))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID, workID: workID,+ operation: .create(name: "Readers")), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let payload = try await source.repository.backupV23Snapshot()+ #expect(payload.groupNoteStates.count == 2)+ #expect(Set(payload.groupNoteStates) == Set([first, second]))+ let bytes = try BackupV23Codec.encode(payload: payload,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ #expect(try BackupV23Codec.decode(bytes).payload == payload)+ let plan = try BackupImporter.plan(from: bytes)+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: plan)+ func states() async throws -> Set<GroupRawV23NoteState> {+ try await restored.repository.withLockedContext(mode: .shared,+ operation: "reading restored physical note variants") { context in+ Set(try context.fetch(FetchDescriptor<NamedCharacterGroup>(predicate: #Predicate {+ $0.id == groupID+ })).map(GroupRawV23NoteState.init))+ }+ }+ #expect(try await states() == Set([first, second]))+ #expect(try await restored.repository.characterGroups(workID: workID).first?.note == "later note")+ _ = try await restored.repository.confirmImport(plan: plan)+ #expect(try await states() == Set([first, second]))+ withExtendedLifetime((source, restored)) {}+ }++ @Test("Legacy archive imports never replace an authored note or clear")+ func legacyArchivePreservesLocalNoteAndClear() async throws {+ let source = try await M5Fixture()+ let workID = UUID(), groupID = UUID()+ try await source.repository.withLockedContext(mode: .exclusive,+ operation: "seeding V22 group identity") { context in+ context.insert(Work(id: workID, displayTitle: "Legacy", timestamp: M5Fixture.epoch))+ context.insert(NamedCharacterGroup(id: groupID, workID: workID,+ note: "not in V22", noteModifiedAt: Date(timeIntervalSince1970: 4_000)))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID, workID: workID,+ operation: .create(name: "Readers")), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let oldPayload = try await source.repository.backupV22Snapshot()+ let bytes = try BackupV22Codec.encode(payload: oldPayload,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let plan = try BackupImporter.plan(from: bytes)+ #expect(plan.payload.groupNoteStates.isEmpty)+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: plan)+ var group = try #require(try await restored.repository.characterGroups(workID: workID).first)+ #expect(group.note.isEmpty && group.noteModifiedAt == Date(timeIntervalSince1970: 0))+ let authored = "Local V24 note"+ #expect(try await restored.repository.commitGroupEdits(workID: workID, operations: [+ .note(groupID: groupID, expectedNote: group.note,+ expectedModifiedAt: group.noteModifiedAt, value: authored)+ ]) == .committed(groupIDs: []))+ _ = try await restored.repository.confirmImport(plan: plan)+ _ = try await restored.repository.confirmImport(plan: plan)+ group = try #require(try await restored.repository.characterGroups(workID: workID).first)+ #expect(group.note == authored)+ #expect(try await restored.repository.commitGroupEdits(workID: workID, operations: [+ .note(groupID: groupID, expectedNote: group.note,+ expectedModifiedAt: group.noteModifiedAt, value: "")+ ]) == .committed(groupIDs: []))+ _ = try await restored.repository.confirmImport(plan: plan)+ _ = try await restored.repository.confirmImport(plan: plan)+ group = try #require(try await restored.repository.characterGroups(workID: workID).first)+ #expect(group.note.isEmpty && group.noteModifiedAt > Date(timeIntervalSince1970: 0))+ withExtendedLifetime((source, restored)) {}+ }+ @Test func currentArchiveRoundTripsGroupFactsAndTransitions() async throws { #expect(BackupV21Document.schemaVersion == AsterismSchemaV22.versionIdentifier.major) #expect(BackupV21Document.formatVersion == 21)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteInvarianceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteInvarianceTests.swiftnew file mode 100644index 00000000..e9242e6d--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteInvarianceTests.swift@@ -0,0 +1,89 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group note derived-state invariance", .serialized)+struct NamedGroupNoteInvarianceTests {+ private struct IDs {+ let work = UUID(), group = UUID(), character = UUID(), entry = UUID()+ }++ private func fixture() async throws -> (M5Fixture, IDs) {+ let fixture = try await M5Fixture()+ let ids = IDs()+ try await fixture.repository.withLockedContext(mode: .exclusive,+ operation: "seeding note-invariance group and 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: "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: 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))+ 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("A note-only edit leaves recognition links history and AI input unchanged")+ func noteOnlyEditLeavesDerivedStateUnchanged() async throws {+ let (fixture, ids) = try await fixture()+ let repository = fixture.repository+ let baselineHistory = try await repository.reconcileGroupHistory()+ #expect(baselineHistory.scannedChapterIDs == [ids.entry])+ let baselineGroup = try #require(try await repository.characterGroups(workID: ids.work).first)+ let baselineLinks = try await repository.chapterAssociations(entryID: ids.entry)+ let baselineCandidate = try #require(try await repository.extractionCandidates(limit: 100)+ .first { $0.workID == ids.work })++ func assertDerivedStateMatchesBaseline(_ expectedNote: String) async throws -> GroupSummary {+ let current = try #require(try await repository.characterGroups(workID: ids.work).first)+ #expect(current.name == baselineGroup.name)+ #expect(current.aliases == baselineGroup.aliases)+ #expect(current.members == baselineGroup.members)+ #expect(current.factEventIDs == baselineGroup.factEventIDs)+ #expect(current.transitions == baselineGroup.transitions)+ #expect(current.transitionEventIDs == baselineGroup.transitionEventIDs)+ #expect(current.note == expectedNote)+ #expect(try await repository.chapterAssociations(entryID: ids.entry) == baselineLinks)+ let candidate = try #require(try await repository.extractionCandidates(limit: 100)+ .first { $0.workID == ids.work })+ #expect(candidate == baselineCandidate,+ "Group-note text must not change recognition, extraction or AI inputs")+ let history = try await repository.reconcileGroupHistory()+ #expect(history.batchSizes.isEmpty && history.associationSaves == 0+ && history.scannedChapterIDs.isEmpty,+ "A note-only change must leave completed historical processing intact")+ return current+ }++ let authored = "General note only"+ #expect(try await repository.commitGroupEdits(workID: ids.work, operations: [+ .note(groupID: ids.group, expectedNote: baselineGroup.note,+ expectedModifiedAt: baselineGroup.noteModifiedAt, value: authored)+ ]) == .committed(groupIDs: []))+ var current = try await assertDerivedStateMatchesBaseline(authored)+ #expect(try await repository.commitGroupEdits(workID: ids.work, operations: [+ .note(groupID: ids.group, expectedNote: current.note,+ expectedModifiedAt: current.noteModifiedAt, value: "")+ ]) == .committed(groupIDs: []))+ current = try await assertDerivedStateMatchesBaseline("")+ #expect(current.noteModifiedAt > baselineGroup.noteModifiedAt)+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteMergeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteMergeTests.swiftnew file mode 100644index 00000000..f8492e20--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteMergeTests.swift@@ -0,0 +1,30 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Named group note merges", .serialized)+struct NamedGroupNoteMergeTests {+ @Test("Work merge carries the elected note to the destination group")+ func mergePreservesNote() async throws {+ let fixture = try await M5Fixture()+ let repository = fixture.repository+ let source = try await repository.createWork(.init(displayTitle: "Source", hostname: "example.com"))+ let target = try await repository.createWork(.init(displayTitle: "Target", hostname: "example.com"))+ let groupID = UUID()+ let authoredAt = Date(timeIntervalSince1970: 2_000)+ try await repository.withLockedContext(mode: .exclusive,+ operation: "seeding a note-bearing source group") { context in+ context.insert(NamedCharacterGroup(id: groupID, workID: source.id,+ note: "Keep this", noteModifiedAt: authoredAt))+ context.insert(try GroupFactEvent(fact: .init(groupID: groupID,+ workID: source.id, operation: .create(name: "Readers")), recordedAt: authoredAt))+ try context.save()+ }+ let preview = try await repository.projectMerge(sourceWorkID: source.id, targetWorkID: target.id)+ #expect(try await repository.commitMerge(preview) == .committed(targetID: target.id))+ let group = try #require(try await repository.characterGroups(workID: target.id).first)+ #expect(group.note == "Keep this")+ #expect(group.noteModifiedAt == authoredAt)+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteWriteTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteWriteTests.swiftnew file mode 100644index 00000000..1e3ad7dc--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupNoteWriteTests.swift@@ -0,0 +1,135 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Named group note writes", .serialized)+struct NamedGroupNoteWriteTests {+ @Test("Note writes guard their basis and remain independent of names")+ func guardedNoteEdit() async throws {+ let fixture = try await M5Fixture()+ let repository = fixture.repository+ let work = try await repository.createWork(.init(displayTitle: "Notes", hostname: "example.com"))+ let groupID = UUID()+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .create(groupID: groupID, name: "Readers")+ ]) == .committed(groupIDs: [groupID]))+ let initial = try #require(try await repository.characterGroups(workID: work.id).first)+ let authored = " Unicode 雪\nsecond line "+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .note(groupID: groupID, expectedNote: initial.note,+ expectedModifiedAt: initial.noteModifiedAt, value: authored)+ ]) == .committed(groupIDs: []))+ let saved = try #require(try await repository.characterGroups(workID: work.id).first)+ #expect(saved.note == authored)+ #expect(saved.noteModifiedAt > initial.noteModifiedAt)+ #expect(saved.factEventIDs == initial.factEventIDs)+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .fact(groupID: groupID, expectedEventIDs: saved.factEventIDs,+ operation: .addAlias("The Readers"))+ ]) == .committed(groupIDs: []))+ let aliased = try #require(try await repository.characterGroups(workID: work.id).first)+ #expect(aliased.name == saved.name && aliased.aliases == ["The Readers"])+ #expect(aliased.note == authored && aliased.noteModifiedAt == saved.noteModifiedAt)+ #expect(aliased.factEventIDs.count == saved.factEventIDs.count + 1)+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .fact(groupID: groupID, expectedEventIDs: aliased.factEventIDs,+ operation: .setName("Renamed"))+ ]) == .committed(groupIDs: []))+ let renamed = try #require(try await repository.characterGroups(workID: work.id).first)+ #expect(renamed.name == "Renamed" && renamed.aliases == ["The Readers"] && renamed.note == authored)+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .note(groupID: groupID, expectedNote: initial.note,+ expectedModifiedAt: initial.noteModifiedAt, value: "stale overwrite")+ ]) == .refused(.stale))+ let timestamp = renamed.noteModifiedAt+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .note(groupID: groupID, expectedNote: authored,+ expectedModifiedAt: timestamp, value: authored)+ ]) == .committed(groupIDs: []))+ let noOp = try #require(try await repository.characterGroups(workID: work.id).first)+ #expect(noOp.note == authored && noOp.noteModifiedAt == timestamp)+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .note(groupID: groupID, expectedNote: authored,+ expectedModifiedAt: timestamp, value: "")+ ]) == .committed(groupIDs: []))+ let cleared = try #require(try await repository.characterGroups(workID: work.id).first)+ #expect(cleared.note.isEmpty && cleared.noteModifiedAt > timestamp)+ #expect(cleared.name == "Renamed")+ withExtendedLifetime(fixture) {}+ }++ @Test("Backwards and equal clocks fan out one authored state and replay safely",+ arguments: [10_000.0, 20_000.0])+ func nonNewerClockFansOutAndReplaysLostAcknowledgement(clockSeconds: Double) async throws {+ let clock = Date(timeIntervalSince1970: clockSeconds)+ let basisTime = Date(timeIntervalSince1970: 20_000)+ let fixture = try await M5Fixture(clock: FixedRepositoryClock(clock))+ let repository = fixture.repository+ let work = try await repository.createWork(.init(displayTitle: "Notes", hostname: "example.com"))+ let groupID = UUID()+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .create(groupID: groupID, name: "Readers")+ ]) == .committed(groupIDs: [groupID]))+ try await repository.withLockedContext(mode: .exclusive,+ operation: "adding duplicate authored group copies") { context in+ let first = try #require(context.fetch(FetchDescriptor<NamedCharacterGroup>()).first {+ $0.id == groupID+ })+ first.note = "Prior state"+ first.noteModifiedAt = basisTime+ context.insert(NamedCharacterGroup(id: groupID, workID: work.id,+ note: "Prior state", noteModifiedAt: basisTime))+ try context.save()+ }+ let initial = try #require(try await repository.characterGroups(workID: work.id).first)+ #expect(initial.note == "Prior state" && initial.noteModifiedAt == basisTime)+ let operation = GroupEditOperation.note(groupID: groupID,+ expectedNote: initial.note, expectedModifiedAt: basisTime,+ value: "Authored once")+ #expect(try await repository.commitGroupEdits(workID: work.id,+ operations: [operation]) == .committed(groupIDs: []))+ let first = try #require(try await repository.characterGroups(workID: work.id).first)+ #expect(first.note == "Authored once")+ #expect(first.noteModifiedAt == basisTime.addingTimeInterval(0.001))+ #expect(try await repository.commitGroupEdits(workID: work.id,+ operations: [operation]) == .committed(groupIDs: []),+ "A retry after a lost acknowledgement accepts already-saved desired state")+ let rows = try await repository.withLockedContext(mode: .shared,+ operation: "checking note fan-out and replay") { context in+ try context.fetch(FetchDescriptor<NamedCharacterGroup>(predicate: #Predicate {+ $0.id == groupID+ })).map(GroupRawV23NoteState.init)+ }+ #expect(rows.count == 2)+ #expect(rows.allSatisfy {+ $0.note == "Authored once" && $0.modifiedAt == first.noteModifiedAt+ })+ #expect(try await repository.characterGroups(workID: work.id).first?.noteModifiedAt == first.noteModifiedAt)+ withExtendedLifetime(fixture) {}+ }++ @Test("A tombstoned group cannot be revived by a note write")+ func noteWriteCannotReviveDeletedGroup() async throws {+ let fixture = try await M5Fixture()+ let repository = fixture.repository+ let work = try await repository.createWork(.init(displayTitle: "Notes", hostname: "example.com"))+ let groupID = UUID()+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .create(groupID: groupID, name: "Readers")+ ]) == .committed(groupIDs: [groupID]))+ let group = try #require(try await repository.characterGroups(workID: work.id).first)+ #expect(try await repository.commitGroupEdits(workID: work.id, operations: [+ .fact(groupID: groupID, expectedEventIDs: group.factEventIDs, operation: .delete)+ ]) == .committed(groupIDs: []))+ let deleted = try await repository.commitGroupEdits(workID: work.id, operations: [+ .note(groupID: groupID, expectedNote: group.note,+ expectedModifiedAt: group.noteModifiedAt, value: "Must remain deleted")+ ])+ if case .refused = deleted {} else {+ Issue.record("A note edit must refuse a deleted group's tombstone")+ }+ #expect(try await repository.characterGroups(workID: work.id).isEmpty)+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupStorageTests.swiftindex 69e39cca..c2518755 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupStorageTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NamedGroupStorageTests.swift@@ -6,7 +6,7 @@ import Testing @Suite("Named group physical storage", .serialized) struct NamedGroupStorageTests { private func context() throws -> (ModelContainer, ModelContext) {- let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let container = try ModelContainer(for: schema, configurations: [ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)]) return (container, ModelContext(container))@@ -36,6 +36,45 @@ struct NamedGroupStorageTests { withExtendedLifetime(container) {} } + @Test("Duplicate group rows elect authored notes independent of fetch order")+ func noteElectionIsDeterministicAndWhitespacePreserving() throws {+ let (container, context) = try context()+ let work = UUID(), group = UUID(), timestamp = Date(timeIntervalSince1970: 100)+ context.insert(try GroupFactEvent(fact: .init(groupID: group, workID: work,+ operation: .create(name: "Notes")), recordedAt: timestamp))+ let emptyDefault = NamedCharacterGroup(id: group, workID: work)+ let older = NamedCharacterGroup(id: group, workID: work,+ note: "old", noteModifiedAt: timestamp)+ let tiedLower = NamedCharacterGroup(id: group, workID: work,+ note: "equal-a", noteModifiedAt: timestamp)+ let tiedWinner = NamedCharacterGroup(id: group, workID: work,+ note: "equal-z", noteModifiedAt: timestamp)+ let newest = NamedCharacterGroup(id: group, workID: work,+ note: " 線 one\nline two ", noteModifiedAt: timestamp.addingTimeInterval(1))+ let rows = [emptyDefault, older, tiedLower, tiedWinner, newest]+ let forward = GroupRoster.project(workID: work, chapters: [], groupRows: rows,+ factRows: try context.fetch(FetchDescriptor<GroupFactEvent>()), transitionRows: [])+ let reverse = GroupRoster.project(workID: work, chapters: [], groupRows: Array(rows.reversed()),+ factRows: try context.fetch(FetchDescriptor<GroupFactEvent>()), transitionRows: [])+ #expect(forward.groups.first?.note == " 線 one\nline two ")+ #expect(forward.groups.first?.noteModifiedAt == timestamp.addingTimeInterval(1))+ #expect(reverse.groups.first?.note == forward.groups.first?.note)+ #expect(reverse.groups.first?.noteModifiedAt == forward.groups.first?.noteModifiedAt)+ let tiedRows = [emptyDefault, tiedLower, tiedWinner, older]+ let tiedForward = GroupRoster.project(workID: work, chapters: [], groupRows: tiedRows,+ factRows: try context.fetch(FetchDescriptor<GroupFactEvent>()), transitionRows: [])+ let tiedReverse = GroupRoster.project(workID: work, chapters: [], groupRows: Array(tiedRows.reversed()),+ factRows: try context.fetch(FetchDescriptor<GroupFactEvent>()), transitionRows: [])+ #expect(tiedForward.groups.first?.note == "old")+ #expect(tiedReverse.groups.first?.note == "old")+ // With an exact timestamp tie, deterministic Swift string ordering elects the larger value.+ let authoredTie = GroupRoster.project(workID: work, chapters: [],+ groupRows: [tiedLower, tiedWinner],+ factRows: try context.fetch(FetchDescriptor<GroupFactEvent>()), transitionRows: [])+ #expect(authoredTie.groups.first?.note == "equal-z")+ withExtendedLifetime(container) {}+ }+ @Test("Divergent physical copies quarantine a fact and a transition") func conflictingTwins() throws { let (container, context) = try context()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swiftindex 47355941..9ccf777a 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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 ffa5cfbf..db8cffb8 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let container = try ModelContainer( for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)]) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swiftindex c4d91d6a..345df508 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) return try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swiftindex 4bea9cf0..63f8dbae 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.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 421d1e8a..494198d0 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swiftindex fbeba0a4..ca5ffce6 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) == ["23.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["24.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 6c28bdcd..26295aab 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift@@ -83,6 +83,7 @@ struct ThumbnailBytesReachTests { // Frozen V20 declares the same stored relationship/blob, with no live accessor. "AsterismSchemaV20Models.swift", "AsterismSchemaV21Models.swift", "AsterismSchemaV22Models.swift",+ "AsterismSchemaV23Models.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 32faf4a8..e2fc59d3 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: AsterismSchemaV23.self).entities.map(\.name))+ let live = Set(Schema(versionedSchema: AsterismSchemaV24.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 479a3d26..9058e7c5 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) container = try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swiftindex feb09507..de7009ab 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swiftindex d09880b0..84fbd902 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() == ["23.0.0"])- #expect(try root.markerText() == "23")+ #expect(try root.recordedVersions() == ["24.0.0"])+ #expect(try root.markerText() == "24") #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() == "23")- #expect(try root.recordedVersions() == ["23.0.0"])+ #expect(try root.markerText() == "24")+ #expect(try root.recordedVersions() == ["24.0.0"]) withExtendedLifetime(root) {} } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swiftindex 0cb1e94a..225b9e26 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) == "23\n")+ encoding: .utf8) == "24\n") #expect(try V4RecordedStoreFixture.recordedModelVersions(- at: configuration.storeURL) == ["23.0.0"])+ at: configuration.storeURL) == ["24.0.0"]) await repository.shutdown() }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swiftindex c8e876ec..922e8b22 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) == "23\n")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["23.0.0"])+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "24\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["24.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", "22", "23"])+ arguments: ["16", "17", "18", "19", "20", "21", "22", "23", "24"]) 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 == "23" ? .ready : .markerLagging(generation: marker)))- if marker != "23" {+ == (marker == "24" ? .ready : .markerLagging(generation: marker)))+ if marker != "24" { 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) == "23\n")+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "24\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 c7eda575..34d8058c 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) == "23\n")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["23.0.0"])+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "24\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["24.0.0"]) } @Test func schemaAddsOnlyTwoRelationshipFreeTables() throws {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V21GroupMigrationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V21GroupMigrationTests.swiftindex c0af06f7..15e1c217 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V21GroupMigrationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V21GroupMigrationTests.swift@@ -45,8 +45,8 @@ struct V21GroupMigrationTests { } #expect(counts.0 == 0 && counts.1 == 0 && counts.2 == 0) await repository.shutdown()- #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "23\n")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["23.0.0"])+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "24\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["24.0.0"]) } @Test func V22AddsOnlyThreeRelationshipFreeGroupTables() throws {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V23RecordedStoreFixture.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V23RecordedStoreFixture.swiftnew file mode 100644index 00000000..c529b8d8--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V23RecordedStoreFixture.swift@@ -0,0 +1,26 @@+import Foundation+import SwiftData+@testable import AsterismCore++/// Seeds the complete frozen V23 schema and releases its container before the+/// live V24 opener runs, avoiding SwiftData's process-global entity registry mix.+enum V23RecordedStoreFixture {+ static let workID = UUID(uuidString: "11111111-1111-1111-1111-111111111023")!+ static let groupID = UUID(uuidString: "22222222-2222-2222-2222-222222222023")!+ static let factID = UUID(uuidString: "33333333-3333-3333-3333-333333333023")!++ static func install(at url: URL) throws {+ let schema = Schema(versionedSchema: AsterismSchemaV23.self)+ let container = try ModelContainer(for: schema, configurations: [+ ModelConfiguration("AsterismV3", schema: schema, url: url, cloudKitDatabase: .none)])+ let context = ModelContext(container)+ let work = AsterismSchemaV23.Work(id: workID, displayTitle: "A populated V23 group", timestamp: Date(timeIntervalSince1970: 500))+ let group = AsterismSchemaV23.CharacterGroup(id: groupID, workID: workID)+ let fact = AsterismSchemaV23.GroupFactEvent(id: factID, workID: workID,+ groupID: groupID, payloadData: try JSONBlob.encode(GroupFactOperation.create(name: "V23 readers")),+ parentHeadIDsData: try JSONBlob.encode([UUID]()), recordedAt: Date(timeIntervalSince1970: 500))+ context.insert(work); context.insert(group); context.insert(fact)+ try context.save()+ withExtendedLifetime(container) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V23RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V23RecordedStoreTests.swiftnew file mode 100644index 00000000..f768bd6f--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V23RecordedStoreTests.swift@@ -0,0 +1,79 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("V23 to V24 group-note migration", .serialized)+struct V23RecordedStoreTests {+ private func propertyShapes(_ schema: Schema) -> [String: [String: String]] {+ var entities: [String: [String: String]] = [:]+ for entity in schema.entities {+ var shapes: [String: String] = [:]+ for attribute in entity.attributes {+ shapes[attribute.name] = """+ attribute \(attribute.valueType) optional=\(attribute.isOptional) \+ unique=\(attribute.isUnique) transient=\(attribute.isTransient) \+ options=\(attribute.options.map { String(describing: $0) }.sorted())+ """+ }+ for relationship in entity.relationships {+ shapes[relationship.name] = """+ relationship -> \(relationship.destination) \+ optional=\(relationship.isOptional) toOne=\(relationship.isToOneRelationship) \+ delete=\(relationship.deleteRule) inverse=\(relationship.inverseName ?? "none")+ """+ }+ entities[entity.name] = shapes+ }+ return entities+ }++ @Test("The app migrates populated V23 groups to pristine V24 note state")+ func populatedGroupReceivesEmptyDefault() async throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "GroupNotesV23-\(UUID())")+ defer { try? FileManager.default.removeItem(at: root) }+ let configuration = LibraryConfiguration(rootDirectory: root)+ try FileManager.default.createDirectory(at: configuration.storeURL.deletingLastPathComponent(),+ withIntermediateDirectories: true)+ try V23RecordedStoreFixture.install(at: configuration.storeURL)+ try Data("23\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic)+ await #expect(throws: Error.self) { try await LibraryRepository.openForExtension(configuration) }+ let (_, repository) = try await LibraryRepository.openForApp(configuration)+ let groups = try await repository.characterGroups(workID: V23RecordedStoreFixture.workID)+ #expect(groups.count == 1)+ #expect(groups.first?.name == "V23 readers")+ #expect(groups.first?.note == "")+ #expect(groups.first?.noteModifiedAt == Date(timeIntervalSince1970: 0))+ await repository.shutdown()+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "24\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["24.0.0"])+ }++ @Test("V24 adds only two defaulted group note columns")+ func schemaDeltaIsAdditive() throws {+ let previous = Schema(versionedSchema: AsterismSchemaV23.self)+ let live = Schema(versionedSchema: AsterismSchemaV24.self)+ #expect(Set(live.entities.map(\.name)) == Set(previous.entities.map(\.name)))+ for old in previous.entities {+ let next = try #require(live.entities.first { $0.name == old.name })+ let additions = Set(next.properties.map(\.name)).subtracting(old.properties.map(\.name))+ #expect(additions == Set(old.name == "CharacterGroup" ? ["note", "noteModifiedAt"] : []))+ }+ var normalizedLiveShapes = propertyShapes(live)+ normalizedLiveShapes["CharacterGroup"]?.removeValue(forKey: "note")+ normalizedLiveShapes["CharacterGroup"]?.removeValue(forKey: "noteModifiedAt")+ #expect(normalizedLiveShapes == propertyShapes(previous),+ "Every pre-existing V23 attribute and relationship must retain its stored shape")+ let group = try #require(live.entities.first { $0.name == "CharacterGroup" })+ let note = try #require(group.attributes.first { $0.name == "note" })+ let modifiedAt = try #require(group.attributes.first { $0.name == "noteModifiedAt" })+ #expect(note.valueType == String.self && !note.isOptional && !note.isUnique)+ #expect(modifiedAt.valueType == Date.self && !modifiedAt.isOptional && !modifiedAt.isUnique)+ let defaults = NamedCharacterGroup(workID: UUID())+ #expect(defaults.note.isEmpty)+ #expect(defaults.noteModifiedAt == Date(timeIntervalSince1970: 0))+ #expect(AsterismV24MigrationPlan.stages.count == 8)+ #expect(AsterismSchemaV23.versionIdentifier == Schema.Version(23, 0, 0))+ #expect(AsterismSchemaV24.versionIdentifier == Schema.Version(24, 0, 0))+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkDetailEditTransactionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkDetailEditTransactionTests.swiftindex 06b7c4e9..a6e9eb96 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkDetailEditTransactionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkDetailEditTransactionTests.swift@@ -64,6 +64,81 @@ struct WorkDetailEditTransactionTests { withExtendedLifetime(fixture) {} } + @Test("Work metadata and group name and note commit in one save")+ func metadataNameAndNoteCommitTogether() async throws {+ let saves = ArmableFailingSaveStrategy()+ let fixture = try await M5Fixture(saveStrategy: saves)+ let work = try await fixture.repository.createWork(+ .init(displayTitle: "Book", hostname: "group.example"))+ let groupID = UUID()+ #expect(try await fixture.repository.commitGroupEdits(workID: work.id, operations: [+ .create(groupID: groupID, name: "Readers")+ ]) == .committed(groupIDs: [groupID]))+ let group = try #require(try await fixture.repository.characterGroups(workID: work.id).first)+ saves.resetCount()+ let outcome = try await fixture.repository.commitWorkDetailEdit(.init(+ workID: work.id, metadata: metadata(work, notes: "Metadata moved together"),+ groupOperations: [+ .fact(groupID: groupID, expectedEventIDs: group.factEventIDs,+ operation: .setName("The Readers")),+ .note(groupID: groupID, expectedNote: group.note,+ expectedModifiedAt: group.noteModifiedAt, value: "General note")+ ]))+ guard case .committed = outcome else {+ Issue.record("Metadata/name/note transaction refused: \(outcome)")+ return+ }+ #expect(saves.saveCount == 1)+ let detail = try await fixture.repository.workDetail(id: work.id)+ let savedGroup = try #require(detail.characterGroups.first)+ #expect(detail.work.genericNotes == "Metadata moved together")+ #expect(savedGroup.name == "The Readers" && savedGroup.note == "General note")+ withExtendedLifetime(fixture) {}+ }++ @Test("Stale group note refuses earlier staged Work and group mutations")+ func staleNoteRollsBackEarlierMutations() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(+ .init(displayTitle: "Book", hostname: "group.example"))+ let groupID = UUID()+ #expect(try await fixture.repository.commitGroupEdits(workID: work.id, operations: [+ .create(groupID: groupID, name: "Readers")+ ]) == .committed(groupIDs: [groupID]))+ let original = try #require(try await fixture.repository.characterGroups(workID: work.id).first)+ #expect(try await fixture.repository.commitGroupEdits(workID: work.id, operations: [+ .note(groupID: groupID, expectedNote: original.note,+ expectedModifiedAt: original.noteModifiedAt, value: "Remote winner")+ ]) == .committed(groupIDs: []))+ let current = try #require(try await fixture.repository.characterGroups(workID: work.id).first)+ let recordID = UUID()+ let outcome = try await fixture.repository.commitWorkDetailEdit(.init(+ workID: work.id, metadata: metadata(work, notes: "Must roll back"),+ recordOperations: [.createIdentified(id: recordID,+ draft: .init(kind: .character, name: "Bjorn"))],+ groupOperations: [+ .fact(groupID: groupID, expectedEventIDs: current.factEventIDs,+ operation: .setName("Must also roll back")),+ .note(groupID: groupID, expectedNote: original.note,+ expectedModifiedAt: original.noteModifiedAt, value: "Stale draft")+ ]))+ #expect(outcome == .groupRefused(.stale))+ let live = try await fixture.repository.workDetail(id: work.id)+ #expect(live.work.genericNotes.isEmpty)+ #expect(live.characters.isEmpty)+ #expect(live.characterGroups.first?.name == "Readers")+ #expect(live.characterGroups.first?.note == "Remote winner")+ 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.first?.name == "Readers")+ #expect(disk.characterGroups.first?.note == "Remote winner")+ withExtendedLifetime((fixture, reopened)) {}+ }+ @Test("Late group refusal rolls back metadata and record edits") func lateRefusal() async throws { let fixture = try await M5Fixture()@@ -104,7 +179,11 @@ struct WorkDetailEditTransactionTests { _ = 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")],+ groupOperations: [+ .create(groupID: groupID, name: "Team Loser"),+ .note(groupID: groupID, expectedNote: "",+ expectedModifiedAt: Date(timeIntervalSince1970: 0), value: "Must roll back too")+ ], workURL: url)) Issue.record("Final save unexpectedly succeeded") } catch { }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swiftindex 4ab7b093..53851984 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swiftindex ca1ec864..a8daf54c 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swiftindex 06f0292b..48c4fc27 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swiftindex d468f5d1..1aeb60d6 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.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) == "23",+ #expect(try markerContent(cfg) == "24", "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) == "23", "the import republishes nothing")+ #expect(try markerContent(cfg) == "24", "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) == "23")+ #expect(try markerContent(cfg) == "24") try expectEveryRelationshipPopulated(cfg) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swiftindex 823a0718..a9886fc5 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: AsterismSchemaV23.self)+ let schema = Schema(versionedSchema: AsterismSchemaV24.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV23MigrationPlan.self,+ for: schema, migrationPlan: AsterismV24MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Users/arjen/projects/personal/asterism-worktrees/T-2516-group-notes/Asterism/AsterismTests/NoteRecordLegacyGroupRecoveryTests.swift b/Users/arjen/projects/personal/asterism-worktrees/T-2516-group-notes/Asterism/AsterismTests/NoteRecordLegacyGroupRecoveryTests.swiftnew file mode 100644index 00000000..a765b6d9--- /dev/null+++ b/Users/arjen/projects/personal/asterism-worktrees/T-2516-group-notes/Asterism/AsterismTests/NoteRecordLegacyGroupRecoveryTests.swift@@ -0,0 +1,50 @@+import AsterismCore+import Foundation+import Testing+@testable import Asterism++// Uses the suite's real-repository fixture without growing its main type body.+extension NoteRecordEditingSessionTests {+ @Test("Typing into a legacy recovered group adopts only the loaded note basis")+ func legacyGroupRecoveryKeepsLoadedNoteBasisThroughStaging() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: root) }+ let (library, entry, _) = try await fixture(root: root)+ let workID = try #require(entry.workID), groupID = UUID()+ _ = try await library.commitGroupEdits(workID: workID,+ operations: [.create(groupID: groupID, name: "Legacy group")], currentChapterID: entry.id)+ let basis = try #require(try await library.characterGroups(workID: workID).first)+ let legacy = CharacterGroupDraft(workID: workID, groupID: groupID, original: basis,+ name: "Legacy group", note: nil, aliases: "", transitions: [],+ conflictResolutions: [:], isDeleted: false)+ let item = NoteCastItem(id: .init(kind: .groups, id: groupID), name: "Legacy group", aliases: [], note: "")+ let store = PendingNoteEditStore(rootDirectory: root)+ let failed = PendingNoteEditRunner(store: store, commit: { .committed($0.basis) },+ commitSharedRecord: { _ in throw CocoaError(.fileWriteUnknown) })+ failed.stageSharedRecord(.group(legacy), entry: entry)+ let first = NoteRecordEditingSession(entry: entry, item: item, library: library, runner: failed)+ await first.load()+ #expect(!(await first.flush()))+ _ = try await library.commitGroupEdits(workID: workID,+ operations: [.note(groupID: groupID, expectedNote: basis.note,+ expectedModifiedAt: basis.noteModifiedAt, value: "Saved while pending")], currentChapterID: nil)+ let loaded = try #require(try await library.characterGroups(workID: workID).first)+ let runner = PendingNoteEditRunner(store: store, commit: { .committed($0.basis) },+ commitSharedRecord: { try await NoteSharedRecordWriter.commit($0, library: library) })+ let recovered = NoteRecordEditingSession(entry: entry, item: item, library: library, runner: runner)+ await recovered.load()+ let editor = try #require(recovered.groupEditor)+ #expect(editor.note == loaded.note)+ editor.note = "Replacement after recovery"+ guard case .group(let staged)? = runner.latestSharedRecord(targetID: groupID) else {+ Issue.record("Recovered typing must remain journaled")+ return+ }+ #expect(staged.original?.note == loaded.note)+ #expect(staged.original?.noteModifiedAt == loaded.noteModifiedAt)+ #expect(staged.original?.factEventIDs == basis.factEventIDs)+ #expect(await recovered.flush(retry: true))+ #expect(try await library.characterGroups(workID: workID).first?.note == "Replacement after recovery")+ }++}
diff --git a/AGENTS.md b/AGENTS.mdindex c8185f8a..4453bca0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -160,11 +160,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 V23** (`specs/chapter-ai-check-results/`), the readiness-marker generation is `"23"`, and the retained migration chain is V16 → V17 →-V18 → V19 → V20 → V21 → V22 → V23. V16–V22 are frozen snapshots; app markers 16–23 remain-accepted, while the extension opens only 23. The current archive generation-is **22/23**, with bounded conversion of predecessor 21/22, 20/21, 19/20 and 18/19 archives.+**The live store schema is V24** (`specs/group-notes/`), the readiness+marker generation is `"24"`, and the retained migration chain is V16 → V17 →+V18 → V19 → V20 → V21 → V22 → V23 → V24. V16–V23 are frozen snapshots; app markers 16–24 remain+accepted, while the extension opens only 24. The current archive generation+is **23/24**, with bounded conversion of predecessor 22/23, 21/22, 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. @@ -265,8 +265,8 @@ 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 the live `AsterismSchemaV23`. Frozen V16–V22 snapshots-remain beside it. The migration plan retains V16 → V23 with seven lightweight+are typealiases onto the live `AsterismSchemaV24`. Frozen V16–V23 snapshots+remain beside it. The migration plan retains V16 → V24 with eight 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`
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex df771323..1e9ef5e4 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/). ### Added +- **Group notes (T-2516):** preserve optional notes through additive V24 migration, backups and Work merges; guard stale edits and keep composite Work saves atomic. Support note editing and recovery in both group editors, and show saved notes in read-only Work, chapter and share cards without changing membership presentation.+ - **Saved chapter AI checks (T-2519):** retain complete synced results, including empty results, so unchanged chapters reuse them without another automatic check. Keep explicit manual checks available, invalidate results after note or Work changes, and preserve review decisions through restart and sync.
diff --git a/docs/agent-notes/schema-migration.md b/docs/agent-notes/schema-migration.mdindex 02db424b..3749425c 100644--- a/docs/agent-notes/schema-migration.md+++ b/docs/agent-notes/schema-migration.md@@ -1,16 +1,17 @@ # Schema migration -Schema **V23** is live (`specs/chapter-ai-check-results/`), with V16–V22-retained as frozen predecessors. The app accepts readiness markers `"16"`-through `"23"`; the extension accepts `"23"` only. V23 adds the relationship-free-`ChapterCheckRecord` table (immutable chapter AI check outcomes and review-receipts; `payloadData` is `.externalStorage`). Converted V22 stores retain all-existing library, association and group data and begin with an empty check-table; no check is fabricated from old coverage. The current archive is-**22/23**, with bounded conversion of predecessor **21/22**, **20/21**, **19/20**-and **18/19** archives; the envelope contract asserts the live schema version-directly. The previous generation, V22 (`specs/named-character-groups/`), added-the `CharacterGroup`, `GroupFactEvent` and `GroupTransition` tables.+Schema **V24** is live (`specs/group-notes/`), with V16–V23 retained as frozen+predecessors. The app accepts readiness markers `"16"` through `"24"`; the+extension accepts `"24"` only. V24 adds defaulted `note` and `noteModifiedAt`+attributes to the relationship-free `CharacterGroup` entity. V23 introduced+the relationship-free `ChapterCheckRecord` table (immutable chapter AI check+outcomes and review receipts; `payloadData` is `.externalStorage`). Converted+V23 stores preserve existing library, association, group, and chapter-check+data while existing group rows receive the empty/epoch note defaults. The+current archive is **23/24**, with bounded conversion of predecessor **22/23**,+**21/22**, **20/21**, **19/20** and **18/19** archives; the envelope contract+asserts the live schema version directly. V22 (`specs/named-character-groups/`)+introduced the `CharacterGroup`, `GroupFactEvent` and `GroupTransition` tables. **Freezing V22 for V23 moved four things together:** the frozen snapshot (`AsterismSchemaV22.swift`, `AsterismSchemaV22Models.swift`,@@ -22,23 +23,39 @@ new violations), the live aliases (`Models.swift`, `AssociationModels.swift`, (`BackupV22*`). `BackupV22Payload` composes `BackupV21Payload` and adds the `chapterChecks` array; every predecessor archive imports with no checks. +**Freezing V23 for V24** keeps the same four boundaries coordinated. The full+frozen model is split across `AsterismSchemaV23.swift`,+`AsterismSchemaV23Models.swift`, `AsterismSchemaV23AssociationModels.swift`,+and `AsterismSchemaV23ChapterCheckModels.swift`; these copy the former live V23+model declarations without changing stored fields or relationship macros.+`AsterismSchemaV24.swift` holds the live schema and the appended lightweight+V23→V24 stage. Live declarations and aliases move together in+`AsterismSchemaV24.swift`, `Models.swift`, `AssociationModels.swift` and+`ChapterCheckModels.swift`. The app adds marker `"24"` while retaining 16–23;+the extension accepts only `"24"`. `BackupV23*` composes the unchanged released+V22 payload and adds exact raw group-note variants. Legacy archives contain no+note state and migrate groups to the pristine empty/epoch default; released+V18–V22 archive payload shapes and checksum codecs remain unchanged.+ The app and extension still open through `openForApp` and `openForExtension` respectively, over the same fixed file layout. The detailed V16 account below is retained as the worked example for the next freeze. ## Current state -- The live classes are nested in `extension AsterismSchemaV23` in `Models.swift`- and reached through top-level typealiases. `AsterismSchemaV16.swift` through- `AsterismSchemaV22Models.swift` hold frozen stored fields, relationship macros and- defaults only. `Work.thumbnailData` keeps `.externalStorage`, and referenced raw+- The live classes are nested in `extension AsterismSchemaV24` and reached+ through top-level typealiases. `AsterismSchemaV16.swift` through the split+ V23 snapshot files hold frozen stored fields, relationship macros and defaults+ only. `Work.thumbnailData` keeps `.externalStorage`, and referenced raw spellings and value types stay frozen by reference.-- `AsterismV23MigrationPlan` is `[V16, …, V22, V23]` with seven lightweight- stages. Keep reachable stages absent the owner's population proof. Each+- `AsterismV24MigrationPlan` is `[V16, …, V23, V24]` with eight lightweight+ stages. V23→V24 adds only two defaulted `CharacterGroup` attributes. 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- entity registry. The V19 conversion checks new raw blobs are nil and the- source table is empty while existing data survives.+ entity registry. `V23RecordedStoreTests` installs a populated predecessor+ store and verifies existing group facts survive with empty/epoch note defaults,+ marker 24 publication and extension refusal before the app migration. - A Work group's snapshot elects catch-up confirmation and override across all rows, independently of its authored-content carrier. `CatchUpWriter` writes only where the decoded value differs. The current archive exports that elected
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex c768c73a..f7983d22 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -2,6 +2,7 @@ | Name | Creation Date | Status | Summary | |------|---------------|--------|---------|+| [Group Notes](#group-notes) | 2026-11-09 | Implementation complete — 4/4 tasks | T-2516: optional group notes now flow through guarded storage, both editor/recovery contracts, and read-only Work, chapter and share cards. Full pre-push UI runs retain two intermittent accessibility failures; focused journeys pass. | | [Chapter AI Check Results](#chapter-ai-check-results) | 2026-11-07 | Done — 17/17 tasks; pre-push review and PR in progress | T-2519: retain synced chapter AI outcomes, skip unchanged automatic checks, preserve explicit manual overrides and review decisions; 17 approved tasks with migration and native loading gates. | | [Note Screen Redesign](#note-screen-redesign) | 2026-11-04 | Implemented — focused qualification complete; PR review pending | Note-screen autosave, limited Undo, retained cast links, shared chapter creation, related sheets, single-note recognition and development-only unavailable-library reset. | | [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. |@@ -77,6 +78,14 @@ --- +## Group Notes++**Created:** 2026-11-09 · **Status:** Implementation complete — all 4 tasks on `T-2516/group-notes`; recorded pre-push UI failures accepted for publication by the owner on 2026-11-10; review/fix/merge in progress.++T-2516 adds one optional general note to a named character group. Notes flow through the additive V24/archive path, guarded atomic writes, Work merges, both editor/recovery contracts and read-only Work, chapter and share cards. All 4,442 package tests passed with no compiler warnings; lint, signed Development Mac app/extension compilation and the baseline simulator unit gate (2,062 methods), followed by the journal-fix gate (2,063 methods) passed. Focused phone and iPad group-note journeys pass. The full pre-push iPhone and iPad UI runs each reported an `All works` reachability failure; bounded reruns show the phone journey passes intermittently on both this branch and `origin/main`, and the iPad journey passes when selected alone. No live-library migration or physical Personal run has occurred.++**Files:** [Smolspec](group-notes/smolspec.md) · [Tasks](group-notes/tasks.md) · [Decision log](group-notes/decision_log.md) · [Verification](group-notes/verification.md)+ ## Chapter AI Check Results **Created:** 2026-11-07 · **Status:** Done — all 17 implementation tasks complete on `T-2519/chapter-ai-check-results`; Kiro implemented and Luna wrote and ran tests. Unfiltered Core passes 4,420 tests, quick passes 2,039 tests with signed Mac/extension compilation, and affected phone/iPad journeys pass. Implementation is committed locally as `a24cd32a`; Transit is ready-for-review. Actual two-device CloudKit delivery remains unverified before release.
diff --git a/specs/group-notes/decision_log.md b/specs/group-notes/decision_log.mdnew file mode 100644index 00000000..c056c7ce--- /dev/null+++ b/specs/group-notes/decision_log.md@@ -0,0 +1,22 @@+# Decision Log: Group Notes++## Quick Decisions++| ID | Date | Decision | Rationale and source |+|----|------|----------|----------------------|+| Q1 | 2026-11-09 | Use smolspec for T-2516 despite the additive persistence/archive change; retain every migration and review safeguard. | Owner: “I've merged and also committed and pushed up the signing fix. Can you get started on a smolspec for T-2516. While it involves a minor schema change that's purely additive so I think a smolspec is warranted.” This overrides the repository's usual full-spec route for this ticket only. The persisted schema/archive boundary is acknowledged, not represented as reversible by a code revert. It does not authorize implementation or a live migration. |+| Q2 | 2026-11-09 | Feature slug is `group-notes`. | Assistant asked “T-2516 is the group notes feature. The smolspec process asks for a feature name first: is **group-notes** okay?” Owner replied “yes that's ok”. |+| Q3 | 2026-11-09 | Preserve both current group editing modes. | Source research at `89d61d46`: Work-detail group drafts join the atomic Work Save; note-screen group sheets use `NoteRecordEditingSession` and the pending-edit journal. A note field does not change either save boundary. |+| Q4 | 2026-11-09 | Draft approach: store plain note text and a field timestamp on the group identity; use the existing creator-note election pattern. | `CreatorSupport.swift`, `CreatorWrites.swift` and `DirectoryFold.swift` already settle general-note storage, duplicate election and authored clears. Adding a new `GroupFactOperation` would alter persisted causal payload vocabulary and make an older decoder reject the event; explanatory prose does not participate in group recognition. This is a proposed implementation choice for spec review, not a separate owner approval. |+| Q5 | 2026-11-09 | Draft approach: generation-specific current archive group records; released predecessor shapes remain unchanged. | `GroupRawIdentity` is shared by archive 21/22 and 22/23 payloads and contributes to their reconstructed checksums. Modifying its Codable shape would break old checksums even with decode defaults. Convert predecessor identities to pristine notes only after their existing codec validates them. |+| Q6 | 2026-11-09 | Keep the note general to the group, visible in its existing detail cards, without AI or chapter-link effects. | T-2516 says “I can't add a note to groups now and I want that so I can explain what group that is.” `ShareWorkContext.swift` already represents a group using `ShareCharacter`, with its general-note slot currently empty or carrying the synthetic “No members” message. The existing shared card can show authored text while retaining the independent empty-roster message. |+| Q7 | 2026-11-09 | Draft and reviews precede approval; tasks and implementation have not started. | `starwave:smolspec` requires explanation validation, design critique and explicit smolspec approval before Rune task creation. Feature-name approval is not spec approval. |+| Q8 | 2026-11-09 | Explanation-validation findings are document clarifications, not new scope. | The clean-context review produced beginner/intermediate/expert explanations. Import matching follows the existing raw-variant retention pattern, now explicitly covering import → edit → reimport. Unicode preservation means semantic text with no trimming, following Swift String equality rather than a new byte-history policy. The standard escalation note remains verbatim, with the owner-approved persistence exception bounded immediately above it. No new behavioral choice or boundary was discovered. |+| Q9 | 2026-11-09 | Design critique found no blocking design issue or new escalation trigger; the reviewed draft awaits owner approval. | Independent review checked note election/fan-out, predecessor archive shapes, journal recovery, migration generations and the shared-card empty-roster behavior against source. Corrected the marker wording to “the extension opens only marker 24”, because the app also accepts 24. Tasks are not created until smolspec approval. |+| Q10 | 2026-11-09 | The owner approved the smolspec; prepare Rune tasks for their separate approval. | Assistant asked “The group-notes smolspec is ready for review. It covers one optional note per group, both existing save modes, and the additive migration and sync. Does the smolspec look good?” Owner replied “approved.” The approved artifact is the reviewed spec from Q9. This approves its proposed note and archive approach; it does not approve the task list or start implementation. |+| Q11 | 2026-11-09 | Four dependency-ordered Rune tasks are drafted for owner approval. | Each task includes specification coverage and its own verification: persistence compatibility, guarded writes/lifecycle, both editors/recovery, then read-only cards and final platform regression gates. All remain pending; no implementation, build, installation, branch creation or publication has started. |+| Q12 | 2026-11-09 | The owner approved all four tasks and requested Luna for implementation. | Assistant asked “The four implementation tasks are ready: persistence and migration, group lifecycle writes, the two editors and recovery, and display and regression coverage. Do these tasks look good?” Owner replied “Looks fine, can you try using Luna to implement this?” Implementation and testing are assigned to Luna; the remaining workflow branch-choice gate is pending. |+| Q13 | 2026-11-09 | The owner approved `T-2516/group-notes`; implementation can begin with Luna in an isolated worktree. | Assistant asked “The project’s workflow asks for the branch choice before starting. Is **T-2516/group-notes** okay?” Owner replied “yes”. The worktree is based on the merged signing-fix commit `89d61d46`; the original main checkout is kept clean. No live-library or physical Personal run is authorized. |+| Q14 | 2026-11-09 | Preserve the historical graph baseline and prove the additive change with focused V23 fixtures. | The retained format-15 V18 graph predates group tables, so it cannot establish group-note preservation. It remains unchanged; populated V23 migration and complete attribute/relationship-shape comparisons verify the new boundary. Migration guidance and task wording record this limitation rather than regenerating historical evidence. |+| Q15 | 2026-11-09 | Phase 1 is reviewed and complete; continue the approved implementation with Luna. | Commit `272263e8` completes Rune tasks 1 and 2. The review identified supplemental test defects and explicit coverage gaps, all corrected and confirmed by a focused follow-up review. The final owner-run unfiltered package gate passed 4,441 tests across 420 suites; the unchanged app source retains its signed Mac/extension and full simulator-unit passes. See verification.md for commands, preserved failures, counts and limitations. Tasks 3 and 4 remain pending. |+| Q16 | 2026-11-10 | Accept the recorded full UI failures for publication and proceed with review/merge and Personal installation/normal launch. | The owner explicitly confirmed both the existing-failure exception and real-library Personal replacement/launch. Full results remain failed; focused reruns do not replace them. New failures and material review findings remain blocking. |
diff --git a/specs/group-notes/implementation.md b/specs/group-notes/implementation.mdnew file mode 100644index 00000000..ef2786a0--- /dev/null+++ b/specs/group-notes/implementation.md@@ -0,0 +1,57 @@+# T-2516 Group Notes — Implementation Explanation++## Beginner level++### What changed++Named character groups can now have a general note. The note can be edited in either group editor, is saved with the group, and appears in the group’s read-only detail cards. It is shown separately from the group’s member list.++### Why it matters++People can keep useful context about a group without mixing it into character names, aliases, or chapter-specific notes. Empty notes stay invisible, and an empty roster still has its own “No members” message.++### Key concepts++- A draft is text being edited before its existing save boundary accepts it.+- An autosaved edit is journaled and can be recovered if saving is interrupted.+- A read-only projection assembles stored group facts for display without changing them.++## Intermediate level++### Changes overview++The Work editor exposes a multiline General note field and retains its nested Done/Cancel and enclosing Work Save/Cancel behavior. The chapter-note editor journals note edits through its existing `NoteRecordEditingSession` flow, and its pending-edit representation carries the note and its basis through replay. Work detail and NoteCast render saved notes in group cards. `ShareWorkContext` keeps the note and roster state as separate display values.++### Implementation approach++Notes follow the existing group edit contracts and carry their guarded basis through draft reconstruction. A small `GroupNoteText` view centralizes the Work-detail card’s accessible note presentation. The read-only projections include a note only when it is nonempty; roster presentation remains independent, so note text is never used to infer whether members exist.++### Trade-offs++The Work card’s note presentation is shared in a small view helper. NoteCast retains its own presentation because it has a distinct accessibility identifier and consumer context. Tests cover the editor/session boundaries, the share projection, and rendered phone and iPad journeys.++## Expert level++### Technical deep dive++The feature preserves the established write paths: the Work editor stages a group draft within the Work transaction, while the chapter-note editor journals its pending mutation and applies it through the note-session runner. The edit basis remains attached to the draft so stale-write refusal and recoverability are governed by existing repository contracts. Display projections carry the elected persisted note through `NoteCastModel` and `ShareWorkContext`; `GroupNoteText` exposes an accessible label and stable identifier for the Work detail card.++### Architecture impact++The change adds independent note state to the group identity carried by presentation and persistence boundaries without conflating it with roster membership or chapter-note contents. Share projection remains a pure formatting boundary, and note display introduces no writes or additional storage reads. Existing schema/archive/write tests cover phase 1; phase 2 adds editor, pending-edit, share-projection and rendered-card coverage.++### Potential issues++The focused feature suites passed. Both full pre-push UI gates reported an `All works` reachability failure. Focused reruns passed on this branch (one phone retry and the iPad method) and the phone journey also passed on `origin/main`; the underlying intermittent UI automation cause remains open. The corrected ChapterNotes selector passed its focused journey. No automated result establishes live CloudKit delivery. Physical Personal installation is a separate device operation and must follow the repository’s approval and Xcode MCP process.++## Completeness assessment++- Fully implemented: multiline note editing in both group editors; guarded save/recovery paths; note display in the expanded Work card and read-only cast/share cards; independent empty-roster messaging; accessibility identifiers and labels.+- Verified so far: focused Core, fast, native, phone and iPad journeys; signed Development app/extension compile and unit tests; unfiltered serial Core; lint.+- Pre-push UI acceptance remains failed; its focused `All works` reruns passed but did not resolve the intermittent full-suite results. The owner accepted exactly the recorded full-suite failures as a publication exception on 2026-11-10; they remain failed. Local GitHub authentication is verified. New review findings still require resolution.++## Persistence and compatibility detail++V24 adds defaulted note text/timestamp columns through lightweight V23→V24 migration, retaining V16–V23 snapshots and all eight stages. App markers 16–24 remain accepted; extension access requires 24. Archive 23/24 retains released predecessor codecs and exact raw group-note variants. Projection elects authored note state deterministically by timestamp/text without writes; guarded fan-out preserves explicit clears. Imports and Work merge retain note state without changing naming/membership event ancestry. Note-only changes leave recognition and historical reprocessing inputs unchanged. Legacy recovered journal staging adopts the first loaded note basis without advancing historical naming authority. Its runner/session regression failed four assertions before the fix, then passed within the fresh2,063-method native gate and the affected phone/iPad autosave journeys.++The pre-push correction and independent quality follow-up resolve the legacy recovery gap. Current source-bound results are in verification.md; the earlier full UI failures remain explicitly accepted for publication, rather than passing.
diff --git a/specs/group-notes/smolspec.md b/specs/group-notes/smolspec.mdnew file mode 100644index 00000000..f6304174--- /dev/null+++ b/specs/group-notes/smolspec.md@@ -0,0 +1,54 @@+# Group Notes++## Overview+T-2516 adds one optional plain-text general note to each named character group, so the reader can explain what the group is. The note belongs to the group within its Work, not to a chapter or an individual membership. Existing group names, aliases, membership history and chapter-link recognition keep their current behavior.++**Status:** Approved by the owner on 2026-11-09; explanation validation and design critique completed before approval. Research baseline: `89d61d46` on 2026-11-09, including the merged chapter-check work and Mac share-extension signing fix. The owner explicitly chose smolspec for this additive schema change and approved `group-notes`; this is a scoped exception to the repository's usual full-spec schema rule (decision log Q1–Q2), not approval to implement.++## Requirements+1. The reader MUST be able to add, edit and clear a multiline general note when creating or editing a group. Empty is valid; Unicode text, line breaks and whitespace MUST be preserved without deliberate trimming or normalization; canonically equivalent Unicode representations count as the same text, and byte-for-byte Unicode encoding preservation is not required. Existing groups MUST initially have no note.+2. A nonempty saved note MUST appear in the expanded group detail on the Work page and in the existing read-only group card used by capture/share surfaces. Empty notes MUST add no placeholder text to those cards. An empty roster MUST still display “No members”, independently of whether a note exists. Group pills MUST remain name-only; the note MUST be labeled “General note” in the editor and exposed to accessibility.+3. Work editing MUST retain its existing transaction: nested group Done stages the note, nested Cancel discards that child edit, Work Cancel discards all staged edits, and Work Save commits the note with the other staged Work/group changes or commits none of them. Reopening a staged group MUST retain its latest draft.+4. A group opened from a chapter note MUST retain the existing journaled autosave contract. Input MUST survive Close, backgrounding, restart and save failure; retry and an acknowledgement arriving after further typing MUST not discard the newer draft. Group-note edits MUST remain outside chapter-note Undo, as other shared-record edits do.+5. A stale group-note edit MUST be refused without overwriting a changed saved note, and its draft MUST remain recoverable. Duplicate rows for one coherent group MUST yield the same note regardless of row order: the latest authored note timestamp wins, with a deterministic text tie-break. An explicit clear MUST remain an authored value; a pristine empty row MUST not erase a saved note.+6. Notes MUST survive supported store upgrades, CloudKit-delivered duplicate rows, backup export/import and Work merge. Importing an older archive MUST not clear an existing note. Deleted groups MUST remain deleted; notes MUST not revive names, memberships or links.+7. A note-only change MUST leave group naming, aliases, membership, name recognition, chapter links, AI inputs/results and historical chapter-reprocessing eligibility unchanged. Reading or projecting a note MUST not write to the store.+8. Existing pending group edits saved by the previous app version MUST remain readable and MUST NOT become an implicit note clear. App/extension migration gates and the accepted predecessor archive/store range MUST remain intact.++## Implementation Approach+Paths below are relative to the repository; `Core/` denotes `Packages/AsterismCore/Sources/AsterismCore/` and `CoreTests/` denotes `Packages/AsterismCore/Tests/AsterismCoreTests/`.++### Storage and projection+- Add defaulted `note: String = ""` and `noteModifiedAt: Date = Date(timeIntervalSince1970: 0)` to the live `CharacterGroup` model. Carry a value/timestamp note basis in `GroupSummary` and the group draft. Keep `GroupFactOperation`, its encoded payload, group identity and causal name/membership rules unchanged; a general note is not a new group fact event.+- Follow `Core/CreatorSupport.swift`, `Core/CreatorWrites.swift` and `Core/DirectoryFold.swift` for a field-specific note election and value-guarded fan-out across local copies. For coherent same-ID/same-Work rows, ignore epoch timestamps if any authored timestamp exists; choose the maximum `(noteModifiedAt, note)` tuple using Swift’s non-locale String ordering/equality, as the creator-note fold does. Equal tuples are identical note state. No `PersistentIdentifier`, clock read or write participates in projection. Do not add directory-only name/state/merge columns or a new reconciliation phase.+- Extend `Core/GroupRoster.swift` and `Core/GroupRosterStorage.swift` to carry the elected note and timestamp without making note disagreement a name/roster conflict. Cross-Work identity disagreement keeps its existing refusal. Preserve note values through every `GroupSummary` reconstruction, including `Asterism/Asterism/ViewModels/WorkDetailModel.swift` staged previews.++### Writes and recovery+- Extend `Core/LibraryRepository+CharacterGroups.swift` and `Core/LibraryRepository+WorkDetailEdit.swift` with a note edit guarded by the loaded note value/timestamp, checked under the existing exclusive lock alongside group existence, ownership and tombstone checks. An unchanged note emits no note operation. A changed note, including clear, writes every selected local copy once with a timestamp strictly newer than the observed note basis (advance one millisecond if the injected clock is not newer); failures roll back the enclosing transaction.+- Keep note writes independent of name fact IDs: a name/alias-only edit cannot clear a note, and a note-only edit does not append a naming event. Mixed edits still share one save. `Core/LibraryRepository+GroupHistory.swift` retains a recognition-only inventory digest; adding the note must not broaden it or force a completed chapter sweep to restart.+- Extend `Asterism/Asterism/ViewModels/CharacterGroupEditorModel.swift`, `NoteRecordEditingSession.swift` and `Asterism/Asterism/Support/PendingSharedRecordEdit.swift`: carry note text/basis through draft creation, staging, acknowledgement, full-content replay comparison and copyable recovery text. Decode legacy journal/snapshot values explicitly; missing note fields mean “not edited”, not a request to clear a current note. Preserve that distinction until a current note basis is loaded. A lost acknowledgement may accept already-saved desired content, while a newer differing local draft retains its own text and advances only an acknowledged own-write basis.++### Migration, archive and ownership+- Follow `docs/agent-notes/schema-migration.md`: freeze the full V23 model snapshot, make V24 live, retain V16–V23 and append a lightweight V23→V24 stage. Update all live schema aliases/openers and model-contract fixtures together. Preserve app markers 16–23 and add 24; the extension opens only marker 24. Publish readiness only after successful conversion/validation; retain old snapshots/stages absent new population proof.+- Advance archive 22/23 to 23/24, retaining accepted 22/23, 21/22, 20/21, 19/20 and 18/19 inputs. Use generation-specific group raw records with note/timestamp for the new archive; do not add fields to the released `GroupRawIdentity` type used by predecessor checksums. Extend the current paths rooted at `Core/BackupV22Types.swift`, `BackupV22Codec.swift`, `BackupV22Exporter.swift`, `BackupImporter.swift`, `GroupRawRecords.swift` and `GroupImportPreparation.swift`. Preserve all other payloads, raw group variants and existing strict checksum validation. Convert old groups to pristine empty note state after their released codec validates them. Match imported current group variants by the full `(id, workID, note, noteModifiedAt)` tuple, retaining differing variants as the existing raw import does; an exact variant already present is a no-op. A legacy identity already present for `(id, workID)` needs no additional pristine row. After a local fan-out edit has removed an older exact variant, reimporting that current-format variant may retain it once again, but the newer elected note/clear remains visible and the next identical import adds nothing. Legacy reimport is an identity-only no-op when that identity exists. Election cannot regress a newer local edit or clear.+- `Core/GroupWorkMerge.swift` copies the elected note and its timestamp onto the new destination group while retaining source event ancestry. Existing record-copy flows still copy characters/places only. Group deletion retains its tombstone semantics; Work deletion and Empty Library continue deleting group rows through their existing paths. Update the hand-reviewed `specs/retire-migration-chain/library-graph-baseline.txt`, schema/archive assertions and migration guidance as required by the added fields, without regenerating the baseline.++### Presentation and verification+- Add the multiline “General note” field to `Asterism/Asterism/Views/CharacterGroupEditorView.swift`, using the plain-text field pattern in `NoteRecordDetailsView.swift` and the editor's existing disabled/save states. Show the note in `Asterism/Asterism/Views/WorkDetailView.swift`'s expanded group card. `Core/ShareWorkContext.swift` already maps a group into `ShareCharacter`; populate its general-note field so `Asterism/SharedUI/ShareCharacterChipsView.swift` renders it through the existing read-only card. Its current synthetic “No members” note is presentation, not authored content: keep that empty-roster message separately in the membership presentation, alongside any general note.+- Extend `CoreTests/NamedGroupStorageTests.swift`, `NamedGroupArchiveTests.swift`, `NamedGroupWorkMergeEditTests.swift`, `GroupProjectionBasisTests.swift` and `NamedGroupSaveLinkTests.swift`; add populated V23→V24 recorded-store coverage and marker/extension refusal checks. Verify multiline/Unicode/clear, duplicate order permutations and ties, independent name/note edits, stale basis, rollback, no-op writes, old/current archives, repeated import, Work merge, tombstone non-resurrection and unchanged recognition/history eligibility. Use the existing note/creator fixtures as patterns, not production library data.+- Extend `Asterism/AsterismTests/CharacterGroupEditorTests.swift`, `NoteRecordEditingSessionTests.swift`, `PendingNoteEditTests.swift` and the Work-detail tests for staged/reopened drafts, nested/Work cancellation, atomic Save failure, legacy journal decoding, restart/retry and typing during acknowledgement. Add rendered journeys to `Asterism/AsterismUITests/CharacterGroupsUITests.swift` and the existing note/share journeys for add/edit/clear/read-only display, keyboard navigation, accessibility and wide layouts. Follow `AGENTS.md`'s targeted development checks and serial Core/signed Mac/unit commit bars; full iPhone/iPad UI gates belong to pre-push review of code.++**Dependencies:** Existing group projection and repository locking, journaled shared-record editing, SwiftData lightweight migration, CloudKit mirroring, current archive compatibility adapters and shared cast-card presentation. No new package or service is needed.++**Out of scope:** AI-generated group notes or extraction-context changes; chapter-specific group annotations; rich text, attachments or note history; search/filter additions; roster, name or alias semantics; new merge/copy workflows; schema retirement; signing changes; app installation, live-library migration or physical `Personal` runs.++## Risks and Assumptions+- Risk: a small model addition is omitted from an opener, raw archive adapter or staged summary and silently loses notes. | Mitigation: coordinated V24/marker/archive tests, populated predecessor fixtures, raw round trips and all editor/merge reconstruction tests.+- Risk: an older durable draft or a delayed save acknowledgement clears newer text. | Mitigation: explicit legacy absence handling, full-content replay comparison and interrupted/reordered acknowledgement tests.+- Assumption: general group notes use the established creator-note last-writer/timestamp behavior, not a separate concurrent-version review UI. The scoped smolspec uses that existing pattern; any new user-facing conflict policy requires owner review.+- Prerequisite: implementation rechecks the live generation before the freeze and preserves the signed app/extension compile bar. Automated fixtures cannot prove real CloudKit delivery; any later physical `Personal` verification requires fresh explicit approval under `AGENTS.md`.++The owner-approved persistence exception covers exactly these additive note fields and their required V24/marker/archive adapters. It does not cover new note-history semantics, altered name/roster event payloads or any additional irreversible boundary.++## Escalation Note+This change was scoped as a smolspec. If implementation reveals ambiguity only the user can resolve, an irreversible boundary (public API, persisted schema, auth path), or a contested architectural choice, stop and escalate to the full spec workflow rather than deciding it inline.
diff --git a/specs/group-notes/tasks.md b/specs/group-notes/tasks.mdnew file mode 100644index 00000000..181c0954--- /dev/null+++ b/specs/group-notes/tasks.md@@ -0,0 +1,47 @@+---+references:+ - specs/group-notes/smolspec.md+ - specs/group-notes/decision_log.md+metadata:+ status: complete+---+# Group Notes — T-2516++## Persistence and safe edits++- [x] 1. Group notes survive storage upgrades, duplicate rows and backup round trips <!-- id:6rcfrk6 -->+ - Specification coverage: smolspec.md, Requirements 1, 5, 6, 8.+ - Deliver the approved note value/timestamp and pure deterministic projection together with the complete V23 freeze, live V24 migration/openers, readiness generation 24 and archive 23/24 compatibility. Keep V16–V23 snapshots/stages, app markers 16–24 and released archive codecs intact; the extension opens only 24. This coordinated persistence boundary lands as one coherent change, including aliases, contracts and recorded-store fixtures. Preserve the hand-reviewed graph baseline unchanged: its format-15 V18 snapshot predates the group tables, so the focused populated V23 migration fixture, not that baseline, establishes group-note preservation.+ - Verify empty defaults, multiline/Unicode/whitespace preservation, authored clear, duplicate permutations/ties, epoch versus authored state and projection with no writes. Add populated predecessor-store tests plus successful/failed readiness publication and extension refusal checks.+ - Verify current archive raw variants and every supported predecessor generation, unchanged checksum validation, no older-import clearing, repeated-import idempotence and import → later local note edit/clear → reimport twice. Include incompatible/corrupt-archive refusal with no partial writes.+ - Run affected Core suites and the unfiltered serial Core/signed Mac compile bar before a code commit, following AGENTS.md. No device or live-library run.+ - References: specs/group-notes/smolspec.md, docs/agent-notes/schema-migration.md++- [x] 2. Group-note writes reject stale edits and preserve group lifecycle behavior <!-- id:6rcfrk7 -->+ - Specification coverage: smolspec.md, Requirements 3, 5, 6, 7.+ - Make group creation and guarded note edit/clear available through the existing repository transaction boundaries, including composite Work Save. Preserve existence, same-Work and tombstone checks; fan out an accepted note state to local copies with a timestamp newer than the observed basis. An unchanged note is a no-op, a stale basis refuses without losing the draft, and any refusal/save failure rolls back all staged Work/group changes.+ - Verify independent name/note edits, mixed operations, backwards/equal injected clocks, duplicate rows, replay after lost acknowledgement, clear and no-op saves. Carry the elected note/timestamp through Work merge without rewriting causal events; retain current record-copy and deletion/Empty Library behavior.+ - Add regressions proving deleted groups cannot be revived and note-only changes leave names, aliases, roster, recognition, links, AI results/inputs and completed historical-reprocessing eligibility unchanged.+ - Run affected repository, merge, archive and group-link/history Core suites; preserve the required serial commit bars.+ - Blocked-by: 6rcfrk6 (Group notes survive storage upgrades, duplicate rows and backup round trips)+ - References: specs/group-notes/smolspec.md++## Editing and reading++- [x] 3. Both group editors retain note drafts and save them through their existing contracts <!-- id:6rcfrk8 -->+ - Specification coverage: smolspec.md, Requirements 1, 3, 4, 5, 8.+ - Expose the accessible multiline General note field for new/existing groups and preserve note text/basis through every editor, staged summary and durable shared-record reconstruction. Work-detail Done/Cancel and enclosing Work Save/Cancel retain their current boundaries, including reopening an already staged group and all-or-nothing mixed Work edits.+ - Chapter-note group sheets retain journaled autosave, Close/background handling, recoverable failures, copyable recovery text and exclusion from chapter-note Undo. Legacy pending drafts decode missing note fields as untouched and load a current basis without clearing saved text.+ - Add native tests for add/edit/clear, nested and Work cancellation, reopened drafts, stale-basis refusal, rollback, old journal data, process restart, retry, lost/delayed acknowledgement and further typing while a save completes. Add focused rendered Work and chapter-note editing journeys, including keyboard dismissal, disabled states and accessibility.+ - Run affected Core tests, make test-fast, relevant CharacterGroupEditor/WorkDetail/NoteRecordEditingSession/PendingNoteEdit native suites and targeted UI selectors; verify expected test names/counts. Keep the signed Mac/app-extension and unfiltered Core/unit commit gates required by AGENTS.md.+ - Blocked-by: 6rcfrk7 (Group-note writes reject stale edits and preserve group lifecycle behavior)+ - References: specs/group-notes/smolspec.md++- [x] 4. Existing group detail cards show notes without changing membership presentation <!-- id:6rcfrk9 -->+ - Specification coverage: smolspec.md, Requirements 2, 6, 7.+ - Display saved nonempty notes in expanded Work group cards and existing capture/share read-only group cards, preserving name-only pills, aliases and membership ranges. Keep No members as a separate empty-roster message whether a note exists or not; do not persist it as authored note text. Empty notes add no note placeholder.+ - Extend projection/card tests and rendered phone/iPad journeys for nonempty, empty, cleared, multiline, whitespace and long notes; verify reopen/refresh, accessible reading order, keyboard interaction and wide layouts. Cover affected share/capture consumers on isolated native dependencies and keep the existing app/extension signed Mac compile bar, including the current signing fix.+ - Record the final dependency-based test selection and actual results. During development run affected Core/native suites and targeted journeys. At pre-push review of completed code run unfiltered make test-quick and make test-ui iPhone gates plus make test-ui-ipad; do not reduce these gates, count missing expected tests as failures and do not claim live CloudKit delivery from automated results.+ - No physical Personal run, app install, live-library migration or signing change is part of this task.+ - Blocked-by: 6rcfrk8 (Both group editors retain note drafts and save them through their existing contracts)+ - References: specs/group-notes/smolspec.md
diff --git a/specs/group-notes/verification.md b/specs/group-notes/verification.mdnew file mode 100644index 00000000..cbbd3e7a--- /dev/null+++ b/specs/group-notes/verification.md@@ -0,0 +1,100 @@+# T-2516 phase 1 verification plan++## Phase 2 implementation verification plan and outcomes++Phase 2 touches both editors and the Work/share read-only group cards. It changes `CharacterGroupEditorView`, `NoteRecordEditingSession`/`PendingSharedRecordEdit` presentation and acknowledgement paths, Work-detail and NoteCast projections, and share-context group mapping. Planned native selection: `make test-fast`; app suites `CharacterGroupEditorTests`, `NoteRecordEditingSessionTests`, and `PendingNoteEditTests`; Core `GroupNoteShareContextTests`. Planned rendered journeys: `CharacterGroupsUITests/testGroupEditorCancelAndSave` for Work draft/save/cancel/reopen and a long whitespace-bearing note; `ChapterNotesUITests/testNoteCastGroupNoteAutosavesAndAppearsInReadOnlyCard` on phone and iPad for an empty card, multiline autosave, reopen and clear; share extension projection is covered by `GroupNoteShareContextTests` plus pure `ShareCharacterChips.detailLabel` assertions because its host UI cannot be launched by XCUITest. Full pre-push UI gates remain later. The scoped escalation route enabled Core and simulator test execution; actual outcomes and remaining gates are recorded below.++## Changed behavior and dependency map++- V23 is retained as a frozen model snapshot; V24 adds the optional-note storage fields and becomes the app/live model. Bootstrap and backup-import scratch openers use V24; app accepts predecessor markers 16–23 and 24 while the extension accepts only 24.+- Group roster projection elects the note state from physical same-group rows, ignoring epoch defaults when authored state exists, then ordering by timestamp and Swift string comparison. WorkDetailModel and pending staged summaries must preserve note/timestamp.+- Archive raw wire shapes/checksums for all released predecessor formats remain immutable. Current archive format needs its own record types and tests before declaring compatibility complete.+- Repository note edit, stale-basis and lifecycle changes are expected to touch group write transactions, Work-save composite transactions, merge behavior, journal draft replay, and read-only projections.++## Historical phase-1 planned test selection++Before any commit, required gates are unfiltered serial `make test-core` and signed `make build-mac`; app/native changes also require `make test-quick`. The targeted Core selection will include `NamedGroupStorageTests` (4 cases), `NamedGroupArchiveTests` (7 declarations, 10 cases after parameters), `NamedGroupNoteWriteTests` (3 declarations, 4 cases after the clock parameter), `NamedGroupNoteMergeTests` (1), `NamedGroupSaveLinkTests` (28 declarations, 42 cases after parameters), `NamedGroupNoteInvarianceTests` (1), `WorkDetailEditTransactionTests` (6), and `V23RecordedStoreTests` (2): 70 expected cases across 8 suites. Run whole suites with `make test-core CORE_TEST='NamedGroup(Storage|Archive|NoteWrite|NoteMerge|SaveLink)Tests|NamedGroupNoteInvarianceTests|WorkDetailEditTransactionTests|V23RecordedStoreTests' SWIFT_TEST_FLAGS='--scratch-path /private/tmp/t2516-core-cache' PIPE_PRETTY=`; then run unfiltered serial `make test-core SWIFT_TEST_FLAGS='--scratch-path /private/tmp/t2516-core-cache' PIPE_PRETTY=`. Expected unfiltered count is 3,817, up from the last passing 3,811 because the added coverage introduces 2 archive cases, 1 clock parameter case, 1 note-invariance case, and 2 composite Work transaction cases. The full AsterismTests app suite, including `CharacterGroupEditorTests`' 9 declarations (one parameterized), has passed on unchanged production source; `NoteRecordEditingSessionTests`, `PendingNoteEditTests`, and UI journeys belong to later editor/display phases. These checks use Apple runtime dependencies and temporary isolated data. Zero expected/executed tests or missing identifiers is a failed selection. Preserve raw logs and actual executed identifiers/counts after each run.++The retained `specs/retire-migration-chain/library-graph-baseline.txt` is format 15 and predates the V22 group tables. It contains no group rows or note fields, so it cannot prove group-note migration preservation. It remains unchanged and must not be regenerated. Populated V23→V24 preservation is covered directly by `V23RecordedStoreTests` and the current V23 archive tests; no graph data is invented.++## Execution coordination++Before each build/test batch, verify the shared slot reservation, keep native execution serial, and use the dedicated simulator/private caches per project guidance.++## Validation attempts to date++- `git diff --check`: passed on the implementation edits and the latest marker/archive test corrections.+- `make lint`: initial feature-local length/complexity findings and a frozen-schema `sorted().first` finding were corrected without changing the lint baseline. Subsequent `make test-core` runs passed lint with 0 violations across 1,092 Swift files. The unfiltered Core log contains 0 compiler warning lines.+- After the read-only review additions, standalone `make lint PIPE_PRETTY=` first found 2 serious size violations after the new invariance test was temporarily placed in the already-large `NamedGroupSaveLinkTests.swift` (log `/private/tmp/t2516-lint-after-review.log`). The test was moved to `NamedGroupNoteInvarianceTests.swift`; the rerun passed with 0 violations across 1,094 files (`/private/tmp/t2516-lint-after-review2.log`). This lint result does not compile or verify the tests.+- `git diff --check` passed after the review corrections. No build or test was run after the denied Core attempt.+- Targeted Core batch with `--scratch-path /private/tmp/t2516-core-cache`: early attempts `dev1`–`dev10` had lint, sandbox or compile failures, all before tests ran; preserved logs: `/private/tmp/t2516-core-dev1.log` through `/private/tmp/t2516-core-dev10.log`. The V23 membership sort and nested `OrderKey` references were fixed. `dev11` compiled the Core sources but found missing V23 fixture initializer arguments; 0 tests ran (`/private/tmp/t2516-core-dev11.log`). After correcting that fixture, `dev12` passed 100 tests in 9 suites in 16.819 seconds (`/private/tmp/t2516-core-dev12.log`).+- The unfiltered serial `make test-core` first completed with 3,811 tests in 371 suites and 42 issues (`/private/tmp/t2516-core-full1.log`). The failures were stale current-generation marker/archive expectations and source-boundary scans that needed to recognize the retained V23 frozen snapshot. Those expectations were updated to current V24 markers / V23-V24 archive support, and the schema snapshot was included in the historical-source boundaries. The focused regressions then passed 185 tests in 10 suites (`/private/tmp/t2516-core-focused2.log`). The final unfiltered serial Core run passed 3,811 tests in 371 suites in 246.858 seconds with 0 issues (`/private/tmp/t2516-core-full2.log`).+- Signed Mac app/extension build: first pass failed in `WorkDetailModel.swift` on a type-check complexity error (`/private/tmp/t2516-build-mac1.log`); the split local-value refactor then exposed an uninitialized note-property reference in `CharacterGroupEditorModel.swift` (`/private/tmp/t2516-build-mac2.log`). Both compile errors were fixed. `make build-mac DERIVED_DATA=/private/tmp/t2516-derived-data` then passed: Asterism Development signed successfully and the Makefile verified `AsterismShareExtensionMac.appex` is embedded (`/private/tmp/t2516-build-mac3.log`).+- The owner's post-fix manual `make test-quick` run passed its signed Development macOS build and embedded-extension check, then linted 1,093 files with 0 violations, then ran the full AsterismTests bundle serially on iPhone 18 Pro / iOS 27.2 (UDID `B47A6578-3216-46C8-AE0C-00E12A4B5A47`). The Xcode command selected `-only-testing:AsterismTests`, disabled parallel testing, and used `/private/tmp/t2516-derived-data`. Swift Testing reported 2,047 tests in 159 suites passed in 83.094 seconds; the XCTest layer reported 11 additional tests, yielding 2,058 passed overall in the result summary, with no failures or skips. The output ends `TEST SUCCEEDED`; result bundle: `/tmp/t2516-derived-data/Logs/Test/Test-Asterism Development-2026.11.09_20-44-35-+1100.xcresult`. The complete raw log is preserved at `/private/tmp/t2516-test-quick-user2-capability-fixed-pass.log`; the prior failed run remains at `/private/tmp/t2516-test-quick-user2-capability-failure.log`. The codec correction and regression assertion were present in the passing run. Non-failing diagnostics included Xcode's multiple-matching-macOS-destinations notice, AppIntents metadata extraction being skipped because the app has no AppIntents.framework dependency, `libsqlite3` vnode-unlinked API-violation diagnostics during temporary fixture cleanup, and one SwiftUI unbalanced appearance-transition diagnostic. No test failed; the AppIntents message was the only build `warning:` line, and there were no compiler warnings.+- Current-code validation after the fix: targeted serial `make test-core CORE_TEST=NamedGroupArchiveTests` passed 5 tests in 1 suite (`/private/tmp/t2516-core-archive-gate.log`); standalone `make lint` passed 0 violations across 1,093 files (`/private/tmp/t2516-lint-fix11.log`); unfiltered serial `make test-core` passed 3,811 tests in 371 suites in 246.526 seconds with 0 issues and 0 warning lines (`/private/tmp/t2516-core-full3.log`). Signed Development `make build-mac` passed and verified the embedded share extension is present (`/private/tmp/t2516-build-mac5.log`). Xcode emitted one AppIntents metadata-extraction warning because Asterism has no AppIntents.framework dependency; there were no compiler warnings.+- **Superseded history:** After the owner-run test-quick passed, regression-only Core tests and supporting docs were expanded; there were no production-source changes after the pass. Coverage now includes the scenarios listed under “Additional phase-1 regression coverage and validation plan.” The attempted earlier targeted selection reached verify-identity and lint (0 findings in 1,093 files), then SwiftPM stopped before test discovery at `sandbox-exec: sandbox_apply: Operation not permitted`; zero tests ran. Its elevated retry was denied before launch. These statements describe only that earlier attempt: subsequent scoped escalation was accepted, the expanded tests passed, and tasks 1–4 were completed as recorded in the phase-2 results below. The earlier instruction not to complete tasks is no longer applicable.+- Earlier targeted attempts remain recorded: first stopped at lint with 16 findings, before compilation; the following attempt passed identity verification and lint, then SwiftPM manifest compilation was blocked by the macOS sandbox (`sandbox_apply: Operation not permitted`); zero tests ran. Logs: `/private/tmp/t2516-core-dev1.log`, `/private/tmp/t2516-core-dev2.log`.++The owner reran the unfiltered command `make test-core SWIFT_TEST_FLAGS='--scratch-path /private/tmp/t2516-core-cache' PIPE_PRETTY=` after the Sendable-boundary fix. All four package runs passed: Constellation 43 tests/8 suites, Presentation 304/20, Intelligence 276/20, and AsterismCore 3,818/372. The full Makefile gate therefore passed 4,441 tests in 420 suites; Core took 237.522 seconds. Lint passed with 0 violations across 1,094 files and the log contains no compiler-warning lines. The complete raw log is preserved at `/private/tmp/t2516-core-user-phase1-pass.log`; the immediately preceding compile failure and its zero-test outcome remain preserved at `/private/tmp/t2516-core-user-review-failure.log`. The owner confirmed that the passed identifiers include the new note archive/write/history/transaction cases and populated V23 migration checks. This validates all Core requirements for phase-1 tasks 1 and 2. No production source changed after the signed Development Mac/extension compile and full simulator pass recorded above; those results remain applicable. The standalone lint after the final test-boundary fix also passed with 0 violations across 1,094 files (`/private/tmp/t2516-lint-after-sendable-fix.log`), and `git diff --check` passed.++## Phase-2 change and validation selection++Changed behavior: Work group drafts edit a multiline general note and retain the existing nested Done/Cancel and enclosing Work Save/Cancel boundaries; chapter-note group editors journal and autosave the same note on Close, preserving recovered input and guarded note basis; expanded Work group cards and read-only cast/share cards render nonempty notes with a General note accessibility label while empty notes add no placeholder. Production consumers are `CharacterGroupEditorModel`, `WorkDetailModel` and `WorkDetailView`, `NoteRecordEditingSession` / `PendingNoteEditRunner` and `NoteCastModel` / `NoteCastView`, plus the Core share-work projection. The changed runtime adapters are SwiftUI text-field/card rendering, the app-owned pending-edit journal and the Core share context projection. Fixtures are the isolated seeded Work editor UI library, isolated seeded note-cast UI library, and the temporary stores used by corresponding native/Core tests.++Expected validation identifiers: Core `GroupNoteShareContextTests` and the `make test-fast` cohort; app native `CharacterGroupEditorTests`, `NoteRecordEditingSessionTests`, and `PendingNoteEditTests`; rendered `CharacterGroupsUITests/testGroupEditorCancelAndSave` and `ChapterNotesUITests/testNoteCastGroupNoteAutosavesAndAppearsInReadOnlyCard` on both phone and iPad. The rendered assertions cover an accessible multiline field, empty and cleared cards without placeholders, a long whitespace-bearing Work note, multiline chapter-note autosave, keyboard dismissal, reopen and accessible note reading. Verify actual executed identifiers and counts, and retain raw logs. The broader full UI acceptance remains a pre-push gate per `AGENTS.md`.++Phase-2 validation results:++- `make lint PIPE_PRETTY=` passed with 0 violations across 1,096 files (`/tmp/t2516-phase2-lint-final3.log`); `git diff --check` passed.+- `make test-core CORE_TEST=GroupNoteShareContextTests` passed 1 test in 1 suite (`/tmp/t2516-phase2-core-escalated2.log`). `make test-fast` verified and passed its 192 declared tests in 14 suites (`/tmp/t2516-phase2-test-fast.log`).+- Focused app native suites passed 37 tests in 3 suites (`/tmp/t2516-phase2-native-escalated.xcresult`, raw log `/tmp/t2516-phase2-native-escalated.log`).+- Rendered Work group edit/save/cancel journey passed 1 test on iPhone 18 Pro (`/tmp/t2516-phase2-ui-phone.xcresult`). The chapter-note group-note journey passed 1 test on iPhone 18 Pro and 1 on iPad Pro 11-inch M5 (`/tmp/t2516-phase2-ui-phone-retry4.xcresult`, `/tmp/t2516-phase2-ui-ipad.xcresult`). Earlier UI attempts exposed and corrected the fixture selector and multiline clear-caret issues; final phone/iPad results are green.+- `make test-quick` passed its signed Development Mac app/share-extension compile, verified the Mac extension is embedded, and passed 2,051 Swift Testing methods in 159 suites plus 11 XCTest methods (2,062 total) (`/tmp/t2516-phase2-test-quick.xcresult`, raw log `/tmp/t2516-phase2-test-quick.log`). Xcode emitted its existing AppIntents metadata-extraction notice because the app does not link AppIntents.framework; tests passed.+- Unfiltered serial `make test-core` passed all four package runs: Constellation 43/8 suites, Presentation 304/20, Intelligence 276/20 and AsterismCore 3,819/373, totaling 4,442 tests in 421 suites. The run exited 0 with no compiler warning lines (`/tmp/t2516-phase2-core-full.log`).++The initial un-escalated Core and simulator attempts were blocked before test discovery by home-directory cache-write restrictions. The normal scoped escalation was accepted and all required development, Core and app-unit validation then completed. Full iPhone and iPad UI acceptance was run for pre-push review as recorded below; no live CloudKit delivery or physical Personal run was performed.++## Declared test identifiers++Select whole suites. Parameterized declarations may produce multiple result identifiers; reconcile expected declarations against actual `.xcresult` inventory and executed count after slot release.++- `NamedGroupStorageTests`: `roundTrip`, `noteElectionIsDeterministicAndWhitespacePreserving`, `conflictingTwins`, `disputedPhysicalLeave`.+- `NamedGroupArchiveTests`: `v23ArchiveRoundTripsAuthoredGroupNotesAndCannotClearLocalEdits`, `predecessorArchiveImportsWithNoInventedGroupRows`, `v23ArchivePreservesPhysicalNoteVariants`, `legacyArchivePreservesLocalNoteAndClear`, `currentArchiveRoundTripsGroupFactsAndTransitions`, `conflictingPhysicalFactCopiesRoundTripWithoutChoosingOne`, `importingCoherentGroupReceiptKeepsItsAuthoredNoteAttached` (parameterized).+- `NamedGroupWorkMergeEditTests` (20 declared): `equivalentSourceHeadsSurviveMerge`, `divergentSourceHeadsSurviveMerge`, `unresolvedSourceNameRefusesMerge`, `unresolvedSourceAliasRefusesMerge`, `deletedSourceGroupDoesNotBlockMerge`, `failedMergeRollsBackConcurrentRebind`, `lateInheritedFactRestartsHistory`, `editMergedGroup`, `editAfterSecondMerge`, `failedEditRollsBack`, `conflictingTwinRefusesRevision`, `aliasTwinAfterBasisRefusesRename`, `divergentHeadsRefuseRevision`, `incompleteCurrentTransitionRefusesRevision`, `lateSourceRemovalTombstonesMergedMembership`, `connectedInventoryIncludesPhysicalVariants`, `tornSourceAncestorKeepsAssociationRecoverable` (parameterized), `missingSourceAncestorKeepsAssociationRecoverable` (parameterized), `missingJoinAnchorKeepsLaterAcceptanceRecoverable`, `conflictingMergedClaimsKeepAcceptanceRecoverable` (parameterized).+- `GroupProjectionBasisTests` (12): `composedTeachingAcceptsASplitEntryGroup`, `composedTeachingAcceptsASplitWorkGroup`, `composedTeachingRefusesATornGroup`, `composedTeachingRefusesATornWorkGroup`, `workURLBasisRefusesATornGroup`, `mergeBasisRefusesATornSource`, `mergeBasisRefusesATornTarget`, `workURLBasisReadsTheGroupContent`, `mergeBasisReadsTheGroupContent`, `entryTeachingDetailExposesTheGroup`, `tornEntryTeachingDetailCarriesVariants`, `workSnapshotReportsTheGroup`.+- `NamedGroupSaveLinkTests`: `editorCommitsNameAndAliasesFromOneSnapshot`, `finalSavedGroupNameLinksCurrentMemberAndReplaysIdempotently`, `ordinaryRemovalSuppressesCapturedGroupSupportAndExplicitRestoreReactivatesIt`, `groupMentionDoesNotCreateLinkBeforeTheJoinChapter`, `directAndGroupSupportOneLinkAndRetireIndependently`, `creatingGroupAndJoiningSavedChapterCommitsItsLinkTogether`, `deletingAFormerMemberDoesNotBlockLaterRosterReconciliation`, `mergedMemberDoesNotBlockGroupRenameReconciliation`, `crossWorkPhysicalTwinCannotAuthorizeGroupLink` (parameterized), `renameAliasAndDeleteRevalidateExistingLink`, `transitionRemoveAndStaleEditDoNotRestoreMembership`, `failedGroupSaveRollsBackFactsAndChapterLinkThenRetryCommitsOnce`, `crossWorkTransitionRefusesWholeSessionWithoutSaving`, `savedNoteTerminalsExpandGroupAgainstChapterRoster` (parameterized), `removingGroupAliasRetiresOnlyItsGroupEvidence`, `movingJoinAnchorRecomputesBothChapterMemberships`, `crossWorkPhysicalTwinRefusesGroupMutation` (parameterized), `groupEditorCannotUseAnotherWorksCurrentChapter`, `identicalCloudKitEventCopyDoesNotMakeGroupEditStale` (parameterized), `malformedPhysicalCopyOfTransitionRefusesRevision`, `remoteOnlyJoinReprocessesPreviouslySavedGroupMention`, `remoteFactChangeRevalidatesOldSavedGroupMentions` (parameterized), `interruptedHistoryResumesAfterCommittedBatchWithoutRepeatingIt` (parameterized), `groupFactsArrivingBeforeWorkHydrationRetryAfterChapterAppears`, `temporaryTornTransitionHidesButDoesNotRetireGroupRoot` (parameterized), `missingLeaveAnchorWithholdsLaterLinkButKeepsEarlierNoteRecoverable`, `importInvalidationForcesCompletedHistoryToRecheck`; the scale test is gated off.+- `NamedGroupNoteInvarianceTests`: `noteOnlyEditLeavesDerivedStateUnchanged`.+- `ModelContractTests` (27): all existing schema/default/contract tests, including `emptyLibraryPhasesCoverTheSchema` and historical frozen-schema checks.+- `V23RecordedStoreTests` (2): `populatedGroupReceivesEmptyDefault`, `schemaDeltaIsAdditive`.+- `CharacterGroupEditorTests`: `cancelNeverStages`, `doneStagesCreateForEnclosingWorkSave`, `nestedEditorStartsFromStagedValueButCanCancelIndependently`, `repeatedNestedSavesDeriveOperationsFromOriginalBasis`, `editingOnlyANoteProducesOnlyAGuardedNoteOperation`, `legacyDraftWithoutNoteDoesNotRequestAClear`, `noteSurvivesNestedWorkDraftAndIndependentCancel`, `deletingExistingGroupStagesTombstoneOnly`, `editsAliasesAndTransitionHistoryFromOneSnapshot`, `explicitConflictedTransitionResolution` (parameterized).+- `NamedGroupNoteWriteTests`: `guardedNoteEdit`, `nonNewerClockFansOutAndReplaysLostAcknowledgement` (2 clock arguments), `noteWriteCannotReviveDeletedGroup`.+- `NamedGroupNoteMergeTests`: `mergePreservesNote`.+- `WorkDetailEditTransactionTests`: existing four transactions plus `metadataNameAndNoteCommitTogether` and `staleNoteRollsBackEarlierMutations`; `failedSave` now stages a note with its group create and verifies no note/group writes remain after disk reopen.++## Additional phase-1 regression coverage and validation plan++The later read-only phase review identified explicit gaps in tie ordering, reimports after local edit/clear, backwards/equal clock behavior, exact raw note variants, legacy imports, composite Work transaction coverage, and note-only derived-state invariance. Added Core tests cover each in storage/archive/write/history/transaction suites, and `V23RecordedStoreTests` now compares every existing stored property shape against the frozen predecessor. The final owner-run unfiltered Core gate passed 3,818 tests in 372 suites, bringing the complete Makefile result to 4,441 tests in 420 suites across four package runs (log `/private/tmp/t2516-core-user-phase1-pass.log`). The one compile issue in the prior attempt was fixed by returning Sendable raw note-state values from the locked-context closure; all tests passed afterward. No production source changed after the owner's app/simulator pass. Earlier targeted attempts and their sandbox/authorization outcomes remain recorded above for history; they were superseded by the successful full gate. Tasks 1–4 are complete. The shared slot is released after validation.++## Pre-push review outcomes (2026-11-10)++- Full `make test-ui` ran on the iPhone 18 Pro simulator with no selection flags. Xcode reported 283 total, 278 passed, 2 failed, and 3 skipped. Failures were `ChapterNotesUITests.testNoteCastGroupChoicesAndLinkNoteAutosave` at an exact-label assertion and `AccessibilityJourneyUITests.testTheCreatorControlsStayReachableAtLargestDynamicType` (“All works is reachable from the hub”). The hierarchy showed the intended text as “General note: A quiet port”; the new assertion now matches that label, and the focused ChapterNotes rerun passed 1/1. The creator journey then ran alone twice on this branch: first failed at the hub assertion, then passed 1/1. It also passed 1/1 on `origin/main` at `89d61d46`. Its observed failure is before any Work opens, but these mixed outcomes do not establish the underlying cause or a green full-suite result. Result bundles: `/tmp/t2516-prepush-test-ui.xcresult`, `/tmp/t2516-chapter-fix.xcresult`, `/tmp/t2516-focused-creator-controls.xcresult`, `/tmp/t2516-focused-creator-controls-repeat.xcresult`, and `/tmp/t2516-origin-main-creator.xcresult`.+- Full `make test-ui-ipad` ran the unfiltered `WideLayoutUITests` and `WideLayoutAccessibilityUITests` on iPad Pro 11-inch (M5). It executed 34 tests: 33 passed and 1 failed. `WideLayoutAccessibilityUITests.testTheFiveReadingStatusSegmentsAreOperableInBothWideLayouts` failed at `openAllWorks` (“All works opens”). The same method passed 1/1 when run alone on the current branch using its actual `WideLayoutAccessibilityUITests` suite name; that run took 726.7 seconds and logged repeated app-animation notification timeouts before continuing. An earlier selector used the source filename's suite name and executed zero tests; it is not counted as a pass. The full acceptance result remains failed. Result bundles: `/tmp/t2516-prepush-test-ui-ipad.xcresult` and `/tmp/t2516-focused-wide-status-correct.xcresult`.+- Bounded diagnosis found no stable T-2516 regression in either journey, but did not determine the exact cause of the intermittent `All works` reachability failures. No failure was waived. Pre-push UI verdict remains failed. No Personal device run, live CloudKit test, push, PR creation, or merge occurred.++## Current publication exception and review (2026-11-10)++The owner explicitly accepted the existing recorded full iPhone and iPad UI failures and authorised pre-push-review, pr-pilot and subsequent Personal installation/normal launch. This is a publication exception for those recorded failures only: the full runs remain failed, focused passes do not replace them, and new failures or material code-review findings are not waived. Earlier no-waiver/authentication statements above describe their historical checkpoints. Local GitHub authentication is now verified.++Actual xcresult reconciliation: the phase-2 native result contains 2,062 passed methods (2,051 Swift Testing plus 11 XCTest), zero failures/skips. Full phone: 283 total, 278 passed, 2 failed, 3 skipped. Full iPad: 34 total, 33 passed, 1 failed. The recorded chapter, creator-repeat, creator-on-main and correctly selected wide-layout reruns each passed 1/1; the first focused creator run failed. The zero-test selector is not counted as a pass. Core remains 4,442 passes across the four package runs, with no warning lines.++The full feature diff is reviewed from merge base `89d61d46`. A pre-push code review identified a legacy pending-group note-basis propagation defect; its regression/fix verification is recorded below when complete. Two nonblocking efficiency suggestions (duplicate note projection and duplicate import fetch) are deferred to preserve the already tested Core implementation.++### Pre-push recovery correction — terminal results++The new real-repository runner/session test `NoteRecordEditingSessionTests.legacyGroupRecoveryKeepsLoadedNoteBasisThroughStaging` reproduced the legacy pending-note basis defect with four failed assertions before the fix (16-method suite, `/private/tmp/t2516-review/legacy-red.xcresult`). The shared simulator also emitted an unrelated app-host unknown-schema diagnostic; its data was preserved. Subsequent verification used dedicated T2516 Review Phone and T2516 Review iPad simulators with isolated libraries.++`PendingSharedRecordEdit.keepingBasis(of:)` now retains the loaded note basis only when the preceding legacy draft never edited notes, while preserving its historical naming/membership basis. The independent quality follow-up found the P2 resolved. Full fresh native gate: 2,063 passed (2,052 Swift Testing plus11 XCTest), zero failures/skips/runtime warnings; the new recovery regression passed. Affected `ChapterNotesUITests/testNoteCastGroupNoteAutosavesAndAppearsInReadOnlyCard` passed1/1 on phone and1/1 on iPad, exact identifiers reconciled. Results: `/private/tmp/t2516-review/{native-green,phone-green,ipad-green}.xcresult`; source/result ledger remains outside the repository.++Identity/lint verification passed with0 findings across1,097 files after placing the new regression in a suite extension to retain the existing type-size rule. Signed Development Mac app and embedded extension compiled through Xcode MCP in74.259s; both strict signatures passed. No Mac launch. The full native command used `SKIP_MAC=1` only after this explicit MCP compile satisfied its Mac prerequisite. Package/Makefile/lint inputs are byte-unchanged from tested e28a520a, so the successful unfiltered4,442-package and192-fast evidence is reused; no unchanged broad suite was repeated.++The scoped fix invalidated the app journal dependency, covered by the fresh native/affected-rendered checks. Full UI runs remain the recorded failed acceptance results under Q16; there is no claim of new green full acceptance. Xcode regenerated the previously clean string catalog; its exact generated file/diff/hashes were retained outside the worktree and its proven pre-run bytes restored per pre-push-review Phase5. An initial unsupported run_silent log flag ran no test and is not a result.