Implementation complete; remaining verification gates are recorded below.
make verify-identity passed. Structured runner not detected: the catalog requires a root Package.swift; this repository has an Xcode project and nested Swift package.Needs fixes — verification outstanding
No new must-fix implementation finding. Before push, obtain the required signed Mac build and resolve or explicitly disposition the recorded UI failures. The owner’s two-device Development sync check remains before merge. No fresh test suite was launched in this review.
68ec5adc [doc]: close catch-up progress implementation and record verification limits d368a705 [doc]: changelog for phase Verification 3d3af862 [doc]: changelog for phase App b295af94 [merge]: phase 7 stream 3 e03965aa [merge]: phase 8 stream 1 b591ef7b [feat]: Align UI journeys with Library navigation 334bdcac [feat]: Add catch-up progress to Today and Work pages c0d7bf21 [doc]: record catch-up Today performance comparison dc9cf1f7 [feat]: Carry Work status on Today release rows 4ec09a1c [feat]: Carry Work status on Today release rows 72170800 [doc]: record Today derivation checks 6286d0de [doc]: changelog for phase Today derivation 629d23f5 [feat]: derive and seed catch-up progress on Today f09e5a0e [doc]: record parallel stream integration checks a39bf82a [doc]: changelog for phase Convergence and archive 05a5dc07 [doc]: changelog for phase Repository writes e1397274 [merge]: phase 5 stream 2 ce4766d2 [merge]: phase 4 stream 1 a6c3b7ed [feat]: preserve catch-up progress through convergence and backups efef0115 [feat]: Add catch-up repository writes and rebase 14339ab1 [doc]: record schema verification and signing limitation c77e0799 [doc]: changelog for phase Schema V17 0a325e24 [feat]: add V17 catch-up storage and snapshot election 1ae8690f [doc]: define missing-target behavior for narrow progress writes e5cdc525 [doc]: record Core verification and protected-file prerequisite ec4c0e69 [doc]: changelog for phase Core values 5e4990b1 [feat]: Add catch-up progress core values d73fbf53 [doc]: mark catch-up progress in progress 9c64a315 [doc]: changelog for phase Baseline 10a30868 [doc]: record catch-up progress performance baseline You can record the latest released chapter and, when needed, correct the last chapter you read. Today shows whether the latest number is confirmed, estimated, unknown, or already reached. The same Set latest sheet is available from Today and the work page.
A release schedule can advance the estimate without repeated edits. Reopening an older chapter does not move your progress backwards. Reaching the latest chapter offers an action; your reading status changes only when you tap it.
A confirmation records what you believe is available at a particular time. An estimate counts scheduled releases after that point. An override corrects reading progress until later captured chapter notes supersede it.
CatchUpRecord stores the confirmation and override as two independently timestamped values. CatchUpProgress derives display state from these values, eligible whole-number chapter notes, work status, release days and an explicitly supplied calendar. Schema V17 adds two optional Data blobs; V16 remains the migration source and V15 is retired.
The effective latest chapter is the larger of two lower bounds: the confirmed latest plus eligible releases, and reading progress plus eligible releases. SetLatestModel keeps a draft until Save; repository writes compare the expected values before committing. Work metadata edits rebase progress under the old schedule inside the same transaction. Root-owned sheet presentation survives layout changes.
Two blobs preserve each tuple as a value while allowing confirmation and override to converge independently. Progress stays outside authored metadata and variant identity. Archives 16/17 use six flat fields. Estimates remain derived instead of creating background writes; duplicate reconciliation and import never invent a new confirmation time.
The fold deterministically elects confirmation and override independently, including timestamped override clears. Narrow writes require the addressed work and reject stale bases. Import folds progress before authored-content and modifiedAt guards, without bumping modifiedAt or adding progress-only work to applied membership changes. Metadata rebasing reads current entries under the write lock and uses the caller’s calendar.
Progress is replicated reader state rather than authored work content. The same derived last-read value also feeds release-shelf badges. Work-page refresh after sheet save is deferred during metadata editing to protect the draft. Forecast days avoid present-day action banners. Counts are capped at 9999 and fractional chapter labels are excluded instead of rounded.
Watch real-device convergence and schedule/status transitions while trialling the feature. Reconciliation deliberately does not rebase, so a mismatch can remain until a later explicit Save. Previously recorded performance samples show no regression, but the outstanding signed Mac build, unresolved broader UI failures and owner two-device check still limit verification.
All 25 implementation tasks are complete. The review and three-level explanation identified no missing implementation requirement or undocumented design divergence. Verification remains incomplete: a signed Mac build is required before push; the recorded broader UI runs are not wholly green; the owner’s two-device Development sync check remains before merge. See verification-run.md for exact historical results. This review ran make verify-identity successfully, but launched no fresh test suite because the prescribed runner catalog did not detect this Xcode project at the repository root. Design preference remains subject to the owner’s trial.
Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift
Why it matters. Avoids an estimate falling below chapters already read.
What to look at. CatchUpProgress
Packages/AsterismCore/Sources/AsterismCore/CatchUpRecord.swift
Why it matters. Keeps concurrent edits and timestamped clears deterministic.
What to look at. CatchUpRecord
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17.swift
Why it matters. Adds storage while freezing the supported predecessor.
What to look at. AsterismSchemaV17
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swift
Why it matters. Refuses stale writes without sending a full metadata draft.
What to look at. setReadingStatus and progress write entry points
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift
Why it matters. A torn title or older metadata must not block newer progress.
What to look at. commitWorks
Asterism/Asterism/ViewModels/SetLatestModel.swift
Why it matters. Makes Save explicit and keeps entry points consistent.
What to look at. SetLatestModel
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| P2 | LibraryRepository+CatchUpProgress.swift:101 | Suggestion: also compare publication status before applying the banner’s reading-status action. | Skipped: Q27 and the design specify a narrow reading-status guard. Publication status and reading status are independent; the displayed action remains an explicit user choice. Adding this precondition changes the approved contract. |
Source: local run at 2026-09-27T23:20:35.367931+00:00 · snapshot 68ec5adc87bf3939595df5765eb606e8a8589163 (dirty working tree)
Baseline: none
Execution: not run · JUnit: none · Coverage: none · Baseline: absent
The test runner could not be detected.
Derived by declaration name, from the diff (no baseline run).
Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 5d51ce90b18dfbca3c872b78b7bb4be4a8cdd1a7.
191 files: 181 code · 10 docs. Click to expand.
diff --git a/Asterism/Asterism/ContentView.swift b/Asterism/Asterism/ContentView.swiftindex 2b78059e..9baa061d 100644--- a/Asterism/Asterism/ContentView.swift+++ b/Asterism/Asterism/ContentView.swift@@ -724,6 +724,7 @@ struct ContentView: View { NavigationStack { WorkDetailView( model: detailModel,+ currentDay: model.currentDay, calendar: model.calendar, // Q56's chapter-row route, on this sheet's own // stack: the rows are the same rows, so they open the // same screen rather than being dead here.@@ -775,6 +776,17 @@ struct ContentView: View { catalog: announcements.catalog, onDone: { navigation.presentedAnnouncement = nil }) }+ .sheet(item: $navigation.presentedSetLatest) { route in+ if let setLatest = model.setLatestModel(+ for: route.workID,+ onSaved: {+ navigation.presentedSetLatest = nil+ navigation.recordLatestSave(for: route.workID)+ })+ {+ SetLatestSheet(model: setLatest)+ }+ } .onChange(of: navigation.presentedAnnouncement) { previous, current in guard current == nil, case .releaseNote? = previous else { return } announcements.recordReleaseNoteSeen()
diff --git a/Asterism/Asterism/Layout/AppNavigation.swift b/Asterism/Asterism/Layout/AppNavigation.swiftindex f4c21209..3572d3a2 100644--- a/Asterism/Asterism/Layout/AppNavigation.swift+++ b/Asterism/Asterism/Layout/AppNavigation.swift@@ -329,6 +329,15 @@ final class AppNavigation { /// between bundled versions as its own state, and a key carrying the /// version would tear the sheet down on every such move. var presentedAnnouncement: TodayAnnouncement?+ /// One Set latest sheet per window, from Today or the Work page.+ var presentedSetLatest: SetLatestRoute?+ private(set) var lastSavedLatestWorkID: UUID?+ private(set) var latestSaveGeneration = 0++ func recordLatestSave(for workID: UUID) {+ lastSavedLatestWorkID = workID+ latestSaveGeneration += 1+ } // MARK: - The route waiting for Settings to close @@ -932,6 +941,7 @@ final class AppNavigation { || presentingToReadMatch != nil || statusWorkID != nil || presentedAnnouncement != nil+ || presentedSetLatest != nil } /// Applies the waiting intent route, or drops it (Q42). The caller runs@@ -1027,6 +1037,11 @@ nonisolated enum WorksDetailSubject: Hashable { // MARK: - Sheet identities +struct SetLatestRoute: Identifiable, Equatable {+ let workID: UUID+ var id: UUID { workID }+}+ /// `.sheet(item:)` needs an `Identifiable`, and what these two sheets are keyed /// by is a set key and a Work id. The wrappers exist only for that. nonisolated struct PresentedDuplicateSet: Identifiable, Equatable {
diff --git a/Asterism/Asterism/Layout/AppScreens.swift b/Asterism/Asterism/Layout/AppScreens.swiftindex a5969c81..701619ed 100644--- a/Asterism/Asterism/Layout/AppScreens.swift+++ b/Asterism/Asterism/Layout/AppScreens.swift@@ -120,6 +120,10 @@ struct AppScreens { // a Works row does, because in the wide tree this list stays beside // the detail column and a second tap would otherwise stack. onSelectWork: { navigation.showWork($0, on: .today) },+ onSetLatest: { navigation.presentedSetLatest = SetLatestRoute(workID: $0) },+ onSetReadingStatus: { id, status in+ try await model.setReadingStatus(id: id, to: status)+ }, // Req 10.1's prune, gated for `selectedEntryID`'s reason: the // detail column is the wide tree's, and on the phone a push stays // until the reader pops it (Q43).@@ -277,10 +281,14 @@ struct AppScreens { if let detailModel = model.workDetailModel(for: workID) { WorkDetailView( model: detailModel,+ currentDay: model.currentDay, calendar: model.calendar,+ lastSavedLatestWorkID: navigation.lastSavedLatestWorkID,+ latestSaveGeneration: navigation.latestSaveGeneration, onResolveDuplicate: navigation.resolveRoute( for: workID, type: .work, workload: { model.todayPresentation.duplicateWorkload }), onSelectEntry: { navigation.showChapter($0, on: stack) },+ onSetLatest: { navigation.presentedSetLatest = SetLatestRoute(workID: $0) }, // Req 4.6: the merge deleted the Work this route is showing, so // the route moves to the one that survived rather than popping // to a list.
diff --git a/Asterism/Asterism/Localizable.xcstrings b/Asterism/Asterism/Localizable.xcstringsindex 56f6f83f..2d416398 100644--- a/Asterism/Asterism/Localizable.xcstrings+++ b/Asterism/Asterism/Localizable.xcstrings@@ -12,6 +12,10 @@ "comment" : "A label displaying the chapter number of a chapter in a book. The argument is the chapter number.", "isCommentAutoGenerated" : true },+ "%@" : {+ "comment" : "The dialog for the \"Which chapters release today?\" intent.",+ "isCommentAutoGenerated" : true+ }, "%@ %@" : { "comment" : "A heading with a title and a description. The first argument is the string “Most read works” or the string “Most read sites”. The second argument is a description.", "isCommentAutoGenerated" : true,@@ -168,6 +172,18 @@ } } },+ "%@: %@" : {+ "comment" : "The text of a note in the Today screen's noted section. The first argument is the note's title. The second argument is the note's note.",+ "isCommentAutoGenerated" : true,+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "%1$@: %2$@"+ }+ }+ }+ }, "%@: version %lld → %@" : { "comment" : "A list of capture titles with the version they were replaced by.", "isCommentAutoGenerated" : true,@@ -241,6 +257,10 @@ } } },+ "%lld notes" : {+ "comment" : "The name of the type of a note.",+ "isCommentAutoGenerated" : true+ }, "%lld of %lld finished" : { "comment" : "A label that describes the number of members that have been finished reading, followed by the total number of members.", "isCommentAutoGenerated" : true,@@ -287,6 +307,10 @@ "comment" : "A label showing the number of books that are yet to be read.", "isCommentAutoGenerated" : true },+ "%lld works" : {+ "comment" : "The display name of the type of entity.",+ "isCommentAutoGenerated" : true+ }, "%lld works · %@" : { "comment" : "A row displaying the number of works and the current sort order.", "isCommentAutoGenerated" : true,@@ -299,6 +323,18 @@ } } },+ "%lld · %@" : {+ "comment" : "The text of the last chapter read.",+ "isCommentAutoGenerated" : true,+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "%1$lld · %2$@"+ }+ }+ }+ }, "%lld × %lld" : { "comment" : "A footnote that shows the width and height of a candidate's image.", "isCommentAutoGenerated" : true,@@ -327,6 +363,13 @@ "comment" : "The text of a button that adds a new creator.", "isCommentAutoGenerated" : true },+ "Add ${url} as to read" : {++ },+ "Add Page as To Read" : {+ "comment" : "Title of the \"Add this as to read\" intent.",+ "isCommentAutoGenerated" : true+ }, "Add a creator" : { "comment" : "The title of a sheet that lets the user add a creator.", "isCommentAutoGenerated" : true@@ -343,6 +386,14 @@ "comment" : "A label for a text field that adds a new alias.", "isCommentAutoGenerated" : true },+ "Add as To Read" : {+ "comment" : "Text for the shortcut to add a page to read.",+ "isCommentAutoGenerated" : true+ },+ "Add it as “%@”?" : {+ "comment" : "The title of the intent.",+ "isCommentAutoGenerated" : true+ }, "Add the role %@" : { "comment" : "A label for a pill button that lets the user add or remove a role from a credit. The argument is the role's label.", "isCommentAutoGenerated" : true@@ -351,6 +402,10 @@ "comment" : "A button that adds a new alias to a character.", "isCommentAutoGenerated" : true },+ "Adds a web page to your library as a new work to read, after you confirm its title." : {+ "comment" : "Description of the AddPageToReadIntent intent.",+ "isCommentAutoGenerated" : true+ }, "Adds to a %@ you already have." : { "comment" : "A note that a bundle adds to a character", "isCommentAutoGenerated" : true@@ -430,6 +485,14 @@ "comment" : "A button that opens a sheet for changing the status of a work.", "isCommentAutoGenerated" : true },+ "Change title" : {+ "comment" : "Choice to change the title of the page.",+ "isCommentAutoGenerated" : true+ },+ "Chapter" : {+ "comment" : "The name of the chapter field in a note.",+ "isCommentAutoGenerated" : true+ }, "Chapter Provenance" : { "comment" : "A label for the provenance of the chapter.", "isCommentAutoGenerated" : true@@ -440,6 +503,10 @@ }, "Chapter: manual protection (preserved)" : { + },+ "Chapters Releasing Today" : {+ "comment" : "Title of the \"Which chapters release today?\" intent.",+ "isCommentAutoGenerated" : true }, "Chapters will stay unsettled" : { @@ -448,6 +515,10 @@ "comment" : "A button that opens a screen to check the library.", "isCommentAutoGenerated" : true },+ "Check on %@" : {+ "comment" : "A button that opens a URL. The argument is the site name.",+ "isCommentAutoGenerated" : true+ }, "Check whether %@ belongs to a story in To Read" : { "comment" : "A button that asks whether a", "isCommentAutoGenerated" : true@@ -509,6 +580,14 @@ }, "Could not load the copies" : { + },+ "Couldn’t update reading status" : {+ "comment" : "A title for an alert that displays when a reading status update fails.",+ "isCommentAutoGenerated" : true+ },+ "Count up on release days" : {+ "comment" : "A toggle that allows users to count up on release days.",+ "isCommentAutoGenerated" : true }, "Counted by when a note was first captured. Re-reading does not move a bar." : { "comment" : "A description of the data in the graph.",@@ -580,6 +659,10 @@ "comment" : "The heading for the Debug section of the settings view.", "isCommentAutoGenerated" : true },+ "Decrease latest chapter" : {+ "comment" : "A button that decreases the latest chapter number.",+ "isCommentAutoGenerated" : true+ }, "Delete" : { "comment" : "The label of a button that deletes a creator.", "isCommentAutoGenerated" : true@@ -721,8 +804,16 @@ "comment" : "A button that fetches a cover from the web.", "isCommentAutoGenerated" : true },+ "Finds works in your Asterism library by title." : {+ "comment" : "Description of the Find Works intent.",+ "isCommentAutoGenerated" : true+ }, "Genre tags (comma-separated)" : { + },+ "Go to Work" : {+ "comment" : "A button that opens a web page for a work item.",+ "isCommentAutoGenerated" : true }, "How these two works are related — “adaptation”, “sequel”, anything you like." : { "comment" : "A description of what the user can enter in the",@@ -747,6 +838,10 @@ "comment" : "A label displayed while the backup is being imported.", "isCommentAutoGenerated" : true },+ "Increase latest chapter" : {+ "comment" : "A button that increases the latest chapter number.",+ "isCommentAutoGenerated" : true+ }, "Keep" : { },@@ -763,6 +858,10 @@ }, "Kept: Credits, %@" : { + },+ "Latest released" : {+ "comment" : "The title of the sheet that lets the user set the latest chapter of a work.",+ "isCommentAutoGenerated" : true }, "Left unattached" : { "comment" : "A description of a book that was left without a work.",@@ -802,6 +901,10 @@ "comment" : "The label for the link type field in the work editor.", "isCommentAutoGenerated" : true },+ "Lists the works in your library with a chapter expected today, as the Today screen shows them." : {+ "comment" : "Description of the intent that lists the works in the library with a chapter expected today.",+ "isCommentAutoGenerated" : true+ }, "Loading copies…" : { "comment" : "The loading text for the duplicate resolution sheet.", "isCommentAutoGenerated" : true@@ -810,6 +913,10 @@ "comment" : "A loading message for the move-to sheet.", "isCommentAutoGenerated" : true },+ "Loading latest chapter…" : {+ "comment" : "The text that appears when the latest chapter is loading.",+ "isCommentAutoGenerated" : true+ }, "Loading merge destinations…" : { "comment" : "A loading message for the merge destination picker.", "isCommentAutoGenerated" : true@@ -880,6 +987,10 @@ }, "Move to" : { + },+ "Move to Reading" : {+ "comment" : "A button that moves a task to the \"Reading\" section.",+ "isCommentAutoGenerated" : true }, "Multiple Works match the parsed title. Assignment will remain unresolved." : { @@ -991,14 +1102,25 @@ "Not %@" : { "comment" : "A button that lets the user dismiss a Work that is not the same as another Work. The argument is the title of the Work that the user is dismissing.", "isCommentAutoGenerated" : true+ },+ "Not yet, more is out" : {+ }, "Note" : { + },+ "Noted today" : {+ "comment" : "A label for a checkmark in a list item.",+ "isCommentAutoGenerated" : true }, "Notes" : { "comment" : "The notes of a creator.", "isCommentAutoGenerated" : true },+ "Notes from Today" : {+ "comment" : "Shortcut name for the Notes from Today shortcut.",+ "isCommentAutoGenerated" : true+ }, "Notes will include merge record" : { },@@ -1020,6 +1142,13 @@ }, "Nothing to resolve" : { + },+ "OK" : {+ "comment" : "The label of a button that dismisses an alert.",+ "isCommentAutoGenerated" : true+ },+ "Open ${work}" : {+ }, "Open %@" : { "comment" : "A button that opens a work. The",@@ -1029,10 +1158,22 @@ "comment" : "A button that opens the Check Library.", "isCommentAutoGenerated" : true },+ "Open Today" : {+ "comment" : "Text for the shortcut to open the Today view.",+ "isCommentAutoGenerated" : true+ },+ "Open Work" : {+ "comment" : "Shortcut name for opening a work.",+ "isCommentAutoGenerated" : true+ }, "Open Work %@" : { "comment" : "The accessibility label", "isCommentAutoGenerated" : true },+ "Open Work Page" : {+ "comment" : "The label of a button that opens a web page.",+ "isCommentAutoGenerated" : true+ }, "Open entry %@ from %@" : { "comment" : "A sentence that describes the action to take to open the entry. The first argument is the entry's accessibility title. The second argument is the site name.", "isCommentAutoGenerated" : true,@@ -1067,11 +1208,19 @@ }, "Opening library…" : { + },+ "Opens Asterism on the Today screen." : {+ "comment" : "Description of the \"Open Today\" intent.",+ "isCommentAutoGenerated" : true }, "Opens a date picker" : { "comment" : "A hint for a button that opens a date picker.", "isCommentAutoGenerated" : true },+ "Opens a work in Asterism." : {+ "comment" : "Intent description for opening a work in Asterism.",+ "isCommentAutoGenerated" : true+ }, "Opens this %@'s name, aliases and facts" : { "comment" : "A hint for a line in the edit session's collection.", "isCommentAutoGenerated" : true@@ -1190,11 +1339,19 @@ "comment" : "A button that triggers the user to re-teach a title pattern.", "isCommentAutoGenerated" : true },+ "Reading Status" : {+ "comment" : "The name of the reading status property.",+ "isCommentAutoGenerated" : true+ }, "Reading backup…" : { }, "Reading that link…" : { + },+ "Reads the notes you made on chapters today." : {+ "comment" : "Description of the Notes from Today intent.",+ "isCommentAutoGenerated" : true }, "Reapplies the current rules to every Entry — use this after moving Entries to resolve a split." : { "comment" : "A description of the recalculation button.",@@ -1219,6 +1376,10 @@ "comment" : "A button that dismisses the drain report.", "isCommentAutoGenerated" : true },+ "Releasing Today" : {+ "comment" : "Short title for the \"What's releasing today\" shortcut.",+ "isCommentAutoGenerated" : true+ }, "Remove" : { "comment" : "A button that removes a creator role.", "isCommentAutoGenerated" : true@@ -1401,6 +1562,14 @@ "comment" : "A heading for the set aside captures in the settings.", "isCommentAutoGenerated" : true },+ "Set latest…" : {+ "comment" : "A button that sets the latest read item.",+ "isCommentAutoGenerated" : true+ },+ "Set or clear your last chapter" : {+ "comment" : "A label for a text field that lets the user set or clear their last read chapter.",+ "isCommentAutoGenerated" : true+ }, "Settings" : { "comment" : "The label for the settings button.", "isCommentAutoGenerated" : true@@ -1654,6 +1823,10 @@ "comment" : "The title of the review screen.", "isCommentAutoGenerated" : true },+ "Unlock your device to use your Asterism library." : {+ "comment" : "Error message shown when the user tries to access the library while the device is locked.",+ "isCommentAutoGenerated" : true+ }, "Update" : { },@@ -1687,18 +1860,42 @@ "comment" : "A button that lets the user choose to use whole segments instead of parts.", "isCommentAutoGenerated" : true },+ "Use “%@”" : {+ "comment" : "The text of the \"Use “...\"\" option in the",+ "isCommentAutoGenerated" : true+ }, "Verdict" : { + },+ "Web Page" : {+ "comment" : "The name of the parameter for the web page.",+ "isCommentAutoGenerated" : true+ },+ "What should it be called?" : {+ "comment" : "Text for the prompt to enter a title for the new work.",+ "isCommentAutoGenerated" : true }, "Which copy do you want to keep?" : { "comment" : "The title of a sheet that lets the user choose which of two duplicate entries to keep.", "isCommentAutoGenerated" : true },+ "Which page?" : {+ "comment" : "Question to ask the user which page to add to their library.",+ "isCommentAutoGenerated" : true+ }, "Which site this Work URL is for" : { + },+ "Work" : {+ "comment" : "The title of the \"Work\" field in a note.",+ "isCommentAutoGenerated" : true }, "Work ID" : { + },+ "Work Status" : {+ "comment" : "The name of the work status property.",+ "isCommentAutoGenerated" : true }, "Work URL" : { "comment" : "A label for the URL of a work.",@@ -1751,6 +1948,10 @@ }, "You have decided every suggestion for this work." : { + },+ "Your last chapter" : {+ "comment" : "A label displayed above the user's last read chapter.",+ "isCommentAutoGenerated" : true }, "Your library currently holds %lld entries and %lld works. Anything this backup does not describe is left alone." : { "comment" : "A description of the backup and the user's library. The first argument is the count of entries in the backup. The second argument is the count of works in the backup. The third argument is the count of entries in the user's library. The fourth argument is the count of works in the user's library.",@@ -1784,6 +1985,10 @@ "comment" : "A description of the sidebar's state when it's hidden.", "isCommentAutoGenerated" : true },+ "estimated" : {+ "comment" : "A description of a number that's not the most recent chapter.",+ "isCommentAutoGenerated" : true+ }, "example.com or example.com/story" : { "comment" : "A placeholder text for the URL field of a new work form.", "isCommentAutoGenerated" : true
diff --git a/Asterism/Asterism/Support/PlatformModifiers.swift b/Asterism/Asterism/Support/PlatformModifiers.swiftindex 8ad91a83..a786b222 100644--- a/Asterism/Asterism/Support/PlatformModifiers.swift+++ b/Asterism/Asterism/Support/PlatformModifiers.swift@@ -160,6 +160,15 @@ extension View { #endif } + /// A chapter number is one whole number, with no decimal separator.+ func wholeNumberKeyboard() -> some View {+ #if os(iOS)+ return keyboardType(.numberPad)+ #else+ return self+ #endif+ }+ /// A field holding data rather than prose — a hostname, a type name — must /// not be capitalised for the reader. func noAutocapitalization() -> some View {
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex 8708def9..6fe48b73 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -323,8 +323,8 @@ public final class AppLibraryModel { /// class-bound, and teardown clears the reference only after awaiting the /// shutdown, where the counter moves before that suspension. private var repositoryEpoch = 0- /// Retains the concrete repository for backup export (conforms to BackupV15SnapshotProviding).- private var backupRepository: (any BackupV15SnapshotProviding)?+ /// Retains the concrete repository for backup export (conforms to BackupV16SnapshotProviding).+ private var backupRepository: (any BackupV16SnapshotProviding)? /// 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.@@ -1539,7 +1539,7 @@ public final class AppLibraryModel { let coverFetcher: any CoverFetching = CoverCandidateFetcher() #endif return WorkDetailModel(- workID: id, library: repo, capabilities: capabilities,+ workID: id, library: repo, calendar: calendar, capabilities: capabilities, coverFetcher: coverFetcher, onMutation: { [weak self] in await self?.clearConflicts(resolvedBy: id)@@ -1551,6 +1551,40 @@ public final class AppLibraryModel { }) } + func setLatestModel(+ for id: UUID, onSaved: @escaping @MainActor () -> Void+ ) -> SetLatestModel? {+ guard let repo = repository else { return nil }+ return SetLatestModel(+ workID: id, library: repo, day: currentDay, calendar: calendar,+ commit: { [weak self] id, basis, draft in+ guard let self else { throw LibraryNotOpen() }+ return try await self.commitCatchUpProgress(id: id, basis: basis, draft: draft)+ },+ onSaved: onSaved)+ }++ /// A sheet Save is one repository write followed by a fresh Today publication.+ func commitCatchUpProgress(+ id: UUID, basis: CatchUpRecord, draft: CatchUpDraft+ ) async throws -> LibraryWriteOutcome {+ guard let repo = repository else { throw LibraryNotOpen() }+ let outcome = try await repo.commitCatchUpProgress(id: id, basis: basis, draft: draft)+ if outcome == .committed { await refreshDiagnosesAndSnapshots() }+ return outcome+ }++ /// The banner's expected status is always Catching up, its visible basis.+ func setReadingStatus(+ id: UUID, to status: ReadingStatus+ ) async throws -> LibraryWriteOutcome {+ guard let repo = repository else { throw LibraryNotOpen() }+ let outcome = try await repo.setReadingStatus(+ id: id, expected: .catchingUp, to: status)+ await refreshDiagnosesAndSnapshots()+ return outcome+ }+ /// The resolution sheet for one duplicate set (Requirement 4). /// /// Schedules a pass on commit, like every other reader action (Req 1.2) —@@ -1981,6 +2015,8 @@ public final class AppLibraryModel { let workload = todayPresentation.duplicateWorkload pendingConflicts.removeAll { pending in switch pending.conflict {+ case .recordChanged:+ return false case .torn, .disclosureStale: return workload.item(for: pending.id, type: pending.recordType) == nil case .survivorDiverged:@@ -2798,11 +2834,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() -> BackupV15Exporter? {+ private func backupExporter() -> BackupV16Exporter? { guard let repo = backupRepository, let config = resolvedConfiguration else { return nil } let stagingDir = config.rootDirectory .appending(path: "Library/Caches/BackupExports")- return BackupV15Exporter(repository: repo, stagingDirectory: stagingDir)+ return BackupV16Exporter(repository: repo, stagingDirectory: stagingDir) } /// The per-entry markdown export model (Req 1.5), staged beside the backup@@ -3074,7 +3110,7 @@ public final class AppLibraryModel { verdict: reloaded.verdict, releaseDays: reloaded.releaseDays, membership: reloaded.membership,- thumbnail: .keep))+ thumbnail: .keep), calendar: calendar) Self.logger.debug("Seeded the character-extraction UI test fixture") } @@ -3215,7 +3251,7 @@ public final class AppLibraryModel { workStatus: workStatus, readingStatus: readingStatus, verdict: verdict, releaseDays: releaseDays, membership: reloaded.membership,- thumbnail: .keep))+ thumbnail: .keep), calendar: calendar) } /// `update-schedule`: the smallest library the Today screen has something@@ -3323,6 +3359,16 @@ public final class AppLibraryModel { #if DEBUG || ASTERISM_PERFORMANCE_TESTING try await repo.backdateEntry(id: lanternEntry, to: previousDate) try await repo.backdateEntry(id: emberEntry, to: emberDate)+ let confirmedAt = previousDate+ try await seedTodayCatchUpWork(+ title: "Frost Relay", latest: 10, lastRead: 6,+ releaseDays: [], confirmedAt: confirmedAt, in: repo)+ try await seedTodayCatchUpWork(+ title: "Copper Atlas", latest: 10, lastRead: 6,+ releaseDays: [currentWeekday], confirmedAt: confirmedAt, in: repo)+ try await seedTodayCatchUpWork(+ title: "Harbor Signal", latest: 8, lastRead: 8,+ releaseDays: [], confirmedAt: confirmedAt, in: repo) #else throw LibraryRepositoryError.invalidInput( operation: operation, reason: "the today fixture requires a debug build")@@ -3330,6 +3376,33 @@ public final class AppLibraryModel { Self.logger.debug("Seeded the today UI test fixture") } + #if DEBUG || ASTERISM_PERFORMANCE_TESTING+ /// These three works have no Entries, so the existing four Recent rows and+ /// their two-day ordering stay fixed. Their past overrides supply R.+ private func seedTodayCatchUpWork(+ title: String, latest: Int, lastRead: Int,+ releaseDays: [ReleaseDay], confirmedAt: Date,+ in repo: LibraryRepository+ ) async throws {+ let work = try await repo.createWork(+ NewWorkDraft(displayTitle: title, hostname: "today.test"))+ let reloaded = try await repo.work(id: work.id)+ _ = try await repo.updateWork(+ id: work.id, basis: WorkEditBasis(work: reloaded),+ draft: WorkMetadataDraft(+ displayTitle: title, typeAssignment: reloaded.typeDisplay.assignment,+ genreTags: reloaded.genreTags, genericNotes: "",+ workStatus: .ongoing, readingStatus: .catchingUp, verdict: "",+ releaseDays: releaseDays, membership: reloaded.membership,+ thumbnail: .keep),+ calendar: calendar)+ try await repo.seedCatchUpFixture(+ workID: work.id, latest: latest, confirmedAt: confirmedAt,+ override: .value(+ lastRead, atMilliseconds: MillisecondInstant.milliseconds(confirmedAt)))+ }+ #endif+ /// Teaches `today.test` the one rule that gives the fixture's entries a /// chapter line. ///@@ -3409,7 +3482,7 @@ public final class AppLibraryModel { workStatus: workStatus, readingStatus: readingStatus, verdict: "", releaseDays: releaseDays, membership: reloaded.membership,- thumbnail: .keep))+ thumbnail: .keep), calendar: calendar) return entry.id } @@ -3517,7 +3590,7 @@ public final class AppLibraryModel { verdict: readingStatus == .abandoned ? "The fog plot went nowhere." : "", releaseDays: reloaded.releaseDays, membership: membership,- thumbnail: .keep))+ thumbnail: .keep), calendar: calendar) return work.id } @@ -3656,7 +3729,7 @@ public final class AppLibraryModel { // what every non-editor caller sends (Q85's other side). credits: credits.isEmpty ? nil : CreditsDraft(seenRowIDs: [], credits: credits),- thumbnail: .keep))+ thumbnail: .keep), calendar: calendar) return work.id }
diff --git a/Asterism/Asterism/ViewModels/EntryDetailModel.swift b/Asterism/Asterism/ViewModels/EntryDetailModel.swiftindex 503ad705..8ad8539d 100644--- a/Asterism/Asterism/ViewModels/EntryDetailModel.swift+++ b/Asterism/Asterism/ViewModels/EntryDetailModel.swift@@ -389,6 +389,8 @@ public final class EntryDetailModel { /// in every arm; what differs is why it could not land yet. static func conflictMessage(_ conflict: WriteConflict) -> String { switch conflict {+ case .recordChanged:+ "This record changed on another device. Close and reopen to see it." case .torn: "This record has copies that differ. Resolve them before editing or deleting." case .survivorDiverged:
diff --git a/Asterism/Asterism/ViewModels/MaintenanceViewModels.swift b/Asterism/Asterism/ViewModels/MaintenanceViewModels.swiftindex a052aa5e..164e206e 100644--- a/Asterism/Asterism/ViewModels/MaintenanceViewModels.swift+++ b/Asterism/Asterism/ViewModels/MaintenanceViewModels.swift@@ -505,6 +505,8 @@ public final class LibraryDiagnosticsModel { // row (Req 9.4). let resolution: String switch conflict.conflict {+ case .recordChanged:+ resolution = "Close and reopen the record to see the latest values." case .torn, .disclosureStale: resolution = "Open the record and save your edit again once the copies are resolved." case .survivorDiverged:
diff --git a/Asterism/Asterism/ViewModels/SetLatestModel.swift b/Asterism/Asterism/ViewModels/SetLatestModel.swiftnew file mode 100644index 00000000..dbc78704--- /dev/null+++ b/Asterism/Asterism/ViewModels/SetLatestModel.swift@@ -0,0 +1,150 @@+import AsterismCore+import Foundation++/// One sheet visit holds its drafts until Save succeeds or the reader dismisses it.+@MainActor @Observable+final class SetLatestModel {+ private let workID: UUID+ private let library: any LibraryProviding+ private let day: CivilDay+ private let calendar: Calendar+ private let commit: @MainActor (UUID, CatchUpRecord, CatchUpDraft) async throws -> LibraryWriteOutcome+ private let onSaved: @MainActor () -> Void++ private(set) var sheetState: CatchUpSheetState?+ private(set) var latestText = ""+ private(set) var overrideText = ""+ var countsUp = true+ private(set) var errorMessage: String?+ private(set) var isLoading = false+ private(set) var isSaving = false+ private var latestEdited = false+ private var overrideEdited = false++ var work: WorkSnapshot? { sheetState?.work }+ var progress: CatchUpProgress? { sheetState?.progress }+ var displayedCalendar: Calendar { calendar }+ var showsCountUp: Bool { !(work?.releaseDays.isEmpty ?? true) }+ var lastReadSourceText: String? {+ switch progress?.lastReadSource {+ case .note(let title): title+ case .override: "set by you"+ case nil: nil+ }+ }++ var latestIsEstimated: Bool {+ guard !latestEdited, let sheetState,+ let effective = sheetState.progress.effectiveLatest,+ latestText == String(effective) else { return false }+ return effective != sheetState.record.latest+ || sheetState.record.confirmation?.isEstimate == true+ }++ var behindCaption: String? {+ guard let read = progress?.lastRead,+ let entered = parsed(latestText), (0...9_999).contains(entered)+ else { return nil }+ if entered < read {+ return "Below your last chapter (\(read)); progress will show \(read)"+ }+ if entered == read { return "Caught up" }+ let episodes = work.map { ChapterNumberText.countsEpisodes($0.typeDisplay) } ?? false+ let count = Pluralisation.count(+ entered - read, episodes ? "episode" : "chapter",+ episodes ? "episodes" : "chapters")+ return "\(count) behind"+ }++ var canSave: Bool {+ sheetState != nil && valid(latestText) && valid(overrideText) && !isSaving+ }++ init(+ workID: UUID, library: any LibraryProviding, day: CivilDay, calendar: Calendar,+ commit: @escaping @MainActor (UUID, CatchUpRecord, CatchUpDraft) async throws -> LibraryWriteOutcome,+ onSaved: @escaping @MainActor () -> Void+ ) {+ self.workID = workID+ self.library = library+ self.day = day+ self.calendar = calendar+ self.commit = commit+ self.onSaved = onSaved+ }++ func load() async {+ guard sheetState == nil, !isLoading else { return }+ isLoading = true+ defer { isLoading = false }+ do {+ let state = try await library.catchUpSheetState(+ workID: workID, day: day, calendar: calendar)+ sheetState = state+ latestText = state.progress.effectiveLatest.map(String.init)+ ?? state.progress.lastRead.map(String.init) ?? ""+ if case .value(let number, _) = state.record.override {+ overrideText = String(number)+ } else { overrideText = "" }+ countsUp = state.record.countsUp+ errorMessage = nil+ } catch {+ errorMessage = error.localizedDescription+ }+ }++ func setLatestText(_ value: String) {+ latestText = value+ latestEdited = true+ }++ func setOverrideText(_ value: String) {+ overrideText = value+ overrideEdited = true+ }++ func adjustLatest(by step: Int) {+ guard let current = parsed(latestText) else {+ setLatestText(String(max(0, step)))+ return+ }+ setLatestText(String(min(9_999, max(0, current + step))))+ }++ func save() async {+ guard canSave, let sheetState else { return }+ isSaving = true+ errorMessage = nil+ defer { isSaving = false }+ let override: OverrideEdit+ if !overrideEdited { override = .unchanged }+ else if overrideText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ override = .clear+ } else {+ override = .set(parsed(overrideText)!)+ }+ let draft = CatchUpDraft(+ latest: parsed(latestText), countsUp: countsUp, override: override)+ do {+ let outcome = try await commit(workID, sheetState.record, draft)+ switch outcome {+ case .committed: onSaved()+ case .conflict(.recordChanged):+ errorMessage = "Changed on another device. Close and reopen to see it."+ case .conflict(let conflict):+ errorMessage = EntryDetailModel.conflictMessage(conflict)+ }+ } catch {+ errorMessage = error.localizedDescription+ }+ }++ private func parsed(_ text: String) -> Int? {+ Int(text.trimmingCharacters(in: .whitespacesAndNewlines))+ }++ private func valid(_ text: String) -> Bool {+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed.isEmpty || parsed(trimmed).map { (0...9_999).contains($0) } == true+ }+}
diff --git a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift b/Asterism/Asterism/ViewModels/SettingsBackupModel.swiftindex 44ddb7e6..c958acfd 100644--- a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift+++ b/Asterism/Asterism/ViewModels/SettingsBackupModel.swift@@ -5,7 +5,7 @@ import OSLog // MARK: - Backup Exporting Protocol /// Test seam abstracting the exporter's operations needed by the Settings-/// surface. Conforms `BackupV15Exporter` to this protocol via extension below.+/// surface. Conforms `BackupV16Exporter` 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@@ -13,12 +13,12 @@ import OSLog /// 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. public protocol BackupExporting: Sendable {- func export(metadata: BackupV15Metadata) async throws -> BackupExportResult+ func export(metadata: BackupV16Metadata) async throws -> BackupExportResult func cleanup(_ result: BackupExportResult) func scavengeStaleFiles() } -extension BackupV15Exporter: BackupExporting {}+extension BackupV16Exporter: BackupExporting {} // MARK: - Export Stage @@ -87,7 +87,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { stagedFileURL = nil do {- let metadata = BackupV15Metadata(+ let metadata = BackupV16Metadata( appBuild: Self.currentAppBuild(), exportedAt: Date() )@@ -120,7 +120,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { // MARK: - Refusal wording private static func routesToCheckLibrary(for error: Error) -> Bool {- guard let exportError = error as? BackupV15ExportError,+ guard let exportError = error as? BackupV16ExportError, case .tornGroups = exportError else { return false } return true@@ -141,7 +141,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { switch error { case is BackupCodecError: "Backup export failed due to an encoding error. Please try again."- case let error as BackupV15ExportError:+ case let error as BackupV16ExportError: exportMessage(for: error) default: "Backup export failed. Please try again."@@ -165,7 +165,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { /// (`character-extraction` Req 6.5, Q105). It needs no new sentence: the /// payload carries a count and a route, not a record kind, and Check Library /// is where every torn group is resolved.- private static func exportMessage(for error: BackupV15ExportError) -> String {+ private static func exportMessage(for error: BackupV16ExportError) -> String { switch error { case .tornGroups(let payload): tornGroupsMessage(payload)@@ -182,7 +182,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { // whole purpose is to send them to that work. Nothing else about the // record travels: not the bytes, not the digest, not the shape. case .unrepresentableValue(let record, let field, _)- where field == BackupV15ExportError.thumbnailField:+ where field == BackupV16ExportError.thumbnailField: "\(record) has a cover this backup cannot carry. Remove the cover in the work's " + "editor and export again — or, if the work is flagged as a duplicate, " + "resolve it first and the cover you keep will be backed up."@@ -220,7 +220,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { switch error { case let e as BackupCodecError: "codec: \(e)"- case let e as BackupV15ExportError:+ case let e as BackupV16ExportError: exportDiagnosticCategory(e) case let e as LibraryRepositoryError: "repository: \(e)"@@ -231,7 +231,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { /// The export refusals, by **category** rather than by message. ///- /// `BackupV15ExportError.description` is written for the reader and names+ /// `BackupV16ExportError.description` is written for the reader and names /// the record: `Work “<title>”` for a cover (`work-thumbnails` Req 8.3) and /// `Site <hostname>` for an unrepresentable site mode. The line above is /// logged `privacy: .public`, so interpolating that description would put a@@ -239,7 +239,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { /// process on the device can read. The refusal that names a record /// therefore logs its **field** — a compile-time constant — and the reader /// gets the title on screen, where it belongs.- private static func exportDiagnosticCategory(_ error: BackupV15ExportError) -> String {+ private static func exportDiagnosticCategory(_ error: BackupV16ExportError) -> String { switch error { case .unrepresentableValue(_, let field, _): "export: unrepresentable \(field)"
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel.swift b/Asterism/Asterism/ViewModels/WorkDetailModel.swiftindex 792d22a9..47770ff1 100644--- a/Asterism/Asterism/ViewModels/WorkDetailModel.swift+++ b/Asterism/Asterism/ViewModels/WorkDetailModel.swift@@ -411,6 +411,7 @@ public final class WorkDetailModel { /// neither this model's unit suite nor a UI-test launch ever touches a /// network (`work-thumbnails` Req 4.1, design Testing Strategy). private let coverFetcher: any CoverFetching+ private let calendar: Calendar private let onMutation: @Sendable () async -> Void /// Where a refused write goes (Req 2.10, Q47): the draft stays here, the /// conflict goes to the model that owns the banner and the listing.@@ -420,6 +421,7 @@ public final class WorkDetailModel { public init( workID: UUID, library: any LibraryProviding,+ calendar: Calendar, locale: Locale = .current, capabilities: AsterismCapabilities = .current, /// Find cover and the paste-URL branch's one seam@@ -431,6 +433,7 @@ public final class WorkDetailModel { ) { self.workID = workID self.library = library+ self.calendar = calendar self.locale = locale self.capabilities = capabilities self.coverFetcher = coverFetcher@@ -2032,7 +2035,7 @@ public final class WorkDetailModel { /// Enters the editor. A torn Work has no editor to enter (Req 2.8) — the /// repository would refuse the write, and the notice already says so. public func beginEditing() {- guard !isReadOnly else { return }+ guard state == .ready, !isReadOnly else { return } clearLastRefusal() // `work-thumbnails` Req 2.1: the Cover field opens on what the work // holds. Seeded here as well as at the load, because the load is what@@ -2741,7 +2744,8 @@ public final class WorkDetailModel { // with no loaded snapshot, where the toggles are what the // editor showed. releaseDays: ReleaseDay.canonical(draftReleaseDays))- let outcome = try await library.updateWork(id: workID, basis: basis, draft: draft)+ let outcome = try await library.updateWork(+ id: workID, basis: basis, draft: draft, calendar: calendar) if case .conflict(let conflict) = outcome { // No optimistic mutation and no draft reset: the edit is the // only copy of itself until the reader resolves the conflict.
diff --git a/Asterism/Asterism/Views/SetLatestSheet.swift b/Asterism/Asterism/Views/SetLatestSheet.swiftnew file mode 100644index 00000000..35369568--- /dev/null+++ b/Asterism/Asterism/Views/SetLatestSheet.swift@@ -0,0 +1,176 @@+import AsterismCore+import ConstellationKit+import SwiftUI++/// The model is @State-owned so a scene background/foreground cycle keeps drafts.+struct SetLatestSheet: View {+ @State private var model: SetLatestModel+ @Environment(\.dismiss) private var dismiss+ @Environment(\.openURL) private var openURL+ @Environment(\.siteNames) private var siteNames++ init(model: SetLatestModel) {+ _model = State(initialValue: model)+ }++ var body: some View {+ NavigationStack {+ ScrollView {+ VStack(alignment: .leading, spacing: 16) {+ if let work = model.work {+ header(work)+ latestCard+ lastReadCard+ if let url = work.primaryURL {+ Button("Check on \(siteNames.label(for: work.primaryHostname))") {+ openURL(url)+ }+ .buttonStyle(.constellationTertiary)+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityIdentifier("today-set-latest-check-site")+ }+ } else if model.isLoading {+ ProgressView("Loading latest chapter…")+ }+ if let error = model.errorMessage {+ Text(error)+ .foregroundStyle(AsterismColors.amberText)+ .fixedSize(horizontal: false, vertical: true)+ .accessibilityIdentifier("today-set-latest-error")+ }+ }+ .padding(20)+ }+ .navigationTitle("Latest released")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Cancel") { dismiss() }+ .disabled(model.isSaving)+ .accessibilityIdentifier("today-set-latest-cancel")+ }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") { Task { await model.save() } }+ .disabled(!model.canSave)+ .accessibilityIdentifier("today-set-latest-save")+ }+ }+ }+ .frame(minWidth: 320)+ .presentationDetents([.medium, .large])+ .interactiveDismissDisabled(model.isSaving)+ .accessibilityIdentifier("today-set-latest-sheet")+ .task { await model.load() }+ }++ private func header(_ work: WorkSnapshot) -> some View {+ HStack(alignment: .top, spacing: 12) {+ TodayCover(+ workID: work.id, thumbnail: work.thumbnail,+ hostname: work.primaryHostname,+ baseSize: CGSize(width: 48, height: 68), cornerRadius: 8)+ VStack(alignment: .leading, spacing: 5) {+ Text(work.displayTitle)+ .font(AsterismTypography.serif(.title3))+ .foregroundStyle(AsterismColors.primaryText)+ .fixedSize(horizontal: false, vertical: true)+ SiteLabel(+ hostname: work.primaryHostname,+ hostnameFont: .caption,+ hostnameColor: AsterismColors.secondaryText)+ if !work.releaseDays.isEmpty {+ Text("Releases " + ReleaseDaysText.abbreviated(+ work.releaseDays, calendar: model.displayedCalendar))+ .font(.caption)+ .foregroundStyle(AsterismColors.secondaryText)+ .fixedSize(horizontal: false, vertical: true)+ }+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(16)+ .constellationCard()+ }++ private var latestCard: some View {+ VStack(alignment: .leading, spacing: 12) {+ Text("Latest released")+ .font(.headline)+ .foregroundStyle(AsterismColors.primaryText)+ HStack(spacing: 12) {+ Button { model.adjustLatest(by: -1) } label: {+ Image(systemName: "minus")+ .frame(minWidth: 48, minHeight: 48)+ }+ .buttonStyle(.constellationSecondary)+ .accessibilityLabel("Decrease latest chapter")+ .accessibilityIdentifier("today-set-latest-decrease")++ TextField("Latest released", text: Binding(+ get: { model.latestText }, set: model.setLatestText))+ .wholeNumberKeyboard()+ .multilineTextAlignment(.center)+ .font(.system(size: 40, weight: .semibold, design: .rounded))+ .foregroundStyle(AsterismColors.cyan)+ .frame(maxWidth: .infinity, minHeight: AsterismLayout.minHitTarget)+ .accessibilityLabel(+ "Latest released, \(model.latestText.isEmpty ? "empty" : model.latestText)"+ + (model.latestIsEstimated ? ", estimated" : ""))+ .accessibilityAdjustableAction { direction in+ switch direction {+ case .increment: model.adjustLatest(by: 1)+ case .decrement: model.adjustLatest(by: -1)+ @unknown default: break+ }+ }+ .accessibilityIdentifier("today-set-latest-number")++ Button { model.adjustLatest(by: 1) } label: {+ Image(systemName: "plus")+ .frame(minWidth: 48, minHeight: 48)+ }+ .buttonStyle(.constellationSecondary)+ .accessibilityLabel("Increase latest chapter")+ .accessibilityIdentifier("today-set-latest-increase")+ }+ if model.latestIsEstimated {+ Text("estimated")+ .font(.caption)+ .foregroundStyle(AsterismColors.cyan)+ }+ if let caption = model.behindCaption {+ Text(caption)+ .font(.subheadline)+ .foregroundStyle(AsterismColors.secondaryText)+ .fixedSize(horizontal: false, vertical: true)+ .accessibilityIdentifier("today-set-latest-behind")+ }+ if model.showsCountUp {+ Toggle("Count up on release days", isOn: $model.countsUp)+ .accessibilityIdentifier("today-set-latest-count-up")+ }+ }+ .padding(16)+ .constellationCard()+ }++ private var lastReadCard: some View {+ VStack(alignment: .leading, spacing: 10) {+ Text("Your last chapter")+ .font(.headline)+ .foregroundStyle(AsterismColors.primaryText)+ if let lastRead = model.progress?.lastRead {+ Text("\(lastRead) · \(model.lastReadSourceText ?? "set by you")")+ .font(.caption)+ .foregroundStyle(AsterismColors.secondaryText)+ .fixedSize(horizontal: false, vertical: true)+ }+ TextField("Set or clear your last chapter", text: Binding(+ get: { model.overrideText }, set: model.setOverrideText))+ .wholeNumberKeyboard()+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityIdentifier("today-set-latest-last-read")+ }+ .padding(16)+ .constellationCard()+ }+}
diff --git a/Asterism/Asterism/Views/TodaySections.swift b/Asterism/Asterism/Views/TodaySections.swiftindex 1078c3ab..0e3ca197 100644--- a/Asterism/Asterism/Views/TodaySections.swift+++ b/Asterism/Asterism/Views/TodaySections.swift@@ -251,6 +251,8 @@ struct CatchUpCard: View { let currentDay: CivilDay let calendar: Calendar let onSelect: (UUID) -> Void+ let onSetLatest: (UUID) -> Void+ let onSetReadingStatus: (UUID, ReadingStatus) -> Void @State private var showsAll = false @@ -264,7 +266,8 @@ struct CatchUpCard: View { if index > 0 { hairline } CatchUpRowView( row: row, selectedDay: selectedDay, currentDay: currentDay,- calendar: calendar, onSelect: onSelect)+ calendar: calendar, onSelect: onSelect,+ onSetLatest: onSetLatest, onSetReadingStatus: onSetReadingStatus) } if let toggle = CatchUpText.toggleLabel(rowCount: rows.count, showsAll: showsAll) { hairline@@ -297,6 +300,8 @@ struct CatchUpRowView: View { let currentDay: CivilDay let calendar: Calendar let onSelect: (UUID) -> Void+ let onSetLatest: (UUID) -> Void+ let onSetReadingStatus: (UUID, ReadingStatus) -> Void @Environment(\.openURL) private var openURL @Environment(\.dynamicTypeSize) private var dynamicTypeSize@@ -309,32 +314,17 @@ struct CatchUpRowView: View { ? AnyLayout(VStackLayout(alignment: .leading, spacing: 8)) : AnyLayout(HStackLayout(spacing: 12)) layout {- Button {- onSelect(row.id)- } label: {- HStack(spacing: 12) {- TodayCover(- workID: row.id, thumbnail: row.thumbnail,- hostname: row.primaryHostname, baseSize: Self.coverSize,- cornerRadius: 6)- VStack(alignment: .leading, spacing: 3) {- Text(row.title)- .font(AsterismTypography.serif(.subheadline))- .foregroundStyle(AsterismColors.primaryText)- .lineLimit(dynamicTypeSize.isAccessibilitySize ? 3 : 1)- Text(status(spoken: false))- .font(.caption)- .foregroundStyle(AsterismColors.secondaryText)- .lineLimit(dynamicTypeSize.isAccessibilitySize ? nil : 2)+ if selectedDay == currentDay {+ primaryButton.contextMenu {+ Button("Set latest…") { onSetLatest(row.id) }+ if let url = row.primaryURL {+ Button("Open Work Page") { openURL(url) } }- Spacer(minLength: 0)+ Button("Move to Reading") { onSetReadingStatus(row.id, .reading) } }- .contentShape(Rectangle())+ } else {+ primaryButton }- .buttonStyle(.plain)- .accessibilityLabel("\(row.title), \(status(spoken: true))")- .accessibilityIdentifier(CatchUpText.rowIdentifier(row.id))- nextButton } .padding(.horizontal, 12)@@ -342,6 +332,56 @@ struct CatchUpRowView: View { .frame(minHeight: 70) } + private var primaryButton: some View {+ Button { onSelect(row.id) } label: {+ HStack(spacing: 12) {+ TodayCover(+ workID: row.id, thumbnail: row.thumbnail,+ hostname: row.primaryHostname, baseSize: Self.coverSize,+ cornerRadius: 6)+ VStack(alignment: .leading, spacing: 3) {+ Text(row.title)+ .font(AsterismTypography.serif(.subheadline))+ .foregroundStyle(AsterismColors.primaryText)+ .lineLimit(dynamicTypeSize.isAccessibilitySize ? nil : 1)+ if let progress = CatchUpText.progressLine(row) {+ GeometryReader { geometry in+ Capsule().fill(AsterismColors.cardBorder)+ .overlay(alignment: .leading) {+ Capsule().fill(AsterismColors.cyan)+ .frame(width: geometry.size.width * progressFraction)+ }+ }+ .frame(height: 4)+ .accessibilityHidden(true)+ Text(progress)+ .font(.caption2)+ .foregroundStyle(AsterismColors.cyan)+ .accessibilityHidden(true)+ }+ Text(status(spoken: false))+ .font(.caption)+ .foregroundStyle(+ row.progress.state == .exact || row.progress.state == .estimated+ ? AsterismColors.cyan : AsterismColors.secondaryText)+ .lineLimit(dynamicTypeSize.isAccessibilitySize ? nil : 2)+ }+ Spacer(minLength: 0)+ }+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityLabel(CatchUpText.accessibilityLabel(+ row, selectedDay: selectedDay, currentDay: currentDay, calendar: calendar))+ .accessibilityIdentifier(CatchUpText.rowIdentifier(row.id))+ }++ private var progressFraction: CGFloat {+ guard let read = row.progress.lastRead,+ let latest = row.progress.effectiveLatest, latest > 0 else { return 0 }+ return min(1, max(0, CGFloat(read) / CGFloat(latest)))+ }+ private func status(spoken: Bool) -> String { CatchUpText.status( row, selectedDay: selectedDay, currentDay: currentDay, calendar: calendar,@@ -363,11 +403,53 @@ struct CatchUpRowView: View { Text(CatchUpText.nextLabel(row)).constellationPill(.count) } .buttonStyle(.plain)+ .frame(minWidth: AsterismLayout.minHitTarget, minHeight: AsterismLayout.minHitTarget) .accessibilityLabel(CatchUpText.nextAccessibilityLabel(row)) .accessibilityIdentifier(CatchUpText.nextIdentifier(row.id)) } } +/// The reader alone decides whether a caught-up work leaves Catching up.+struct CatchUpBanner: View {+ let row: ReleaseRow+ let onSetLatest: (UUID) -> Void+ let onSetReadingStatus: (UUID, ReadingStatus) -> Void++ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ Text(CatchUpText.bannerTitle(row.title))+ .font(AsterismTypography.serif(.subheadline))+ .foregroundStyle(AsterismColors.primaryText)+ .fixedSize(horizontal: false, vertical: true)+ ViewThatFits(in: .horizontal) {+ actions+ actionsVertical+ }+ }+ .padding(16)+ .constellationCard()+ .accessibilityElement(children: .contain)+ .accessibilityIdentifier("today-catchup-banner-\(row.id.uuidString)")+ }++ private var actions: some View {+ HStack(spacing: 8) { buttons }+ }++ private var actionsVertical: some View {+ VStack(alignment: .leading, spacing: 4) { buttons }+ }++ @ViewBuilder private var buttons: some View {+ Button(CatchUpText.primaryButtonLabel(row.workStatus)) {+ onSetReadingStatus(row.id, CatchUpText.primaryReadingStatus(row.workStatus))+ }+ .buttonStyle(.constellationSecondary)+ Button("Not yet, more is out") { onSetLatest(row.id) }+ .buttonStyle(.constellationTertiary)+ }+}+ // MARK: - Noted timeline (§8) /// One note on the selected day: a dot and its time on a vertical rule, then the
diff --git a/Asterism/Asterism/Views/TodayText.swift b/Asterism/Asterism/Views/TodayText.swiftindex 29299774..0bee5def 100644--- a/Asterism/Asterism/Views/TodayText.swift+++ b/Asterism/Asterism/Views/TodayText.swift@@ -307,10 +307,7 @@ nonisolated enum ReleaseShelfText { } } -/// The catching-up card's words and order (Today v2 §5), for the one state-/// the library can answer today: what was last read, when, and how many-/// release days have passed since. The handover's exact and estimated states-/// need a latest-released chapter, which no work records yet.+/// The catching-up card's words and order for the selected day. nonisolated enum CatchUpText { /// Rows the card shows before `Show all`. static let collapsedLimit = 5@@ -330,11 +327,26 @@ nonisolated enum CatchUpText { static func nextIdentifier(_ id: UUID) -> String { "today-catchup-next-\(id.uuidString)" } static let showAllIdentifier = "today-catchup-show-all" - /// Stalest first: never read, then the oldest last-read day. Ties keep the- /// order they arrived in, which is `titleOrder`.+ /// Known distances first, most behind first; then caught up; then unknown+ /// by the oldest read day. Equal values keep the incoming title order. static func ordered(_ rows: [ReleaseRow]) -> [ReleaseRow] { rows.enumerated().sorted { lhs, rhs in- switch (lhs.element.lastNotedDay, rhs.element.lastNotedDay) {+ let left = lhs.element+ let right = rhs.element+ func rank(_ row: ReleaseRow) -> Int {+ switch row.progress.state {+ case .exact, .estimated: 0+ case .caughtUp: 1+ case .unknown: 2+ }+ }+ if rank(left) != rank(right) { return rank(left) < rank(right) }+ if rank(left) == 0, left.progress.behind != right.progress.behind {+ return (left.progress.behind ?? 0) > (right.progress.behind ?? 0)+ }+ guard rank(left) == 2 else { return lhs.offset < rhs.offset }+ switch (left.progress.readDay ?? left.lastNotedDay,+ right.progress.readDay ?? right.lastNotedDay) { case (nil, nil): return lhs.offset < rhs.offset case (nil, _): return true case (_, nil): return false@@ -354,6 +366,44 @@ nonisolated enum CatchUpText { _ row: ReleaseRow, selectedDay: CivilDay, currentDay: CivilDay, calendar: Calendar, spoken: Bool = false ) -> String {+ switch row.progress.state {+ case .exact, .estimated:+ guard let behind = row.progress.behind else { return "Not read yet" }+ let word = chapterWord(behind, type: row.typeDisplay)+ if row.progress.state == .estimated {+ return "~\(behind) \(word) behind · estimated"+ }+ var value = "\(behind) \(word) behind"+ if let confirmed = row.progress.confirmedDay,+ calendar.dateComponents(+ [.day], from: confirmed.date(in: calendar),+ to: selectedDay.date(in: calendar)).day.map({ $0 > 7 }) == true+ {+ value += " · as of " + ReleaseLineText.relativeDay(+ RelativeDay(noted: confirmed, selected: selectedDay, calendar: calendar),+ calendar: calendar)+ }+ return value+ case .caughtUp:+ return "Caught up"+ case .unknown:+ break+ }+ if let read = row.progress.lastRead {+ let chapter = spoken+ ? ChapterNumberText.spoken(read, type: row.typeDisplay)+ : ChapterNumberText.short(read, type: row.typeDisplay)+ var parts = ["Last read \(chapter)"]+ if let readDay = row.progress.readDay {+ parts.append(readDay == selectedDay ? "today" : ReleaseLineText.relativeDay(+ RelativeDay(noted: readDay, selected: selectedDay, calendar: calendar),+ calendar: calendar))+ }+ if let since = row.releasesSince, since > 0 {+ parts.append("~\(Pluralisation.count(since, "release", "releases")) since")+ }+ return parts.joined(separator: " · ")+ } let chapter = row.lastChapter.map { spoken@@ -383,6 +433,54 @@ nonisolated enum CatchUpText { return parts.joined(separator: " · ") } + static func progressLine(_ row: ReleaseRow) -> String? {+ guard let read = row.progress.lastRead,+ let latest = row.progress.effectiveLatest else { return nil }+ switch row.progress.state {+ case .exact: return "\(read)/\(latest)"+ case .estimated: return "\(read)/~\(latest)"+ case .unknown, .caughtUp: return nil+ }+ }++ static func accessibilityLabel(+ _ row: ReleaseRow, selectedDay: CivilDay, currentDay: CivilDay, calendar: Calendar+ ) -> String {+ switch row.progress.state {+ case .exact, .estimated:+ guard let behind = row.progress.behind,+ let read = row.progress.lastRead,+ let latest = row.progress.effectiveLatest else { return row.title }+ let word = chapterWord(behind, type: row.typeDisplay)+ let spoken = chapterWord(1, type: row.typeDisplay)+ let estimate = row.progress.state == .estimated ? ", estimated" : ""+ return "\(row.title), \(behind) \(word) behind, \(spoken) \(read) of \(latest)\(estimate)"+ case .caughtUp:+ return "\(row.title), caught up"+ case .unknown:+ let spokenStatus = status(+ row, selectedDay: selectedDay, currentDay: currentDay,+ calendar: calendar, spoken: true)+ return "\(row.title), \(spokenStatus)"+ }+ }++ static func bannerTitle(_ title: String) -> String { "Caught up on \(title)." }++ static func primaryButtonLabel(_ status: WorkStatus) -> String {+ status == .finished ? "Mark Finished" : "Move to Reading"+ }++ static func primaryReadingStatus(_ status: WorkStatus) -> ReadingStatus {+ status == .finished ? .finished : .reading+ }++ private static func chapterWord(_ count: Int, type: WorkTypeDisplay) -> String {+ let episodes = ChapterNumberText.countsEpisodes(type)+ if episodes { return count == 1 ? "episode" : "episodes" }+ return count == 1 ? "chapter" : "chapters"+ }+ /// The `Next` capsule's label: the next chapter where there is a whole /// number to add one to, `Open` otherwise. static func nextLabel(_ row: ReleaseRow) -> String {
diff --git a/Asterism/Asterism/Views/TodayView.swift b/Asterism/Asterism/Views/TodayView.swiftindex be779adf..015e41fe 100644--- a/Asterism/Asterism/Views/TodayView.swift+++ b/Asterism/Asterism/Views/TodayView.swift@@ -79,6 +79,8 @@ struct TodayView: View { /// Req 5.3: a release row opens the work — on Today's own stack (Q38), which /// is the caller's business and not this screen's. let onSelectWork: (UUID) -> Void+ let onSetLatest: (UUID) -> Void+ let onSetReadingStatus: (UUID, ReadingStatus) async throws -> LibraryWriteOutcome /// Req 10.1's prune, **on the wide tree only** (Q43): the detail column /// clears when the row it is showing is no longer in this list. Nil in the /// compact tree, where a push stays until the reader pops it.@@ -125,6 +127,8 @@ struct TodayView: View { @State private var showingActionableOnly = false @State private var showingDuplicatesOnly = false+ @State private var catchUpActionError: String?+ @State private var showingCatchUpActionError = false init( presentation: TodayPresentation,@@ -156,6 +160,8 @@ struct TodayView: View { onPageWeek: @escaping (Int) -> Void = { _ in }, onSelectToday: @escaping () -> Void = {}, onSelectWork: @escaping (UUID) -> Void = { _ in },+ onSetLatest: @escaping (UUID) -> Void = { _ in },+ onSetReadingStatus: @escaping (UUID, ReadingStatus) async throws -> LibraryWriteOutcome = { _, _ in .committed }, onPruneSelection: ((TodayVisibility) -> Void)? = nil, onShowSettings: (() -> Void)? = nil ) {@@ -184,6 +190,8 @@ struct TodayView: View { self.onPageWeek = onPageWeek self.onSelectToday = onSelectToday self.onSelectWork = onSelectWork+ self.onSetLatest = onSetLatest+ self.onSetReadingStatus = onSetReadingStatus self.onPruneSelection = onPruneSelection self.onShowSettings = onShowSettings }@@ -248,6 +256,11 @@ struct TodayView: View { // never reaches the screen (verified in the simulator — pure black). // In the wide tree the window owns it instead (Req 3.1). .screenSky(showsSky)+ .alert("Couldn’t update reading status", isPresented: $showingCatchUpActionError) {+ Button("OK", role: .cancel) { catchUpActionError = nil }+ } message: {+ Text(catchUpActionError ?? "")+ } // No search field (`launch-to-today` Req 5.1, Decision 1): Today is a // dashboard. The filter stays in the plan, unreachable until T-2347. .onChange(of: presentation.actionableCount) { _, newCount in@@ -504,15 +517,31 @@ struct TodayView: View { @ViewBuilder private func catchingUpSection(_ plan: TodayDisplayPlan) -> some View { if !plan.day.catchingUp.isEmpty {+ let current = plan.day.day == currentDay+ let banners = current+ ? plan.day.catchingUp.filter { $0.progress.state == .caughtUp }+ : []+ let cardRows = current+ ? plan.day.catchingUp.filter { $0.progress.state != .caughtUp }+ : plan.day.catchingUp Section {- // Today v2 §5: one card, one compact row per work.- CatchUpCard(- rows: CatchUpText.ordered(plan.day.catchingUp),- selectedDay: plan.day.day,- currentDay: currentDay,- calendar: calendar,- onSelect: onSelectWork)- .constellationListRow()+ ForEach(banners) { row in+ CatchUpBanner(+ row: row, onSetLatest: onSetLatest,+ onSetReadingStatus: handleReadingStatus)+ .constellationListRow()+ }+ if !cardRows.isEmpty {+ CatchUpCard(+ rows: CatchUpText.ordered(cardRows),+ selectedDay: plan.day.day,+ currentDay: currentDay,+ calendar: calendar,+ onSelect: onSelectWork,+ onSetLatest: onSetLatest,+ onSetReadingStatus: handleReadingStatus)+ .constellationListRow()+ } } header: { ConstellationSectionHeader( TodayTitleText.catchingUpHeader,@@ -523,6 +552,25 @@ struct TodayView: View { } } + private func handleReadingStatus(_ id: UUID, _ status: ReadingStatus) {+ Task {+ do {+ let outcome = try await onSetReadingStatus(id, status)+ if case .conflict(let conflict) = outcome {+ // A stale banner disappears on the refresh the app model+ // performs; a torn group needs the same route explanation+ // the Work page gives.+ if case .recordChanged = conflict { return }+ catchUpActionError = EntryDetailModel.conflictMessage(conflict)+ showingCatchUpActionError = true+ }+ } catch {+ catchUpActionError = error.localizedDescription+ showingCatchUpActionError = true+ }+ }+ }+ /// The releases section's vertical rows, drawn at the accessibility sizes /// where a 98 pt shelf cover cannot hold the title (Today v2 §4). @ViewBuilder
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex 111be937..e5d202ce 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -26,6 +26,7 @@ import UniformTypeIdentifiers /// view mode. struct WorkDetailView: View { @State private var model: WorkDetailModel+ @State private var pendingLatestRefresh = false @Environment(\.dismiss) private var dismiss @Environment(\.openURL) private var openURL /// `site-display-names`: what the site picker and the identity review menu@@ -54,6 +55,12 @@ struct WorkDetailView: View { /// route to push onto. Navigation is `ContentView`'s (the house rule), so /// the screen reports the tap rather than resolving a destination. let onSelectEntry: ((UUID) -> Void)?+ /// The window owns this sheet; the Merge preview has no route to it.+ let onSetLatest: ((UUID) -> Void)?+ let currentDay: CivilDay+ let calendar: Calendar+ let lastSavedLatestWorkID: UUID?+ let latestSaveGeneration: Int /// Where a committed merge leaves the reader (Req 4.6): the Work that /// survived it. Nil where the host has no route — the Merge sheet's own /// embedded copy of this screen — and the screen dismisses instead, which is@@ -131,8 +138,13 @@ struct WorkDetailView: View { init( model: WorkDetailModel,+ currentDay: CivilDay,+ calendar: Calendar,+ lastSavedLatestWorkID: UUID? = nil,+ latestSaveGeneration: Int = 0, onResolveDuplicate: (() -> Void)? = nil, onSelectEntry: ((UUID) -> Void)? = nil,+ onSetLatest: ((UUID) -> Void)? = nil, onMergeCommitted: ((UUID) -> Void)? = nil, onSelectWork: ((UUID) -> Void)? = nil, onSelectSeries: ((UUID) -> Void)? = nil,@@ -142,9 +154,14 @@ struct WorkDetailView: View { extraction: CharacterExtractionCoordinator? = nil ) { _model = State(initialValue: model)+ self.currentDay = currentDay+ self.calendar = calendar+ self.lastSavedLatestWorkID = lastSavedLatestWorkID+ self.latestSaveGeneration = latestSaveGeneration _exportModel = State(initialValue: exportModel) self.onResolveDuplicate = onResolveDuplicate self.onSelectEntry = onSelectEntry+ self.onSetLatest = onSetLatest self.onMergeCommitted = onMergeCommitted self.onSelectWork = onSelectWork self.onSelectSeries = onSelectSeries@@ -205,6 +222,16 @@ struct WorkDetailView: View { .intentEditSession(active: model.isEditing || presentsSheet) .screenSky(showsSky) .task { await model.load() }+ .onChange(of: latestSaveGeneration) { _, newGeneration in+ guard newGeneration > 0,+ lastSavedLatestWorkID == model.work?.id else { return }+ refreshAfterLatestSave()+ }+ .onChange(of: model.isEditing) { wasEditing, isEditing in+ guard wasEditing, !isEditing, pendingLatestRefresh else { return }+ pendingLatestRefresh = false+ refreshAfterLatestSave()+ } // A committed deletion takes the screen with it — there is nothing left // to show and nothing to go back to. .onChange(of: model.isDeleted) { _, deleted in@@ -566,6 +593,30 @@ struct WorkDetailView: View { } } + if !model.isEditing,+ work.readingStatus == .reading || work.readingStatus == .catchingUp,+ let onSetLatest+ {+ Button { onSetLatest(work.id) } label: {+ HStack(alignment: .firstTextBaseline, spacing: 10) {+ Text("Latest released")+ .foregroundStyle(AsterismColors.secondaryText)+ Spacer(minLength: 0)+ Text(latestReleasedLine(work))+ .foregroundStyle(AsterismColors.cyan)+ Image(systemName: "chevron.right")+ .font(.caption.weight(.semibold))+ .accessibilityHidden(true)+ }+ .font(.subheadline)+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: .infinity, minHeight: AsterismLayout.minHitTarget)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityIdentifier("work-detail-latest-released")+ }+ // Q96: the credits read as the work's top-level metadata, // beside the site rather than as a section of their own — // stacked here, under the site row and above the pills.@@ -792,6 +843,27 @@ struct WorkDetailView: View { .accessibilityIdentifier("work-detail-pulse") } + private func latestReleasedLine(_ work: WorkSnapshot) -> String {+ let progress = CatchUpProgress.build(+ work: work, day: currentDay, calendar: calendar)+ guard let latest = progress.effectiveLatest else { return "Not set" }+ let estimated = latest != work.catchUp.latest+ || work.catchUp.confirmation?.isEstimate == true+ return "\(estimated ? "~" : "")\(latest)"+ }++ private func refreshAfterLatestSave() {+ Task {+ // A reader may enter edit mode after the generation changes but+ // before this task runs. Keep the draft and refresh on leaving it.+ guard !model.isEditing else {+ pendingLatestRefresh = true+ return+ }+ await model.load()+ }+ }+ // MARK: - Edit mode /// Edit mode's first section: **one** card holding what the work *is* — the@@ -1783,7 +1855,7 @@ struct WorkDetailView: View { } // A torn Work has no editor to enter: the repository refuses // the write and the notice above already says why (Req 2.8).- .disabled(model.state == .submitting || model.isReadOnly)+ .disabled(model.state != .ready || model.isReadOnly) .accessibilityIdentifier("work-detail-edit-button") .accessibilityLabel("Edit this work") }
diff --git a/Asterism/AsterismTests/AppLibraryModelTests.swift b/Asterism/AsterismTests/AppLibraryModelTests.swiftindex 830478bf..6492fd21 100644--- a/Asterism/AsterismTests/AppLibraryModelTests.swift+++ b/Asterism/AsterismTests/AppLibraryModelTests.swift@@ -1266,7 +1266,7 @@ struct AppLibraryModelLaunchTests { let root = Self.temporaryRoot() defer { try? FileManager.default.removeItem(at: root) } // The fixture with a schedule worth comparing: two works due on a day,- // one kept off it by its status, one being caught up on.+ // one kept off it by status, and four being caught up on. let model = Self.launchedModel(at: root, fixture: .today) await model.bootstrap()@@ -1275,7 +1275,7 @@ struct AppLibraryModelLaunchTests { let titlesAtLaunch = model.workTitlesByID #expect(!scheduleAtLaunch.works.isEmpty) #expect(!scheduleAtLaunch.catchingUp.isEmpty)- #expect(titlesAtLaunch.count == 4)+ #expect(titlesAtLaunch.count == 7) await model.waitForLaunchTail()
diff --git a/Asterism/AsterismTests/BackupExportStageTests.swift b/Asterism/AsterismTests/BackupExportStageTests.swiftindex 198bd0f9..140e718a 100644--- a/Asterism/AsterismTests/BackupExportStageTests.swift+++ b/Asterism/AsterismTests/BackupExportStageTests.swift@@ -48,7 +48,7 @@ struct BackupExportStageTests { @MainActor func tornRefusalRoutesToCheckLibrary() async { let exporter = RecordingBackupExporter() exporter.exportResult = .failure(- BackupV15ExportError.tornGroups(+ BackupV16ExportError.tornGroups( TornGroupsPayload(count: 3, blockingWorkSet: nil))) let stage = BackupExportStage(exporter: exporter) @@ -68,14 +68,14 @@ struct BackupExportStageTests { /// Every other refusal is either transient or a state no screen can act on, /// and a button routing to neither is worse than no button. @Test("Every other refusal has a message and no route", arguments: [- BackupV15ExportError.referencesStillArriving(detail: "rule 1"),- BackupV15ExportError.unrepresentableValue(+ BackupV16ExportError.referencesStillArriving(detail: "rule 1"),+ BackupV16ExportError.unrepresentableValue( record: "Character", field: "factsData", value: "…"),- BackupV15ExportError.snapshotFailed(reason: "read"),- BackupV15ExportError.encodingFailed(reason: "encode"),- BackupV15ExportError.stagingFailed(reason: "stage"),+ BackupV16ExportError.snapshotFailed(reason: "read"),+ BackupV16ExportError.encodingFailed(reason: "encode"),+ BackupV16ExportError.stagingFailed(reason: "stage"), ])- @MainActor func otherRefusalsOfferNoRoute(error: BackupV15ExportError) async {+ @MainActor func otherRefusalsOfferNoRoute(error: BackupV16ExportError) async { let exporter = RecordingBackupExporter() exporter.exportResult = .failure(error) let stage = BackupExportStage(exporter: exporter)@@ -100,9 +100,9 @@ struct BackupExportStageTests { @MainActor func coverRefusalNamesTheWorkAndNothingElse() async { let exporter = RecordingBackupExporter() exporter.exportResult = .failure(- BackupV15ExportError.unrepresentableValue(+ BackupV16ExportError.unrepresentableValue( record: "Work “Actual Title”",- field: BackupV15ExportError.thumbnailField,+ field: BackupV16ExportError.thumbnailField, value: "17 bytes that are not a portrait cover")) let stage = BackupExportStage(exporter: exporter) @@ -129,9 +129,9 @@ struct BackupExportStageTests { @Test("The logged category names the field, never the record") @MainActor func diagnosticCategoryCarriesNoReaderContent() { let cover = BackupExportStage.diagnosticCategory(- for: BackupV15ExportError.unrepresentableValue(+ for: BackupV16ExportError.unrepresentableValue( record: "Work “Actual Title”",- field: BackupV15ExportError.thumbnailField,+ field: BackupV16ExportError.thumbnailField, value: "17 bytes that are not a portrait cover")) #expect(cover == "export: unrepresentable thumbnail")@@ -141,7 +141,7 @@ struct BackupExportStageTests { // The same hole the cover arm would have opened has been standing on // the site arm since the refusal was written. let site = BackupExportStage.diagnosticCategory(- for: BackupV15ExportError.unrepresentableValue(+ for: BackupV16ExportError.unrepresentableValue( record: "Site reader.example", field: "mode", value: "hexagonal")) #expect(site == "export: unrepresentable mode")@@ -151,7 +151,7 @@ struct BackupExportStageTests { // The refusals that name no record keep their whole description: a // count and a route carry nothing of the reader's. let torn = BackupExportStage.diagnosticCategory(- for: BackupV15ExportError.tornGroups(+ for: BackupV16ExportError.tornGroups( TornGroupsPayload(count: 2, blockingWorkSet: nil))) #expect(torn.hasPrefix("export: ")) #expect(torn.contains("2 records"))@@ -235,7 +235,7 @@ private struct TemporaryStaging { } /// Records what the stage asked of the exporter, and — unlike the backup row's-/// mock — removes the staged file on cleanup, as `BackupV15Exporter` does.+/// mock — removes the staged file on cleanup, as `BackupV16Exporter` does. private final class RecordingBackupExporter: BackupExporting, @unchecked Sendable { var exportCallCount = 0 var cleanupCallCount = 0@@ -243,9 +243,9 @@ private final class RecordingBackupExporter: BackupExporting, @unchecked Sendabl var lastCleanupURL: URL? var exportResult: Result<BackupExportResult, Error> = .failure(- BackupV15ExportError.snapshotFailed(reason: "not configured"))+ BackupV16ExportError.snapshotFailed(reason: "not configured")) - func export(metadata: BackupV15Metadata) async throws -> BackupExportResult {+ func export(metadata: BackupV16Metadata) async throws -> BackupExportResult { exportCallCount += 1 return try exportResult.get() }
diff --git a/Asterism/AsterismTests/EmptyLibraryModelTests.swift b/Asterism/AsterismTests/EmptyLibraryModelTests.swiftindex 26749997..089d48be 100644--- a/Asterism/AsterismTests/EmptyLibraryModelTests.swift+++ b/Asterism/AsterismTests/EmptyLibraryModelTests.swift@@ -158,7 +158,7 @@ struct EmptyLibraryModelTests { func aTornRefusalRoutesToCheckLibrary() async { let harness = Harness() harness.exporter.exportResult = .failure(- BackupV15ExportError.tornGroups(TornGroupsPayload(count: 3, blockingWorkSet: nil)))+ BackupV16ExportError.tornGroups(TornGroupsPayload(count: 3, blockingWorkSet: nil))) await harness.confirm() @@ -175,7 +175,7 @@ struct EmptyLibraryModelTests { func anUnroutedRefusalOffersNoRoute() async { let harness = Harness() harness.exporter.exportResult = .failure(- BackupV15ExportError.referencesStillArriving(detail: "rule 1"))+ BackupV16ExportError.referencesStillArriving(detail: "rule 1")) await harness.confirm() @@ -397,7 +397,7 @@ struct EmptyLibraryModelTests { harness.model.cancelConfirmation() harness.exporter.exportResult = .failure(- BackupV15ExportError.encodingFailed(reason: "encode"))+ BackupV16ExportError.encodingFailed(reason: "encode")) await harness.confirm() #expect(harness.failureMessage != nil) @@ -568,14 +568,14 @@ private actor PassGate { } /// Records what the stage asked of the exporter, and removes the staged file on-/// cleanup as `BackupV15Exporter` does.+/// cleanup as `BackupV16Exporter` does. private final class RecordingBackupExporter: BackupExporting, @unchecked Sendable { var exportCallCount = 0 var cleanupCallCount = 0 var exportResult: Result<BackupExportResult, Error> = .failure(- BackupV15ExportError.snapshotFailed(reason: "not configured"))+ BackupV16ExportError.snapshotFailed(reason: "not configured")) - func export(metadata: BackupV15Metadata) async throws -> BackupExportResult {+ func export(metadata: BackupV16Metadata) async throws -> BackupExportResult { exportCallCount += 1 return try exportResult.get() }
diff --git a/Asterism/AsterismTests/EntryDetailModelTests.swift b/Asterism/AsterismTests/EntryDetailModelTests.swiftindex b9774c88..b5be5e90 100644--- a/Asterism/AsterismTests/EntryDetailModelTests.swift+++ b/Asterism/AsterismTests/EntryDetailModelTests.swift@@ -443,6 +443,13 @@ struct EntryDetailModelTests { #expect(message.contains("deleting")) } + @Test("A stale narrow action tells the reader to reopen")+ @MainActor func changedRecordMessage() {+ let message = EntryDetailModel.conflictMessage(.recordChanged(recordID: UUID()))+ #expect(message.contains("changed on another device"))+ #expect(message.contains("Close and reopen"))+ }+ // MARK: - What the title card says (Q51) /// The screen showed the raw capture title, so the row a reader tapped in
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex d5586a25..f1c08bb9 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -32,6 +32,9 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { var deleteEntryResult: Result<LibraryWriteOutcome, Error> = .success(.committed) var createWorkResult: Result<WorkSnapshot, Error> = .failure(MockError.notConfigured) var updateWorkResult: Result<LibraryWriteOutcome, Error> = .success(.committed)+ var catchUpSheetStateResult: Result<CatchUpSheetState, Error> = .failure(MockError.notConfigured)+ var commitCatchUpProgressResult: Result<LibraryWriteOutcome, Error> = .success(.committed)+ var setReadingStatusResult: Result<LibraryWriteOutcome, Error> = .success(.committed) var moveEntryResult: Result<LibraryWriteOutcome, Error> = .success(.committed) var workDestinationsResult: Result<[WorkSnapshot], Error> = .success([]) /// Q46's flag, as the background-export pass reads it (Req 1.10). Named@@ -57,6 +60,9 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { var lastMoveDestination: WorkDestination? var lastUpdateEntryBasis: EntryEditBasis? var lastUpdateWorkBasis: WorkEditBasis?+ var lastUpdateWorkCalendar: Calendar?+ var lastCatchUpDraft: CatchUpDraft?+ var lastCatchUpBasis: CatchUpRecord? /// What the editor actually sent. Recorded beside the basis because /// `updateWork` writes every field of the draft to every row of the group /// (Req 7.1 of `work-and-reading-status`): a draft that quietly carried a@@ -181,15 +187,36 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { var updateWorkResultsByWorkID: [UUID: Result<LibraryWriteOutcome, Error>] = [:] func updateWork(- id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft+ id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar ) async throws -> LibraryWriteOutcome { updateWorkCallCount += 1 lastUpdateWorkBasis = basis+ lastUpdateWorkCalendar = calendar lastUpdateWorkDraft = draft updateWorkCalls.append((id, basis, draft)) return try (updateWorkResultsByWorkID[id] ?? updateWorkResult).get() } + func catchUpSheetState(+ workID: UUID, day: CivilDay, calendar: Calendar+ ) async throws -> CatchUpSheetState {+ try catchUpSheetStateResult.get()+ }++ func commitCatchUpProgress(+ id: UUID, basis: CatchUpRecord, draft: CatchUpDraft+ ) async throws -> LibraryWriteOutcome {+ lastCatchUpBasis = basis+ lastCatchUpDraft = draft+ return try commitCatchUpProgressResult.get()+ }++ func setReadingStatus(+ id: UUID, expected: ReadingStatus, to: ReadingStatus+ ) async throws -> LibraryWriteOutcome {+ try setReadingStatusResult.get()+ }+ func moveEntry( _ entryID: UUID, basis: EntryAssignmentBasis, to destination: WorkDestination ) async throws -> LibraryWriteOutcome {
diff --git a/Asterism/AsterismTests/Helpers/RepositoryWriteTestSupport.swift b/Asterism/AsterismTests/Helpers/RepositoryWriteTestSupport.swiftindex 5707c4b9..12218c8c 100644--- a/Asterism/AsterismTests/Helpers/RepositoryWriteTestSupport.swift+++ b/Asterism/AsterismTests/Helpers/RepositoryWriteTestSupport.swift@@ -34,9 +34,11 @@ extension LibraryProviding { try await deleteEntry(id: id, basis: basis, disclosedVariants: nil)) } - func updateWork(id: UUID, draft: WorkMetadataDraft) async throws {+ func updateWork(+ id: UUID, draft: WorkMetadataDraft, calendar: Calendar = .current+ ) async throws { let basis = WorkEditBasis(work: try await work(id: id))- try requireCommitted(try await updateWork(id: id, basis: basis, draft: draft))+ try requireCommitted(try await updateWork(id: id, basis: basis, draft: draft, calendar: calendar)) } func moveEntry(_ entryID: UUID, to destination: WorkDestination) async throws {
diff --git a/Asterism/AsterismTests/Helpers/WorkDetailModelTestSupport.swift b/Asterism/AsterismTests/Helpers/WorkDetailModelTestSupport.swiftindex 7b5a6b84..1dbb032b 100644--- a/Asterism/AsterismTests/Helpers/WorkDetailModelTestSupport.swift+++ b/Asterism/AsterismTests/Helpers/WorkDetailModelTestSupport.swift@@ -25,6 +25,7 @@ import Foundation func makeWorkDetailModel( workID: UUID, library: any LibraryProviding,+ calendar: Calendar = .current, locale: Locale = .current, capabilities: AsterismCapabilities = .current, coverFetcher: any CoverFetching = StubCoverFetcher(),@@ -34,6 +35,7 @@ func makeWorkDetailModel( WorkDetailModel( workID: workID, library: library,+ calendar: calendar, locale: locale, capabilities: capabilities, coverFetcher: coverFetcher,
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex 8953b00b..aecfacfb 100644--- a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift+++ b/Asterism/AsterismTests/IntegrationSafetyNetTests.swift@@ -152,13 +152,13 @@ struct IntegrationSafetyNetTests { workStatus: .ongoing, readingStatus: .reading, verdict: "" , releaseDays: [], membership: nil, thumbnail: .keep)- )+ , calendar: .current) let stagingDirectory = fixture.baseDirectory.appending(path: "validated-backups")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: stagingDirectory)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: stagingDirectory) let exportedAt = Date(timeIntervalSince1970: 1_784_246_400) let result = try await exporter.export(- metadata: BackupV15Metadata(+ metadata: BackupV16Metadata( 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 BackupV15Codec.decode(encoded)- let source = try await repository.backupV15Snapshot()+ let decoded = try BackupV16Codec.decode(encoded)+ let source = try await repository.backupV16Snapshot() #expect(decoded.payload == source) #expect(decoded.payload.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 BackupV15Codec.decode(Data(contentsOf: backupURL))+ let document = try BackupV16Codec.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 = BackupV15Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+ let exporter = BackupV16Exporter(repository: sourceRepo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "fill-test", exportedAt: Date())+ metadata: BackupV16Metadata(appBuild: "fill-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } let backupData = try Data(contentsOf: exportResult.fileURL)@@ -398,9 +398,9 @@ struct IntegrationSafetyNetTests { ) ) let stagingDir = fixture.baseDirectory.appending(path: "restore-stage")- let exporter = BackupV15Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+ let exporter = BackupV16Exporter(repository: sourceRepo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "restore-test", exportedAt: Date())+ metadata: BackupV16Metadata(appBuild: "restore-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } let plan = try BackupImporter.plan(from: try Data(contentsOf: exportResult.fileURL))@@ -697,7 +697,7 @@ struct IntegrationSafetyNetTests { workStatus: .ongoing, readingStatus: .reading, verdict: "" , releaseDays: [], membership: nil, thumbnail: .keep)- )+ , calendar: .current) // Project merge let mergeContract = try await repo.projectMerge(@@ -842,15 +842,15 @@ struct IntegrationSafetyNetTests { ) let stagingDir = fixture.baseDirectory.appending(path: "corrupt-stage")- let exporter = BackupV15Exporter(repository: repo, stagingDirectory: stagingDir)+ let exporter = BackupV16Exporter(repository: repo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "corrupt-test", exportedAt: Date())+ metadata: BackupV16Metadata(appBuild: "corrupt-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } // Verify good backup decodes let goodData = try Data(contentsOf: exportResult.fileURL)- let decoded = try BackupV15Codec.decode(goodData)+ let decoded = try BackupV16Codec.decode(goodData) #expect(decoded.payload.entries.count == 1) // Corrupt the data by flipping bytes in the payload area@@ -863,7 +863,7 @@ struct IntegrationSafetyNetTests { // Corrupted backup should fail decode/checksum do {- _ = try BackupV15Codec.decode(corruptData)+ _ = try BackupV16Codec.decode(corruptData) Issue.record("Expected corrupted backup to fail validation") } catch { // Expected: checksum or decode failure@@ -950,13 +950,13 @@ struct IntegrationSafetyNetTests { // Export the archive let stagingDir = fixture.baseDirectory.appending(path: "url-backup-stage")- let exporter = BackupV15Exporter(repository: repo, stagingDirectory: stagingDir)+ let exporter = BackupV16Exporter(repository: repo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "url-backup-test", exportedAt: Date())+ metadata: BackupV16Metadata(appBuild: "url-backup-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } let backupData = try Data(contentsOf: exportResult.fileURL)- let decoded = try BackupV15Codec.decode(backupData)+ let decoded = try BackupV16Codec.decode(backupData) // Site should be present in the payload. let site = decoded.payload.sites.first { $0.hostname == "backupurl.test" }
diff --git a/Asterism/AsterismTests/SetLatestModelTests.swift b/Asterism/AsterismTests/SetLatestModelTests.swiftnew file mode 100644index 00000000..1316d266--- /dev/null+++ b/Asterism/AsterismTests/SetLatestModelTests.swift@@ -0,0 +1,147 @@+import AsterismCore+import Foundation+import Testing++@testable import Asterism++@Suite("Set latest model")+struct SetLatestModelTests {+ private func calendar() -> Calendar {+ var value = Calendar(identifier: .gregorian)+ value.timeZone = TimeZone(identifier: "UTC")!+ return value+ }++ private func day() -> CivilDay {+ CivilDay(Date(timeIntervalSince1970: 1_800_000_000), calendar: calendar())+ }++ private func state(+ latest: Int?, read: Int?, estimate: Bool = false,+ days: [ReleaseDay] = [], override: LastChapterOverride? = nil+ ) -> CatchUpSheetState {+ let cal = calendar()+ let work = TestFixtures.makeWork(releaseDays: days)+ let record = CatchUpRecord(+ confirmation: latest.map {+ CatchUpConfirmation(+ latest: $0,+ confirmedAtMilliseconds: MillisecondInstant.milliseconds(day().date(in: cal)),+ countsUp: !days.isEmpty, isEstimate: estimate)+ },+ override: override)+ let notes = read.map {+ [NumberedNote(number: $0, firstCapturedAt: day().date(in: cal), title: "Chapter \($0)")]+ } ?? []+ return CatchUpSheetState(+ work: work, record: record,+ progress: CatchUpProgress.build(+ record: record, notes: notes, releaseDays: days,+ workStatus: .ongoing, day: day(), calendar: cal))+ }++ @MainActor private func model(+ _ state: CatchUpSheetState,+ result: Result<LibraryWriteOutcome, Error> = .success(.committed)+ ) -> (SetLatestModel, MockLibraryProvider, SavedFlag) {+ let library = MockLibraryProvider()+ library.catchUpSheetStateResult = .success(state)+ library.commitCatchUpProgressResult = result+ let saved = SavedFlag()+ let model = SetLatestModel(+ workID: state.work.id, library: library, day: day(), calendar: calendar(),+ commit: { id, basis, draft in+ try await library.commitCatchUpProgress(id: id, basis: basis, draft: draft)+ },+ onSaved: { saved.value = true })+ return (model, library, saved)+ }++ @Test("Latest prefills from estimate, then last read, then empty")+ @MainActor func prefill() async {+ let (estimated, _, _) = model(state(latest: 42, read: 40, estimate: true))+ await estimated.load()+ #expect(estimated.latestText == "42")+ #expect(estimated.latestIsEstimated)++ let (read, _, _) = model(state(latest: nil, read: 40))+ await read.load()+ #expect(read.latestText == "40")+ #expect(!read.latestIsEstimated)++ let (empty, _, _) = model(state(latest: nil, read: nil))+ await empty.load()+ #expect(empty.latestText.isEmpty)+ }++ @Test("Editing removes the estimated mark and the behind caption follows the field")+ @MainActor func fieldCaption() async {+ let (model, _, _) = model(state(latest: 42, read: 40, estimate: true))+ await model.load()+ #expect(model.behindCaption == "2 chapters behind")+ model.setLatestText("40")+ #expect(!model.latestIsEstimated)+ #expect(model.behindCaption == "Caught up")+ model.setLatestText("39")+ #expect(model.behindCaption == "Below your last chapter (40); progress will show 40")+ model.setLatestText("42")+ #expect(!model.latestIsEstimated)+ model.setLatestText("10000")+ #expect(!model.canSave)+ #expect(model.behindCaption == nil)+ model.setLatestText("0")+ #expect(model.canSave)+ }++ @Test("Count-up is offered only with days, and the source names its note")+ @MainActor func settingsAndSource() async {+ let (scheduled, _, _) = model(state(latest: 42, read: 40, days: [.monday]))+ await scheduled.load()+ #expect(scheduled.showsCountUp)+ #expect(scheduled.lastReadSourceText == "Chapter 40")+ let (unscheduled, _, _) = model(state(latest: 42, read: 40))+ await unscheduled.load()+ #expect(!unscheduled.showsCountUp)+ }++ @Test("Override edits map to value, clear, or unchanged")+ @MainActor func overrideDraft() async {+ let state = state(latest: 42, read: 40, override: .value(39, atMilliseconds: 1))+ let (model, library, _) = model(state)+ await model.load()+ #expect(model.overrideText == "39")+ #expect(model.lastReadSourceText == "Chapter 40")+ await model.save()+ #expect(library.lastCatchUpDraft?.override == .unchanged)++ let (cleared, clearLibrary, _) = self.model(state)+ await cleared.load()+ cleared.setOverrideText("")+ await cleared.save()+ #expect(clearLibrary.lastCatchUpDraft?.override == .clear)++ let (set, setLibrary, _) = self.model(state)+ await set.load()+ set.setOverrideText("41")+ await set.save()+ #expect(setLibrary.lastCatchUpDraft?.override == .set(41))+ #expect(setLibrary.lastCatchUpDraft?.latest == 42)+ }++ @Test("A refused Save keeps the reader's values and does not dismiss")+ @MainActor func conflictKeepsDraft() async {+ let state = state(latest: 42, read: 40)+ let (model, _, saved) = model(+ state, result: .success(.conflict(.recordChanged(recordID: state.work.id))))+ await model.load()+ model.setLatestText("55")+ model.setOverrideText("44")+ await model.save()+ #expect(model.latestText == "55")+ #expect(model.overrideText == "44")+ #expect(model.errorMessage == "Changed on another device. Close and reopen to see it.")+ #expect(!saved.value)+ }+}++@MainActor private final class SavedFlag { var value = false }
diff --git a/Asterism/AsterismTests/SettingsBackupModelTests.swift b/Asterism/AsterismTests/SettingsBackupModelTests.swiftindex 60e88409..09f62724 100644--- a/Asterism/AsterismTests/SettingsBackupModelTests.swift+++ b/Asterism/AsterismTests/SettingsBackupModelTests.swift@@ -319,7 +319,7 @@ struct SettingsBackupModelTests { @MainActor func tornGroupsMessageStatesTheCount() async { let mock = MockBackupExporting() mock.exportResult = .failure(- BackupV15ExportError.tornGroups(+ BackupV16ExportError.tornGroups( TornGroupsPayload(count: 3, blockingWorkSet: nil))) let model = SettingsBackupModel(exporter: mock)@@ -340,7 +340,7 @@ struct SettingsBackupModelTests { @MainActor func tornGroupsMessageReadsSingular() async { let mock = MockBackupExporting() mock.exportResult = .failure(- BackupV15ExportError.tornGroups(+ BackupV16ExportError.tornGroups( TornGroupsPayload(count: 1, blockingWorkSet: nil))) let model = SettingsBackupModel(exporter: mock)@@ -358,7 +358,7 @@ struct SettingsBackupModelTests { @MainActor func tornGroupsMessagePointsAtTheBlockingWorkSet() async { let mock = MockBackupExporting() mock.exportResult = .failure(- BackupV15ExportError.tornGroups(+ BackupV16ExportError.tornGroups( TornGroupsPayload( count: 1, blockingWorkSet: DuplicateSetKey(@@ -394,7 +394,7 @@ struct SettingsBackupModelTests { let mock = MockBackupExporting() mock.exportResult = .failure(- BackupV15ExportError.tornGroups(+ BackupV16ExportError.tornGroups( TornGroupsPayload(count: 1, blockingWorkSet: nil))) let model = SettingsBackupModel(exporter: mock) await model.startExport()@@ -429,7 +429,7 @@ struct SettingsBackupModelTests { let model = SettingsBackupModel(exporter: mock) await model.startExport() - let metadata: BackupV15Metadata? = mock.lastMetadata+ let metadata: BackupV16Metadata? = mock.lastMetadata #expect(metadata != nil) #expect(metadata?.appBuild.isEmpty == false) }@@ -444,7 +444,7 @@ struct SettingsBackupModelTests { @MainActor func nineTenTornRefusalRoutes() async { let mock = MockBackupExporting() mock.exportResult = .failure(- BackupV15ExportError.tornGroups(+ BackupV16ExportError.tornGroups( TornGroupsPayload(count: 2, blockingWorkSet: nil))) let model = SettingsBackupModel(exporter: mock)@@ -461,14 +461,14 @@ struct SettingsBackupModelTests { /// through to the default arm would be indistinguishable from an error the /// app has never heard of. @Test("Every 15/16 export refusal has its own message", arguments: [- BackupV15ExportError.referencesStillArriving(detail: "rule 1"),- BackupV15ExportError.unrepresentableValue(+ BackupV16ExportError.referencesStillArriving(detail: "rule 1"),+ BackupV16ExportError.unrepresentableValue( record: "Character", field: "factsData", value: "…"),- BackupV15ExportError.snapshotFailed(reason: "read"),- BackupV15ExportError.encodingFailed(reason: "encode"),- BackupV15ExportError.stagingFailed(reason: "stage"),+ BackupV16ExportError.snapshotFailed(reason: "read"),+ BackupV16ExportError.encodingFailed(reason: "encode"),+ BackupV16ExportError.stagingFailed(reason: "stage"), ])- @MainActor func everyNineTenRefusalHasAMessage(error: BackupV15ExportError) async {+ @MainActor func everyNineTenRefusalHasAMessage(error: BackupV16ExportError) async { let mock = MockBackupExporting() mock.exportResult = .failure(error) @@ -495,9 +495,9 @@ struct SettingsBackupModelTests { @MainActor func coverRefusalNamesTheWork() async { let mock = MockBackupExporting() mock.exportResult = .failure(- BackupV15ExportError.unrepresentableValue(+ BackupV16ExportError.unrepresentableValue( record: "Work “Actual Title”",- field: BackupV15ExportError.thumbnailField,+ field: BackupV16ExportError.thumbnailField, value: "17 bytes that are not a portrait cover")) let model = SettingsBackupModel(exporter: mock)@@ -536,12 +536,12 @@ final class MockBackupExporting: BackupExporting, @unchecked Sendable { var cleanupCallCount = 0 var scavengeCallCount = 0 var lastCleanupURL: URL?- var lastMetadata: BackupV15Metadata?+ var lastMetadata: BackupV16Metadata? var exportResult: Result<BackupExportResult, Error> = .failure(MockBackupError.notConfigured) var exportDelay: Duration? - func export(metadata: BackupV15Metadata) async throws -> BackupExportResult {+ func export(metadata: BackupV16Metadata) async throws -> BackupExportResult { exportCallCount += 1 lastMetadata = metadata if let delay = exportDelay {
diff --git a/Asterism/AsterismTests/SettingsImportTests.swift b/Asterism/AsterismTests/SettingsImportTests.swiftindex cc965a1d..35135b60 100644--- a/Asterism/AsterismTests/SettingsImportTests.swift+++ b/Asterism/AsterismTests/SettingsImportTests.swift@@ -67,9 +67,9 @@ struct SettingsBackupImportModelTests { static let minimalBackupData: Data = { let hostname = "settings-import.example" let rawURL = "https://\(hostname)/read?chapter=1"- let payload = BackupV15Payload(+ let payload = BackupV16Payload( entries: [- BackupV15Entry(+ BackupV16Entry( id: UUID(), captureTitle: "Chapter 1", captureTitleSource: .host, rawURL: rawURL, canonicalURL: nil, hostname: hostname, entryIdentityKey: rawURL,@@ -84,13 +84,13 @@ struct SettingsBackupImportModelTests { ], works: [], sites: [- BackupV15Site(+ BackupV16Site( hostname: hostname, displayName: hostname, mode: .untaught) ], titlePatterns: [], urlRules: [], workTypes: [])- return try! BackupV15Codec.encode(+ return try! BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(+ metadata: BackupV16Metadata( appBuild: "test", exportedAt: Date(timeIntervalSince1970: 1_800_000_000))) }()
diff --git a/Asterism/AsterismTests/TodayFixtureSeedingTests.swift b/Asterism/AsterismTests/TodayFixtureSeedingTests.swiftindex 2db9177f..bdbc8a97 100644--- a/Asterism/AsterismTests/TodayFixtureSeedingTests.swift+++ b/Asterism/AsterismTests/TodayFixtureSeedingTests.swift@@ -18,26 +18,28 @@ import Testing /// about the Today screen: the screen's derivation is /// `TodayDayPlanTests`' subject in Core, and the one assertion here that touches /// it (`TodaySchedule.build`) is there because the fixture's whole point is that-/// two of its four works are scheduled, one is kept off by its status and one-/// by being caught up on.+/// two works are scheduled; the catch-up examples are a separate bucket. @Suite("The today UI fixture, seeded") struct TodayFixtureSeedingTests { - /// The four works, their statuses and their days — everything the seeder's+ /// The works, their statuses and their days — everything the seeder's /// table states, read back off the publication a launch would have.- @Test("Seeding `today` publishes four works whose days follow the launch clock")+ @Test("Seeding `today` publishes seven works and keeps the four Recent entries") @MainActor func seedsTheDocumentedShape() async throws { let library = try await SeededTodayLibrary() defer { library.removeRoot() } let calendar = library.calendar let works = library.model.worksSnapshot.works- #expect(works.count == 4)+ #expect(works.count == 7) let kite = try #require(works.first { $0.displayTitle == "Kite Season" }) let salt = try #require(works.first { $0.displayTitle == "Salt Harvest" }) let lantern = try #require(works.first { $0.displayTitle == "Paper Lantern" }) let ember = try #require(works.first { $0.displayTitle == "Ember Road" })+ let frost = try #require(works.first { $0.displayTitle == "Frost Relay" })+ let copper = try #require(works.first { $0.displayTitle == "Copper Atlas" })+ let harbor = try #require(works.first { $0.displayTitle == "Harbor Signal" }) // Req 6.1's exclusion needs one work that days alone would schedule and // a status keeps off the day.@@ -51,6 +53,8 @@ struct TodayFixtureSeedingTests { #expect(ember.workStatus == .finished) #expect(ember.readingStatus == .catchingUp) #expect(ember.releaseDays.isEmpty)+ #expect([frost, copper, harbor].allSatisfy { $0.readingStatus == .catchingUp })+ #expect([frost, copper, harbor].allSatisfy { $0.entries.isEmpty }) // The two civil days the fixture spans, taken off the rows rather than // off a second reading of the clock, so a run that straddles midnight@@ -89,7 +93,21 @@ struct TodayFixtureSeedingTests { #expect(schedule.works.map(\.title) == ["Kite Season", "Salt Harvest"]) #expect(schedule.dueWeekdays == Set([currentWeekday, previousWeekday])) // Q8: the catch-up work is its own list and adds no dot.- #expect(schedule.catchingUp.map(\.title) == ["Ember Road"])+ #expect(schedule.catchingUp.map(\.title)+ == ["Copper Atlas", "Ember Road", "Frost Relay", "Harbor Signal"])+ let byTitle = Dictionary(uniqueKeysWithValues: works.map { ($0.displayTitle, $0) })+ #expect(CatchUpProgress.build(work: frost, day: currentDay, calendar: calendar).state == .exact)+ #expect(CatchUpProgress.build(work: copper, day: currentDay, calendar: calendar).state == .estimated)+ #expect(CatchUpProgress.build(work: harbor, day: currentDay, calendar: calendar).state == .caughtUp)+ #expect(CatchUpProgress.build(work: ember, day: currentDay, calendar: calendar).state == .unknown)+ #expect(frost.releaseDays.isEmpty)+ #expect(!copper.releaseDays.isEmpty)+ for title in ["Frost Relay", "Copper Atlas", "Harbor Signal"] {+ let confirmation = try #require(byTitle[title]?.catchUp.confirmation)+ #expect(CivilDay(+ MillisecondInstant.date(fromMilliseconds: confirmation.confirmedAtMilliseconds),+ calendar: calendar) < currentDay)+ } } /// Req 5.2's two furnished forms — `Noted today · {chapter line}` and@@ -120,7 +138,7 @@ struct TodayFixtureSeedingTests { // Teaching reparses every entry on the hostname, so this is also the // check that it re-attributed nothing: each entry is still under the // work the seeder moved it to.- for work in library.model.worksSnapshot.works {+ for work in library.model.worksSnapshot.works where !work.entries.isEmpty { #expect(work.entries.count == 1) let captured = try #require(work.entries.first?.captureTitle) #expect(captured.hasSuffix(" - \(work.displayTitle)"))
diff --git a/Asterism/AsterismTests/TodayShelfTextTests.swift b/Asterism/AsterismTests/TodayShelfTextTests.swiftindex deef4bda..d6fb0e5c 100644--- a/Asterism/AsterismTests/TodayShelfTextTests.swift+++ b/Asterism/AsterismTests/TodayShelfTextTests.swift@@ -30,16 +30,44 @@ struct TodayShelfTextTests { private func row( _ title: String, line: ReleaseRow.Line = .notNotedYet, type: WorkTypeDisplay = .untyped, lastChapter: Int? = nil,- lastNotedDay: CivilDay? = nil, releasesSince: Int? = nil, primaryURL: URL? = nil+ lastNotedDay: CivilDay? = nil, releasesSince: Int? = nil, primaryURL: URL? = nil,+ progress: CatchUpProgress? = nil, workStatus: WorkStatus = .ongoing ) -> ReleaseRow { ReleaseRow( id: UUID(), title: title, primaryHostname: "example.com", typeDisplay: type,- thumbnail: nil, line: line, lastChapter: lastChapter, lastNotedDay: lastNotedDay,+ thumbnail: nil, line: line,+ progress: progress ?? CatchUpProgress.build(+ record: .pristine, notes: [], releaseDays: [], workStatus: .ongoing,+ day: today, calendar: Self.calendar()), workStatus: workStatus,+ lastChapter: lastChapter, lastNotedDay: lastNotedDay, releasesSince: releasesSince, primaryURL: primaryURL) } private var today: CivilDay { Self.civilDay(2026, 9, 23) } + private func progress(+ latest: Int?, read: Int?, confirmedDay: CivilDay? = nil,+ readDay: CivilDay? = nil, estimated: Bool = false,+ type: WorkStatus = .ongoing, days: [ReleaseDay] = []+ ) -> CatchUpProgress {+ let calendar = Self.calendar()+ let confirmation = confirmedDay.map {+ CatchUpConfirmation(+ latest: latest,+ confirmedAtMilliseconds: MillisecondInstant.milliseconds($0.date(in: calendar)),+ countsUp: !days.isEmpty, isEstimate: estimated)+ }+ let notes = read.map {+ [NumberedNote(+ number: $0, firstCapturedAt: (readDay ?? today).date(in: calendar),+ title: "Chapter \($0)")]+ } ?? []+ return CatchUpProgress.build(+ record: CatchUpRecord(confirmation: confirmation, override: nil),+ notes: notes, releaseDays: days, workStatus: type,+ day: today, calendar: calendar)+ }+ // MARK: - Shelf @Test("The shelf puts unread works first and keeps title order within each half")@@ -92,6 +120,78 @@ struct TodayShelfTextTests { == ["Never", "Old", "Recent", "Also recent"]) } + @Test("Exact and estimated rows lead by distance, then caught-up and unknown by read day")+ func progressOrdering() {+ let old = Self.civilDay(2026, 9, 1)+ let recent = Self.civilDay(2026, 9, 20)+ let unknownRecent = row("Unknown recent", progress: progress(latest: nil, read: 9, readDay: recent))+ let exactTwo = row("Exact two", progress: progress(latest: 12, read: 10, confirmedDay: today))+ let caught = row("Caught", progress: progress(latest: 10, read: 10, confirmedDay: today))+ let estimateFive = row("Estimated five", progress: progress(latest: 15, read: 10, confirmedDay: today, estimated: true))+ let unknownOld = row("Unknown old", progress: progress(latest: nil, read: 9, readDay: old))+ let exactFive = row("Exact five", progress: progress(latest: 15, read: 10, confirmedDay: today))+ #expect(CatchUpText.ordered([+ unknownRecent, exactTwo, caught, exactFive, unknownOld, estimateFive,+ ]).map(\.title) == [+ "Exact five", "Estimated five", "Exact two", "Caught", "Unknown old", "Unknown recent",+ ])+ }++ @Test("Progress text gives exact, estimated and caught-up rows distinct labels")+ func progressTextAndLabels() {+ let calendar = Self.calendar()+ let exact = row(+ "Exact", lastChapter: 9,+ progress: progress(latest: 10, read: 9, confirmedDay: today))+ #expect(CatchUpText.progressLine(exact) == "9/10")+ #expect(CatchUpText.status(exact, selectedDay: today, currentDay: today, calendar: calendar) == "1 chapter behind")+ #expect(CatchUpText.accessibilityLabel(exact, selectedDay: today, currentDay: today, calendar: calendar) == "Exact, 1 chapter behind, chapter 9 of 10")++ let estimated = row(+ "Estimated", type: Self.webtoon, lastChapter: 8,+ progress: progress(latest: 10, read: 8, confirmedDay: today, estimated: true))+ #expect(CatchUpText.progressLine(estimated) == "8/~10")+ #expect(CatchUpText.status(estimated, selectedDay: today, currentDay: today, calendar: calendar) == "~2 episodes behind · estimated")+ #expect(CatchUpText.accessibilityLabel(estimated, selectedDay: today, currentDay: today, calendar: calendar) == "Estimated, 2 episodes behind, episode 8 of 10, estimated")++ let caught = row("Caught", progress: progress(latest: 10, read: 10, confirmedDay: today))+ #expect(CatchUpText.status(caught, selectedDay: today, currentDay: today, calendar: calendar) == "Caught up")+ #expect(CatchUpText.accessibilityLabel(caught, selectedDay: today, currentDay: today, calendar: calendar) == "Caught, caught up")+ }++ @Test("An exact number gets an as-of suffix only after seven days")+ func exactAsOfThreshold() {+ let calendar = Self.calendar()+ let seven = today.adding(days: -7, calendar: calendar)+ let eight = today.adding(days: -8, calendar: calendar)+ let recent = row("Recent", progress: progress(latest: 10, read: 9, confirmedDay: seven))+ let old = row("Old", progress: progress(latest: 10, read: 9, confirmedDay: eight))+ #expect(CatchUpText.status(recent, selectedDay: today, currentDay: today, calendar: calendar) == "1 chapter behind")+ #expect(CatchUpText.status(old, selectedDay: today, currentDay: today, calendar: calendar) == "1 chapter behind · as of last week")+ }++ @Test("Unknown override-only progress names the chapter and today")+ func unknownOverrideOnly() {+ let calendar = Self.calendar()+ let record = CatchUpRecord(+ confirmation: nil,+ override: .value(42, atMilliseconds: MillisecondInstant.milliseconds(today.date(in: calendar))))+ let unknown = row(+ "Override", progress: CatchUpProgress.build(+ record: record, notes: [], releaseDays: [], workStatus: .ongoing,+ day: today, calendar: calendar))+ #expect(CatchUpText.status(unknown, selectedDay: today, currentDay: today, calendar: calendar) == "Last read Ch 42 · today")+ #expect(CatchUpText.accessibilityLabel(unknown, selectedDay: today, currentDay: today, calendar: calendar) == "Override, Last read chapter 42 · today")+ }++ @Test("Banner text and primary action follow work status")+ func bannerText() {+ #expect(CatchUpText.bannerTitle("Harbor Signal") == "Caught up on Harbor Signal.")+ #expect(CatchUpText.primaryButtonLabel(.ongoing) == "Move to Reading")+ #expect(CatchUpText.primaryButtonLabel(.hiatus) == "Move to Reading")+ #expect(CatchUpText.primaryButtonLabel(.finished) == "Mark Finished")+ }+ @Test("A catch-up row says what was read last, when, and how many releases since") func catchUpStatusLine() { let calendar = Self.calendar()
diff --git a/Asterism/AsterismTests/WorkDetailModelTests.swift b/Asterism/AsterismTests/WorkDetailModelTests.swiftindex adfa11e9..ceedebea 100644--- a/Asterism/AsterismTests/WorkDetailModelTests.swift+++ b/Asterism/AsterismTests/WorkDetailModelTests.swift@@ -76,6 +76,21 @@ struct WorkDetailModelTests { #expect(tracker.mutationCount == 1) } + @Test("Save passes the calendar the app supplied")+ @MainActor func saveUsesInjectedCalendar() async {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(identifier: "Australia/Sydney")!+ let work = TestFixtures.makeWork()+ let mock = MockLibraryProvider()+ mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: work))+ let model = makeWorkDetailModel(+ workID: work.id, library: mock, calendar: calendar)+ await model.load()+ model.draftNotes = "read another chapter"+ await model.save()+ #expect(mock.lastUpdateWorkCalendar?.timeZone == calendar.timeZone)+ }+ /// The `.conflict` path already kept the drafts, on the grounds that a draft /// is the only copy of itself until it lands and the editor is still open on /// it. A throw is the same situation — nothing was written — so it now keeps@@ -567,6 +582,8 @@ struct WorkDetailModelTests { @MainActor @Test("The screen opens in view mode and enters the editor on request") func theScreenOpensInViewMode() async { let (model, _, _) = makeSUT()+ model.beginEditing()+ #expect(!model.isEditing, "The editor needs a ready snapshot") await model.load() #expect(!model.isEditing)
diff --git a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swiftindex a80be832..5c49f0ae 100644--- a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift+++ b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift@@ -51,9 +51,7 @@ final class AccessibilityJourneyUITests: XCTestCase { "Move-to sheet should dismiss after assignment" ) - let worksTab = app.tabControl(.works)- XCTAssertTrue(worksTab.waitForExistence(timeout: 10))- worksTab.tap()+ openAllWorks(in: app) let workTitle = app.buttons["Open Work Integration Work from integration.test"] XCTAssertTrue(workTitle.waitForExistence(timeout: 10)) workTitle.tap()@@ -313,8 +311,8 @@ final class AccessibilityJourneyUITests: XCTestCase { let abandoned = app.buttons.matching( NSPredicate(format: "label BEGINSWITH %@", "Open Work Marrow Lane")).firstMatch- XCTAssertTrue(abandoned.waitForExistence(timeout: 15), "The abandoned work is listed") scrollToElement(abandoned, attempts: 8)+ XCTAssertTrue(abandoned.waitForExistence(timeout: 15), "The abandoned work is listed") assertContentControl(abandoned, named: "The abandoned row at largest Dynamic Type") abandoned.tap() @@ -472,8 +470,8 @@ final class AccessibilityJourneyUITests: XCTestCase { let rising = app.buttons.matching( NSPredicate(format: "label BEGINSWITH %@", "Open Work Ashfall Rising")).firstMatch- XCTAssertTrue(rising.waitForExistence(timeout: 15), "The work in a series is listed") scrollToElement(rising, attempts: 8)+ XCTAssertTrue(rising.waitForExistence(timeout: 15), "The work in a series is listed") assertContentControl(rising, named: "A row in a series at largest Dynamic Type") // A row 152 pt tall reports itself hittable while its **centre** is // under the tab bar, and XCUI taps an element at its centre — measured@@ -590,7 +588,10 @@ final class AccessibilityJourneyUITests: XCTestCase { // The creators list, and the field that makes one. app.goBack()- scrollUntilTappableAndTap(app.buttons["library-destination-creators"], in: app, "Creators is reachable")+ waitFor(app.anyElement("library-hub"), "Back returns to the library hub")+ let creators = app.buttons["library-destination-creators"]+ for _ in 0..<8 where !creators.isHittable { app.swipeDown() }+ waitFor(creators, "Creators is reachable").tap() XCTAssertTrue( app.anyElement("creator-list").waitForExistence(timeout: 15), "The creators list opens")@@ -614,10 +615,16 @@ final class AccessibilityJourneyUITests: XCTestCase { app.anyElement("creator-list").waitForExistence(timeout: 15), "Back returns to the creators list") app.goBack()+ waitFor(app.anyElement("library-hub"), "Back returns to the library hub again")+ let allWorks = app.buttons["library-destination-allWorks"]+ for _ in 0..<8 where !allWorks.isHittable {+ app.scrollViews["library-hub"].swipeDown()+ }+ openAllWorks(in: app) let song = app.buttons.matching( NSPredicate(format: "label BEGINSWITH %@", "Open Work Lantern Song")).firstMatch- XCTAssertTrue(song.waitForExistence(timeout: 15), "The credited work is listed") scrollToElement(song, attempts: 8)+ XCTAssertTrue(song.waitForExistence(timeout: 15), "The credited work is listed") // A row 152 pt tall reports itself hittable while its **centre** is // under the tab bar, and XCUI taps an element at its centre, so the row // is nudged clear of the bar before it is tapped.@@ -955,7 +962,7 @@ final class AccessibilityJourneyUITests: XCTestCase { private func walkWorksAppearanceJourney(named appearance: String) { let works = app.tabControl(.works) XCTAssertTrue(works.waitForExistence(timeout: 30), "Works tab missing in \(appearance)")- works.tap()+ openAllWorks(in: app) XCTAssertTrue( app.anyElement("works-group-allWorks").waitForExistence(timeout: 10),@@ -1043,7 +1050,7 @@ final class AccessibilityJourneyUITests: XCTestCase { "The library opens") let works = app.tabControl(.works) XCTAssertTrue(works.waitForExistence(timeout: 30), "The Works tab is reachable")- works.tap()+ openAllWorks(in: app) let workRow = app.elements(withIdentifierPrefix: "work-row-").firstMatch XCTAssertTrue(workRow.waitForExistence(timeout: 20), "The seeded work is listed") scrollToElement(workRow, attempts: 8)@@ -1294,8 +1301,8 @@ final class AccessibilityJourneyUITests: XCTestCase { let marrowLane = app.buttons.matching( NSPredicate(format: "label BEGINSWITH %@", "Open Work Marrow Lane")).firstMatch- XCTAssertTrue(marrowLane.waitForExistence(timeout: 15), "The scheduled work is listed") scrollToElement(marrowLane, attempts: 8)+ XCTAssertTrue(marrowLane.waitForExistence(timeout: 15), "The scheduled work is listed") marrowLane.tap() let edit = app.buttons["work-detail-edit-button"]@@ -1358,7 +1365,7 @@ final class AccessibilityJourneyUITests: XCTestCase { ) let works = app.tabControl(.works) XCTAssertTrue(works.waitForExistence(timeout: 60), "The Works tab is reachable")- works.tap()+ openAllWorks(in: app) scrollUntilTappableAndTap( app.buttons["work-to-read-match-pill"], in: app,@@ -1633,7 +1640,8 @@ final class WideLayoutAccessibilityUITests: XCTestCase { let target = app.buttons["work-detail-reading-status-\(chosen)"] scrollUntilTappableAndTap( target, in: app, "\(chosen) is operable in \(layout)",- scroll: { $0.swipeDown() }, file: file, line: line)+ scroll: { $0.anyElement("wide-detail-column").swipeDown() },+ file: file, line: line) let selected = XCTNSPredicateExpectation( predicate: NSPredicate { _, _ in self.app.buttons["work-detail-reading-status-\(chosen)"].isSelected@@ -1648,9 +1656,8 @@ final class WideLayoutAccessibilityUITests: XCTestCase { /// /// Reachable at a width means reachable by scrolling, so existence is not /// the question: a segment half in the column exists while the reader still- /// cannot tap it. `app.swipeUp()` in the middle of the window is the detail- /// column's own gesture here, which is the fact `revealInTheList` below- /// records from the other side.+ /// cannot tap it. Scope the gesture to detail; the window's middle can+ /// land on the Works list after the columns resize. private func revealInEditor( _ element: XCUIElement, _ message: String, file: StaticString = #filePath, line: UInt = #line@@ -1658,7 +1665,7 @@ final class WideLayoutAccessibilityUITests: XCTestCase { _ = element.waitForExistence(timeout: 15) for _ in 0..<8 { if element.exists, element.isHittable { return }- app.swipeUp()+ app.anyElement("wide-detail-column").swipeUp() _ = element.waitForExistence(timeout: 2) } XCTFail(message, file: file, line: line)
diff --git a/Asterism/AsterismUITests/DuplicateResolutionUITests.swift b/Asterism/AsterismUITests/DuplicateResolutionUITests.swiftindex f839150a..9f7d03d2 100644--- a/Asterism/AsterismUITests/DuplicateResolutionUITests.swift+++ b/Asterism/AsterismUITests/DuplicateResolutionUITests.swift@@ -167,7 +167,7 @@ final class DuplicateResolutionUITests: XCTestCase { app.buttons["duplicate-elsewhere-row"], "The filter names what Recent holds no row for") XCTAssertTrue(- elsewhere.label.localizedCaseInsensitiveContains("works tab"),+ elsewhere.label.localizedCaseInsensitiveContains("library tab"), "The line says where the work is resolved: \(elsewhere.label)") // And it is a route, not a label.@@ -274,7 +274,7 @@ final class DuplicateResolutionUITests: XCTestCase { launch("divergentWorkSet") require(app.collectionViews["recent-list"], "The library opens", timeout: 60) - selectTab(.works, in: app)+ openAllWorks(in: app) let pills = app.buttons.matching(identifier: "work-resolve-duplicate-pill") let pill = require( pills.firstMatch,@@ -344,7 +344,7 @@ final class DuplicateResolutionUITests: XCTestCase { // Req 4.2: the to-read work survived under its own UUID and the // captured one is gone — not the other way round, which would show the // same title on the survivor's page.- selectTab(.works, in: app)+ openAllWorks(in: app) require( app.buttons["work-row-\(ToReadMatchScenario.toReadID)"], "The to-read work is the survivor")@@ -354,13 +354,13 @@ final class DuplicateResolutionUITests: XCTestCase { } /// Q30, Q47: confirmed from the Works pill, the survivor opens on the- /// Works stack, as its only route: one Back returns to the list, where the- /// to-read work stands and the captured one is gone.+ /// Works stack, as its only route: one Back returns to the Library hub;+ /// All works then shows the surviving work and no captured work. func testConfirmingFromTheWorksPillShowsTheSurvivorOnTheWorksStack() { launch(ToReadMatchScenario.shape) require(app.collectionViews["recent-list"], "The library opens", timeout: 60) - selectTab(.works, in: app)+ openAllWorks(in: app) require( app.buttons["work-to-read-match-pill"], "The captured work's row carries the pill" ).tap()@@ -376,9 +376,11 @@ final class DuplicateResolutionUITests: XCTestCase { "The survivor carries the captured title") app.goBack()+ require(any("library-hub"), "Back from the survivor reaches the Library hub")+ openAllWorks(in: app) require( app.buttons["work-row-\(ToReadMatchScenario.toReadID)"],- "Back from the survivor is the Works list, with the to-read work in it")+ "All works contains the to-read survivor") waitForDisappearance( app.buttons["work-row-\(ToReadMatchScenario.capturedID)"], "The captured work was merged away")@@ -393,7 +395,7 @@ final class DuplicateResolutionUITests: XCTestCase { launch(ToReadMatchScenario.shape) require(app.collectionViews["recent-list"], "The library opens", timeout: 60) - selectTab(.works, in: app)+ openAllWorks(in: app) require( app.buttons["work-to-read-match-pill"], "The captured work's row carries the pill" ).tap()@@ -424,7 +426,7 @@ final class DuplicateResolutionUITests: XCTestCase { launch(ToReadMatchScenario.shape) require(app.collectionViews["recent-list"], "The library opens", timeout: 60) - selectTab(.works, in: app)+ openAllWorks(in: app) let pill = require( app.buttons["work-to-read-match-pill"], "The captured work's row carries the pill") XCTAssertEqual(
diff --git a/Asterism/AsterismUITests/EntryToWorkLinkUITests.swift b/Asterism/AsterismUITests/EntryToWorkLinkUITests.swiftindex 30823046..c010f122 100644--- a/Asterism/AsterismUITests/EntryToWorkLinkUITests.swift+++ b/Asterism/AsterismUITests/EntryToWorkLinkUITests.swift@@ -146,7 +146,7 @@ final class EntryToWorkLinkUITests: XCTestCase { func testTheMergeSheetsChapterNamesItsWorkWithoutOfferingTheRoute() { launch("seeded-tolerated-divergentWorkSet") - selectTab(.works, in: app)+ openAllWorks(in: app) waitFor( app.buttons.matching(identifier: "work-resolve-duplicate-pill").firstMatch, "A divergent Work set offers the way into the Merge"
diff --git a/Asterism/AsterismUITests/TodayUITests.swift b/Asterism/AsterismUITests/TodayUITests.swiftindex a4145e0b..b2954ffb 100644--- a/Asterism/AsterismUITests/TodayUITests.swift+++ b/Asterism/AsterismUITests/TodayUITests.swift@@ -96,6 +96,43 @@ final class TodayUITests: XCTestCase { app.elements(withIdentifierPrefix: "today-catchup-row-") } + private var catchUpBanners: XCUIElementQuery {+ app.descendants(matching: .any).matching(+ NSPredicate(format: "identifier BEGINSWITH %@", "today-catchup-banner-"))+ }++ private func catchUpRow(_ title: String) -> XCUIElement {+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-catchup-row-", "\(title),")).firstMatch+ }++ private func adjustLatest(to target: Int) {+ let field = waitFor(app.textFields["today-set-latest-number"], "The latest field loads")+ guard let current = Int((field.value as? String) ?? "") else {+ XCTFail("The seeded latest field has a whole number")+ return+ }+ let button = target >= current ? "today-set-latest-increase" : "today-set-latest-decrease"+ for _ in 0..<abs(target - current) { app.buttons[button].tap() }+ XCTAssertEqual(field.value as? String, String(target))+ }++ private func openSetLatest(for title: String) {+ scrollUntilPresent(catchUpRow(title), in: app, "\(title) is in the catch-up card")+ let row = waitFor(catchUpRow(title), "\(title) is in the catch-up card")+ row.press(forDuration: 1)+ waitFor(app.buttons["Set latest…"], "The current-day menu offers Set latest").tap()+ waitFor(app.anyElement("today-set-latest-sheet"), "The latest sheet opens")+ }++ private func saveLatest(_ number: Int, for title: String) {+ openSetLatest(for: title)+ adjustLatest(to: number)+ waitFor(app.buttons["today-set-latest-save"], "The number can be saved").tap()+ XCTAssertFalse(app.anyElement("today-set-latest-sheet").waitForExistence(timeout: 2))+ }+ // MARK: - Days, and reaching them /// `yyyy-MM-dd`, which is what `CivilDay.description` spells and therefore@@ -567,13 +604,6 @@ final class TodayUITests: XCTestCase { assertHeader( "today-section-releases", says: "Releasing", "Req 5.1/Q76: the releases header names the section, never the day")- assertHeader(- "today-section-noted", says: "Noted",- "Req 5.4/Q76: and so does the notes header")- XCTAssertLessThan(- app.anyElement("today-section-releases").frame.minY,- app.anyElement("today-section-noted").frame.minY,- "Req 5.5: the current day reads as a plan — releases first") XCTAssertEqual(releaseRows.count, 1, "Only Kite Season is due on the current weekday") let release = releaseRows.firstMatch@@ -589,18 +619,6 @@ final class TodayUITests: XCTestCase { release.label.contains("Paper Lantern"), "Req 6.1: a work on hiatus is never in a releases section") - // Req 5.4: both of the current day's notes, in Recent's order.- let settled = expectation(for: NSPredicate(format: "count == 2"), evaluatedWith: recentRows)- XCTAssertEqual(- XCTWaiter().wait(for: [settled], timeout: 15), .completed,- "Req 5.4: the current day holds the two entries dated on it")- XCTAssertTrue(- recentRows.element(boundBy: 0).label.contains("Salt Harvest"),- "Recent's ordering: the later capture leads")- XCTAssertTrue(- recentRows.element(boundBy: 1).label.contains("Kite Season"),- "…and the earlier one follows it")- // `catch-up-mode`: the third section, after the releases and before the // notes, with the one work the reader is behind on. assertHeader(@@ -610,13 +628,8 @@ final class TodayUITests: XCTestCase { app.anyElement("today-section-releases").frame.minY, app.anyElement("today-section-catching-up").frame.minY, "Q4: it sits directly after the releases section")- XCTAssertLessThan(- app.anyElement("today-section-catching-up").frame.minY,- app.anyElement("today-section-noted").frame.minY,- "…and before the notes")-- XCTAssertEqual(catchUpRows.count, 1, "Only Ember Road is being caught up on")- let catchUp = catchUpRows.firstMatch+ XCTAssertEqual(catchUpRows.count, 3, "Exact, estimated and unknown works stay in the card")+ let catchUp = catchUpRow("Ember Road") XCTAssertTrue( catchUp.label.hasPrefix("Ember Road, Last read"), "Today v2 §5: the card row says what was read last — was \"\(catchUp.label)\"")@@ -624,11 +637,24 @@ final class TodayUITests: XCTestCase { catchUp.label.contains("yesterday"), "…measured against the day being shown — was \"\(catchUp.label)\"") XCTAssertEqual(- app.elements(withIdentifierPrefix: "today-catchup-next-").count, 1,+ app.elements(withIdentifierPrefix: "today-catchup-next-").count, 3, "Today v2 §5: each card row carries its own Next button") XCTAssertEqual( releaseRows.count, 1, "Q8: a catch-up work lights no release row, and the prefixes are disjoint")+ scrollUntilPresent(+ app.anyElement("today-section-noted"), in: app,+ "The Noted section follows the expanded catch-up card")+ assertHeader(+ "today-section-noted", says: "Noted",+ "Req 5.4/Q76: the noted section is reachable below Catching up")+ // The expanded card pushes this lazy section below the first viewport.+ let settled = expectation(for: NSPredicate(format: "count == 2"), evaluatedWith: recentRows)+ XCTAssertEqual(+ XCTWaiter().wait(for: [settled], timeout: 15), .completed,+ "Req 5.4: the current day holds the two entries dated on it")+ XCTAssertTrue(recentRows.element(boundBy: 0).label.contains("Salt Harvest"))+ XCTAssertTrue(recentRows.element(boundBy: 1).label.contains("Kite Season")) } /// Q5's other half: the section is a standing reminder, so a past day — which@@ -644,6 +670,137 @@ final class TodayUITests: XCTestCase { XCTAssertEqual(catchUpRows.count, 0, "…and no rows either") } + func testCatchUpProgressRowsAndBannerAreDistinct() {+ launchToday()+ let copper = waitFor(catchUpRow("Copper Atlas"), "The estimated work is listed")+ XCTAssertTrue(copper.label.contains("5 chapters behind"))+ XCTAssertTrue(copper.label.contains("estimated"))+ let frost = waitFor(catchUpRow("Frost Relay"), "The exact work is listed")+ XCTAssertTrue(frost.label.contains("4 chapters behind"))+ XCTAssertFalse(frost.label.contains("estimated"))+ XCTAssertTrue(catchUpRow("Ember Road").label.contains("Last read"))+ XCTAssertFalse(catchUpRow("Harbor Signal").exists)+ let banner = waitFor(catchUpBanners.firstMatch, "The caught-up work has a banner")+ XCTAssertTrue(banner.exists)+ XCTAssertTrue(app.staticTexts["Caught up on Harbor Signal."].exists)+ XCTAssertTrue(app.buttons["Move to Reading"].exists)+ XCTAssertTrue(app.buttons["Not yet, more is out"].exists)+ }++ func testSetLatestCancelKeepsTheBannerAndSaveMovesItIntoTheCard() {+ launchToday()+ waitFor(app.buttons["Not yet, more is out"], "The banner opens the sheet").tap()+ waitFor(app.anyElement("today-set-latest-sheet"), "The Set latest sheet is visible")+ let latestField = app.textFields["today-set-latest-number"]+ XCTAssertTrue(latestField.exists)+ app.buttons["today-set-latest-increase"].tap()+ let override = app.textFields["today-set-latest-last-read"]+ override.tap()+ override.typeText("7")+ let typedOverride = override.value as? String+ XCTAssertNotEqual(typedOverride, "8")+ XCUIDevice.shared.press(.home)+ app.activate()+ waitFor(app.anyElement("today-set-latest-sheet"), "The draft survives backgrounding")+ XCTAssertEqual(app.textFields["today-set-latest-number"].value as? String, "9")+ XCTAssertEqual(app.textFields["today-set-latest-last-read"].value as? String, typedOverride)+ app.buttons["today-set-latest-cancel"].tap()+ XCTAssertTrue(app.buttons["Move to Reading"].waitForExistence(timeout: 10))++ waitFor(app.buttons["Not yet, more is out"], "The banner still opens the sheet").tap()+ adjustLatest(to: 9)+ app.buttons["today-set-latest-save"].tap()+ XCTAssertTrue(catchUpRow("Harbor Signal").waitForExistence(timeout: 15))+ XCTAssertFalse(app.buttons["Move to Reading"].exists)+ }++ func testCaughtUpPrimaryActionMovesTheWorkOnlyAfterATap() {+ launchToday()+ XCTAssertTrue(app.buttons["Move to Reading"].exists)+ app.buttons["Move to Reading"].tap()+ XCTAssertFalse(app.buttons["Move to Reading"].waitForExistence(timeout: 10))+ XCTAssertFalse(catchUpRow("Harbor Signal").exists)+ }++ func testWorkPageLatestRowOpensTheSheetAndHidesInEditMode() {+ launchToday()+ scrollUntilTappableAndTap(+ catchUpRow("Frost Relay"), in: app,+ "The catch-up row opens its Work page")+ let latest = waitFor(+ app.buttons["work-detail-latest-released"], "The Work page shows latest released")+ XCTAssertTrue(latest.label.contains("10"))+ latest.tap()+ waitFor(app.anyElement("today-set-latest-sheet"), "The Work page opens the same sheet")+ app.buttons["today-set-latest-increase"].tap()+ app.buttons["today-set-latest-save"].tap()+ let refreshed = waitFor(+ app.buttons["work-detail-latest-released"],+ "The Work page reloads its latest row after the sheet Save")+ let changed = expectation(+ for: NSPredicate(format: "label CONTAINS %@", "11"), evaluatedWith: refreshed)+ XCTAssertEqual(XCTWaiter().wait(for: [changed], timeout: 15), .completed)+ waitFor(app.buttons["work-detail-edit-button"], "The page offers editing").tap()+ XCTAssertFalse(app.buttons["work-detail-latest-released"].exists)+ }++ func testFutureCaughtUpWorkIsARowWithoutBannerOrMenu() {+ launchToday()+ selectDay(daysFromLaunch: 1, "Tomorrow is selected")+ XCTAssertFalse(catchUpBanners.firstMatch.exists)+ let harbor = waitFor(catchUpRow("Harbor Signal"), "Caught up is a forecast row")+ XCTAssertTrue(harbor.label.contains("caught up"))+ harbor.press(forDuration: 1)+ XCTAssertFalse(app.buttons["Set latest…"].exists)+ }++ func testAllCaughtUpWorksLeaveTheHeaderAndBannersWithoutAnEmptyCard() {+ launchToday()+ saveLatest(6, for: "Copper Atlas")+ saveLatest(6, for: "Frost Relay")+ saveLatest(4, for: "Ember Road")+ XCTAssertTrue(app.anyElement("today-section-catching-up").exists)+ XCTAssertEqual(catchUpRows.count, 0)+ XCTAssertEqual(catchUpBanners.count, 4)+ XCTAssertEqual(app.elements(withIdentifierPrefix: "today-catchup-next-").count, 0)+ }++ func testCatchUpControlsRemainReachableAtLargestDynamicType() {+ app.launchArguments = [+ "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"+ ]+ launchToday()+ scrollUntilPresent(app.buttons["Move to Reading"], in: app,+ "The caught-up banner is reachable below the header")+ let primary = waitFor(app.buttons["Move to Reading"], "The caught-up action remains")+ XCTAssertGreaterThanOrEqual(primary.frame.height, 44)+ scrollUntilPresent(catchUpRow("Copper Atlas"), in: app,+ "The progress row becomes visible below the banner")+ let copper = waitFor(catchUpRow("Copper Atlas"), "The progress row is readable")+ XCTAssertGreaterThan(copper.frame.height, 70, "The row grows to wrap its progress")+ XCTAssertTrue(copper.label.contains("estimated"))+ for _ in 0..<3 { app.swipeDown() }+ scrollUntilTappableAndTap(+ app.buttons["Not yet, more is out"], in: app,+ "The sheet action stays reachable at the largest text size")+ waitFor(app.anyElement("today-set-latest-sheet"), "The sheet opens at large text")+ for id in ["today-set-latest-decrease", "today-set-latest-increase"] {+ let control = waitFor(app.buttons[id], "\(id) remains reachable")+ let settled = XCTNSPredicateExpectation(+ predicate: NSPredicate { _, _ in control.frame.height >= 43.9 }, object: nil)+ XCTAssertEqual(+ XCTWaiter().wait(for: [settled], timeout: 4), .completed,+ "\(id) stays below a 44 pt target after the sheet settles: \(control.frame)")+ }+ // UIKit toolbar buttons have system hit slop outside their reported+ // visual frame (`AccessibilityJourneyUITests.assertSystemControl`).+ for id in ["today-set-latest-save", "today-set-latest-cancel"] {+ let control = waitFor(app.buttons[id], "\(id) remains in the toolbar")+ XCTAssertTrue(control.isHittable, "\(id) remains operable")+ XCTAssertFalse(control.label.isEmpty, "\(id) has a spoken name")+ }+ }+ /// Req 5.5's other placement: a past day reads as a record, so the notes come /// first. Q55 is why this is the one journey that may have to page. func testAPastDayLeadsWithItsNotes() {@@ -870,6 +1027,9 @@ final class TodayUITests: XCTestCase { waitFor(app.collectionViews["recent-list"], "The seeded library opens", timeout: 60) XCTAssertEqual( releaseRows.count, 1, "One work is due on the current weekday")+ scrollUntilPresent(+ app.anyElement("today-section-noted"), in: app,+ "The four work-only catch-up fixtures leave Recent below the fold") let settled = expectation(for: NSPredicate(format: "count == 2"), evaluatedWith: recentRows) XCTAssertEqual( XCTWaiter().wait(for: [settled], timeout: 15), .completed,
diff --git a/Asterism/AsterismUITests/WideLayoutUITests.swift b/Asterism/AsterismUITests/WideLayoutUITests.swiftindex d81d93c1..bee56a0b 100644--- a/Asterism/AsterismUITests/WideLayoutUITests.swift+++ b/Asterism/AsterismUITests/WideLayoutUITests.swift@@ -356,9 +356,10 @@ final class WideLayoutUITests: XCTestCase { let detailColumn = waitFor( app.anyElement("wide-detail-column"), "The detail column is laid out") let placePill = app.anyElement("work-detail-place")- scrollUntilPresent(placePill, in: app, "The Places section draws in the wide layout")+ for _ in 0..<8 where !placePill.exists { detailColumn.swipeUp() }+ waitFor(placePill, "The Places section draws in the wide layout") assertInsideColumn(placePill, column: detailColumn, what: "The kept place's pill")- waitFor(app.anyElement("library-hub"), "…with the hub still beside it")+ waitFor(app.anyElement("works-group-allWorks"), "…with All works still beside it") } // MARK: - Q57 — a chapter replaces its work in the detail column@@ -992,6 +993,13 @@ final class WideLayoutUITests: XCTestCase { waitFor(app.anyElement("today-header-date"), "…on a day rather than on every day") } + private func returnToTodayHeader() {+ let list = app.collectionViews["recent-list"]+ let chevron = app.anyElement("today-week-previous")+ for _ in 0..<8 where !chevron.exists { list.swipeDown() }+ waitFor(chevron, "The week controls remain reachable above the expanded card")+ }+ /// `yyyy-MM-dd`, the spelling `CivilDay.description` gives a strip cell's /// identifier: proleptic Gregorian in the device's zone, under a fixed /// locale, because this is an identifier and not a presentation.@@ -1077,8 +1085,12 @@ final class WideLayoutUITests: XCTestCase { waitFor(app.collectionViews["recent-list"], "The day stays beside the column") waitFor(app.anyElement("today-header-date"), "…with its chrome, since nothing was pushed") + // The expanded catch-up section places Noted below the lazy list's+ // first viewport. Scroll the Today column, leaving detail in place.+ let todayList = app.collectionViews["recent-list"]+ for _ in 0..<8 where !recentRows.firstMatch.exists { todayList.swipeUp() } // Req 10.1: selecting the other kind clears the first.- let noted = waitFor(recentRows.element(boundBy: 0), "The day lists a note too")+ let noted = waitFor(recentRows.firstMatch, "The day lists a note too") let entryID = Self.entryID(fromRowIdentifier: noted.identifier) XCTAssertFalse(entryID.isEmpty, "The row is identified by the entry it opens") noted.tap()@@ -1103,7 +1115,9 @@ final class WideLayoutUITests: XCTestCase { func testAChangeOfSelectedDayClearsAVanishedSelection() { launchToday() - let noted = waitFor(recentRows.element(boundBy: 0), "The current day lists a note")+ let todayList = app.collectionViews["recent-list"]+ for _ in 0..<8 where !recentRows.firstMatch.exists { todayList.swipeUp() }+ let noted = waitFor(recentRows.firstMatch, "The current day lists a note") let entryID = Self.entryID(fromRowIdentifier: noted.identifier) XCTAssertFalse(entryID.isEmpty, "The row is identified by the entry it opens") noted.tap()@@ -1116,6 +1130,7 @@ final class WideLayoutUITests: XCTestCase { // reached through the chevron only when the calendar says so. let target = stripCell(daysFromLaunch: -3) if !target.exists {+ returnToTodayHeader() waitFor(app.anyElement("today-week-previous"), "The week row pages back").tap() } waitFor(target, "A day holding neither the entry nor a release is reachable").tap()@@ -1151,6 +1166,7 @@ final class WideLayoutUITests: XCTestCase { let target = stripCell(daysFromLaunch: -3) if !target.exists {+ returnToTodayHeader() waitFor(app.anyElement("today-week-previous"), "The week row pages back").tap() } waitFor(target, "A past day, where the section is not drawn at all").tap()@@ -1294,7 +1310,7 @@ final class WideLayoutUITests: XCTestCase { launch(ToReadMatchScenario.scenario, orientation: .landscapeLeft) waitForLibrary() - selectTab(.works, in: app)+ openAllWorks(in: app) waitFor( app.buttons["work-to-read-match-pill"], "The captured work's row carries the pill" ).tap()
diff --git a/Makefile b/Makefileindex a3468635..4ab14c85 100644--- a/Makefile+++ b/Makefile@@ -41,6 +41,10 @@ else PIPE_PRETTY = endif +# Optional xcodebuild flags for simulator test targets; empty keeps their+# existing invocation unchanged. Useful for isolating Xcode diagnostics stalls.+XCODE_TEST_FLAGS ?=+ .PHONY: help help: @echo "Available targets:"@@ -207,6 +211,7 @@ endif -only-testing:$(UNIT_TEST_BUNDLE) \ -parallel-testing-enabled NO \ -parallel-testing-worker-count 1 \+ $(XCODE_TEST_FLAGS) \ $(PIPE_PRETTY) # The opt-in gate must be set on the test command, not before $(PIPEFAIL):@@ -397,6 +402,7 @@ test-performance-m4-recent: PERFORMANCE_LOG ?= CONTROLLED ?= RUNS ?= 1+PERFORMANCE_FILTER ?= M4(ScalePerformance|ToleratedScalePerformance|ToleratedFixture|DuplicateScalePerformance|MembershipScalePerformance|SeriesScalePerformance|CreatorScalePerformance|EmptyLibraryPerformance|ToReadMatchScalePerformance)Tests .PHONY: test-performance-m4 test-performance-m4: $(PIPEFAIL) for run in $$(seq 1 $(RUNS)); do \@@ -408,7 +414,7 @@ test-performance-m4: --no-parallel \ -c release \ -Xswiftc -DASTERISM_PERFORMANCE_TESTING \- --filter 'M4(ScalePerformance|ToleratedScalePerformance|ToleratedFixture|DuplicateScalePerformance|MembershipScalePerformance|SeriesScalePerformance|CreatorScalePerformance|EmptyLibraryPerformance|ToReadMatchScalePerformance)Tests' \+ --filter '$(PERFORMANCE_FILTER)' \ || exit $$?; \ done @@ -465,6 +471,7 @@ test: -parallel-testing-enabled NO \ -parallel-testing-worker-count 1 \ -maximum-concurrent-test-simulator-destinations 1 \+ $(XCODE_TEST_FLAGS) \ $(PIPE_PRETTY) .PHONY: test-ui@@ -481,6 +488,7 @@ test-ui: -parallel-testing-enabled NO \ -parallel-testing-worker-count 1 \ -maximum-concurrent-test-simulator-destinations 1 \+ $(XCODE_TEST_FLAGS) \ $(PIPE_PRETTY) # Req 9.2: the wide layout's own suite, on a regular-width destination.@@ -510,6 +518,7 @@ test-ui-ipad: -parallel-testing-enabled NO \ -parallel-testing-worker-count 1 \ -maximum-concurrent-test-simulator-destinations 1 \+ $(XCODE_TEST_FLAGS) \ $(PIPE_PRETTY) .PHONY: test-only@@ -530,6 +539,7 @@ test-only: -parallel-testing-enabled NO \ -parallel-testing-worker-count 1 \ -maximum-concurrent-test-simulator-destinations 1 \+ $(XCODE_TEST_FLAGS) \ $(PIPE_PRETTY) # DEVICE picks the physical device by alias: `phone` (the default) or `ipad`,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift b/Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swiftindex 09777ce6..e5b932ea 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift@@ -48,7 +48,7 @@ internal enum ArchiveThumbnail: Equatable, Sendable { /// shape with no bytes, or bytes with no shape, claims a cover this import /// cannot honour, so it is `.dropped` and named rather than silently half /// applied.- static func of(_ record: BackupV15Work) -> ArchiveThumbnail {+ static func of(_ record: BackupV16Work) -> ArchiveThumbnail { switch (record.thumbnailShape, record.thumbnail) { case (nil, nil): return .none@@ -65,14 +65,14 @@ internal enum ArchiveThumbnail: Equatable, Sendable { internal enum ArchiveRecordBuilders { - static func makeSite(_ record: BackupV15Site) -> Site {+ static func makeSite(_ record: BackupV16Site) -> Site { let site = Site(hostname: record.hostname, displayName: record.displayName) site.modeRaw = record.mode.rawValue return site } static func makeTitlePattern(- _ record: BackupV15TitlePattern, site: Site?+ _ record: BackupV16TitlePattern, site: Site? ) throws -> TitlePattern { return try TitlePattern( id: record.id,@@ -87,7 +87,7 @@ internal enum ArchiveRecordBuilders { } static func makeURLRule(- _ record: BackupV15URLRule, site: Site?+ _ record: BackupV16URLRule, site: Site? ) throws -> URLRulePattern { try URLRulePattern( id: record.id,@@ -103,7 +103,7 @@ internal enum ArchiveRecordBuilders { /// The wire timestamps are what an import-created row carries on both fields /// (Q33), and an unrecognised state coerces to `.active` rather than /// refusing — a type row from a later build's wider set is legal data.- static func makeWorkType(_ record: BackupV15WorkType) -> WorkTypeEntity {+ static func makeWorkType(_ record: BackupV16WorkType) -> WorkTypeEntity { makeWorkType( id: record.id, name: record.name, state: ToleratedEnum.read(record.stateRaw, default: .active),@@ -131,7 +131,7 @@ internal enum ArchiveRecordBuilders { /// `WorkSiteMembership`, which `makeMembership` below builds from the /// archive's own records. static func makeWork(- _ record: BackupV15Work, thumbnail: ArchiveThumbnail = .none+ _ record: BackupV16Work, thumbnail: ArchiveThumbnail = .none ) -> Work { let work = Work( id: record.id,@@ -139,6 +139,7 @@ internal enum ArchiveRecordBuilders { timestamp: record.createdAt ) LibraryRepository.apply(record, to: work, thumbnail: thumbnail)+ CatchUpWriter.apply(record.catchUpRecord, to: [work]) return work } @@ -146,7 +147,7 @@ internal enum ArchiveRecordBuilders { /// carries it. `workID` travels whether or not the Work is there (Q37), so an /// orphan re-attaches when its Work arrives (Req 8.3, 9.5). static func makeMembership(- _ record: BackupV15Membership, work: Work?, site: Site?+ _ record: BackupV16Membership, work: Work?, site: Site? ) -> WorkSiteMembership { WorkSiteMembership( id: record.id,@@ -164,7 +165,7 @@ internal enum ArchiveRecordBuilders { /// One dismissed pair. The record's ids are already in the canonical sorted /// order — `BackupImportPayload` normalises them at the door — so nothing /// here re-sorts and then disagrees about which end is which.- static func makeDistinctPair(_ record: BackupV15DistinctPair) -> WorkDistinctPair {+ static func makeDistinctPair(_ record: BackupV16DistinctPair) -> WorkDistinctPair { WorkDistinctPair( id: record.id, lowerWorkID: record.lowerWorkID, higherWorkID: record.higherWorkID, recordedAt: record.recordedAt)@@ -174,7 +175,7 @@ internal enum ArchiveRecordBuilders { /// nothing derived: the name and notes are stored trimmed by every writer /// and the reference checks refuse an empty name, so the record's values go /// in as they arrived.- static func makeSeries(_ record: BackupV15Series) -> Series {+ static func makeSeries(_ record: BackupV16Series) -> Series { Series( id: record.id, name: record.name, notes: record.notes, createdAt: record.createdAt, modifiedAt: record.modifiedAt)@@ -183,7 +184,7 @@ internal enum ArchiveRecordBuilders { /// One link row. The record's ids are already in the canonical sorted order /// — `BackupImportPayload` normalises them at the door — so nothing here /// re-sorts and then disagrees about which end is which.- static func makeLink(_ record: BackupV15Link) -> WorkLink {+ static func makeLink(_ record: BackupV16Link) -> WorkLink { WorkLink( id: record.id, lowerWorkID: record.lowerWorkID, higherWorkID: record.higherWorkID, linkType: record.linkType,@@ -197,7 +198,7 @@ internal enum ArchiveRecordBuilders { /// import once and stay put: the next sync fold and a repeated import see /// exactly what the exporting device saw and write nothing. An unrecognised /// state coerces to `.active` at every read site, so the raw column travels.- static func makeCreator(_ record: BackupV15Creator) -> Creator {+ static func makeCreator(_ record: BackupV16Creator) -> Creator { let row = Creator( id: record.id, name: record.name, notes: record.notes, stateRaw: record.stateRaw, canonicalID: record.canonicalID)@@ -210,7 +211,7 @@ internal enum ArchiveRecordBuilders { } /// One role row, the same way, with the archive's list position.- static func makeCreatorRole(_ record: BackupV15CreatorRole) -> CreatorRole {+ static func makeCreatorRole(_ record: BackupV16CreatorRole) -> CreatorRole { makeCreatorRole(record, position: record.position, at: record.positionModifiedAt) } @@ -219,7 +220,7 @@ internal enum ArchiveRecordBuilders { /// stamped at import time so a later-arriving sync row cannot undo the /// placement (Req 9.4, Q38). static func makeCreatorRole(- _ record: BackupV15CreatorRole, position: Int, at positionModifiedAt: Date+ _ record: BackupV16CreatorRole, position: Int, at positionModifiedAt: Date ) -> CreatorRole { let row = CreatorRole( id: record.id, name: record.name, position: position,@@ -239,14 +240,14 @@ internal enum ArchiveRecordBuilders { /// render, never a row to drop. `roleIDs` is normalised on the way in for /// the reason every writer normalises it: equal sets have to be equal /// arrays.- static func makeCredit(_ record: BackupV15Credit) -> WorkCredit {+ static func makeCredit(_ record: BackupV16Credit) -> WorkCredit { WorkCredit( id: record.id, workID: record.workID, creatorID: record.creatorID, roleIDs: WorkCreditSupport.roleIDs(record.roleIDs), createdAt: record.createdAt, modifiedAt: record.modifiedAt) } - static func makeEntry(_ record: BackupV15Entry) -> Entry {+ static func makeEntry(_ record: BackupV16Entry) -> Entry { let entry = Entry( id: record.id, captureTitle: record.captureTitle,@@ -299,19 +300,19 @@ internal enum ArchiveRecordBuilders { // The four named entry points stay: each table's `make(imported:)` names its // own archive record, and the generic pair above is the body they share. - static func makeCharacter(_ record: BackupV15Character) -> CharacterRecord {+ static func makeCharacter(_ record: BackupV16Character) -> CharacterRecord { makeRecord(CharacterRecord.self, record) } - static func makeSuppression(_ record: BackupV15Suppression) -> CharacterSuppression {+ static func makeSuppression(_ record: BackupV16Suppression) -> CharacterSuppression { makeSuppressionRow(CharacterSuppression.self, record) } - static func makePlace(_ record: BackupV15Place) -> Place {+ static func makePlace(_ record: BackupV16Place) -> Place { makeRecord(Place.self, record) } - static func makePlaceSuppression(_ record: BackupV15PlaceSuppression) -> PlaceSuppression {+ static func makePlaceSuppression(_ record: BackupV16PlaceSuppression) -> PlaceSuppression { makeSuppressionRow(PlaceSuppression.self, record) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swiftindex 4b276dfa..67698ea7 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swift@@ -18,7 +18,7 @@ public struct AsterismCapabilities: Codable, Equatable, Sendable { /// and the archive it writes is format 11 over schema 12. Nothing about a /// *rule form* changes with it — every `supports…` answer below is m4's /// — so the case exists to name the store shape and the rule-form set,- /// which is what `BackupV15Codec` stamps. The literal has not moved with+ /// which is what `BackupV16Codec` stamps. The literal has not moved with /// any archive generation since: none of 8/9 through 15/16 changes those /// two things (`rule-citation-by-uuid` Q19), and the generation is named /// by its format and schema numbers, which are what the importer gates@@ -35,7 +35,7 @@ public struct AsterismCapabilities: Codable, Equatable, Sendable { public static let multiSite = AsterismCapabilities(gate: .multiSite) /// The current runtime gate is `.multiSite` (`multi-site-works` Q29).- /// `BackupV15Codec` stamps the literal `"multi-site"` rather than reading+ /// `BackupV16Codec` stamps the literal `"multi-site"` rather than reading /// this value, so the archive's gate is independent of the runtime's. /// Earlier gates stay available because the schema and teaching suites still /// exercise them — `CapabilityGatingTests`, `PhraseParsingTests`,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV15.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV15.swiftdeleted file mode 100644index d77f1cee..00000000--- a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV15.swift+++ /dev/null@@ -1,398 +0,0 @@-import Foundation-import SwiftData--/// The frozen `update-schedule` schema — the shape every installed library was-/// written by before `remove-article-mode`, and the `from` version of the-/// V15 → V16 lightweight stage.-///-/// V15 was V14 **plus one defaulted `Work` column**, `releaseDaysRaw`, and no-/// table at all. V16 **removes** one `Site` column, `junkSuffixRule`, and adds-/// nothing: it is the second removing stage in the project's history, after-/// V8 → V9, and the entity list stays at seventeen.-///-/// V15 is frozen for the same reason V5 through V14 were: *any* edit to its body-/// makes a V15-recorded store refuse to open with `NSCocoaErrorDomain` 134504,-/// "Cannot use staged migration with an unknown model version". The live classes-/// therefore moved to `AsterismSchemaV16`, and this declaration exists only to-/// give `AsterismV16MigrationPlan` the `from` version of its **only** stage —-/// and to let `V15RecordedStoreFixture` seed a genuinely 15.0.0-recorded store-/// in-process. It is the last snapshot the package declares: the V14 → V15 stage-/// and `AsterismSchemaV14` retired with this freeze, on-/// `retire-migration-chain` Decision 6's population precondition, confirmed by-/// the owner on 2026-09-21 (`remove-article-mode` Q10).-///-/// The classes are nested so they can carry the same SwiftData entity names-/// ("Entry", "Site", …) as the live V16 classes without a top-level collision:-/// the only top-level references are typealiases, and two *top-level* `@Model`s-/// sharing an entity name crash `ModelContext`-/// (`docs/agent-notes/schema-migration.md`). Nothing reads a V15-shaped object-/// at runtime, so these carry stored columns and attribute options only — no-/// accessors, no business logic.-///-/// # These snapshots are frozen *by reference*, not only by file-///-/// The nesting freezes the class bodies; it does **not** freeze anything a body-/// *names*. Editing one of those changes the stored shape of this frozen schema-/// silently — and that is exactly what makes a recorded store refuse to open-/// (134504). Two families of referent:-///-/// * **The stored value types.** `Site.junkSuffixRule` is a `JunkSuffixRule`,-/// a top-level type in `ValueObjects.swift`, and it stores-/// `[SegmentPositionSpec]`; the stored properties of **both** are this-/// schema's stored properties. After `remove-article-mode` this file is-/// `JunkSuffixRule`'s only consumer — the live `Site` has no such column —-/// which is precisely why the type stays where it is, unchanged, until V15-/// itself retires (Q8). Do not move it, nest it, rename its properties or-/// touch its `Codable` representation.-/// * **Every enum whose raw value is baked into a default.** A default is part-/// of the shape, so `CaptureTitleSource.manual.rawValue`,-/// `EntryIdentityBasis.conservative.rawValue`, `TitleProvenance.manual`,-/// `SiteMode.untaught.rawValue`, `URLRuleOrigin.readerTaught`,-/// `WorkTypeState.active`, `CharacterSuppressionKind.candidate`,-/// `CharacterSuppressionStatus.active`, `WorkURLIdentityState.none`,-/// `WorkStatus.ongoing` and `ReadingStatus.reading` are all frozen *spellings*-/// here, not merely frozen references. Renaming a case, or reordering one-/// whose raw value is derived rather than written out, edits this file without-/// touching it.-///-/// **`SiteMode.articles` was never one of them.** `modeRaw` defaults to-/// `untaught`, so removing the `articles` case changed no default in this-/// file; an `articles` row is a stored *value* a V15 build wrote, and the-/// live build reads it as any other unknown mode (Decision 1).-///-/// # What this generation freezes beyond the columns-///-/// Everything V14's header named, carried across verbatim:-///-/// `@Attribute(.externalStorage)` on `thumbnailData` is the schema's only-/// attribute option and it is part of the **stored** shape, so it is carried-/// across verbatim (`work-thumbnails` Decision 2). `ThumbnailShape`'s two raw-/// spellings and the SHA-256 digest function are frozen for this generation-/// too — they are bytes in every installed library — but no *default* here-/// names them, because all three columns are optional.-///-/// And one of V15's own: **`ReleaseDay`'s seven raw spellings**, the lowercase-/// English day names `releaseDaysRaw` holds in every installed library. No-/// column default names them either — the default is the empty array — but a-/// stored spelling is a stored spelling. `ModelContractTests` pins the-/// spellings and the case order on the live schema.-public enum AsterismSchemaV15: VersionedSchema {- public static let versionIdentifier = Schema.Version(15, 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]- }-}--extension AsterismSchemaV15 {- @Model- public final class Entry {- public var id: UUID = UUID()- public var captureTitle: String = ""- public var captureTitleSourceRaw: String = CaptureTitleSource.manual.rawValue- public var rawURLString: String = ""- public var canonicalURLString: String?- public var hostname: String = ""- public var site: Site?- public var entryIdentityKey: String = ""- public var conservativeIdentityKey: String = ""- public var identityBasisRaw: String = EntryIdentityBasis.conservative.rawValue- public var urlWorkIdentity: String?- public var chapterSequence: String?- public var chapterTitle: String?- public var note: String = ""- public var ratingRaw: String?- public var firstCapturedAt: Date = Date(timeIntervalSince1970: 0)- public var lastSharedAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)- public var work: Work?- public var intentionallyUnattached: Bool = false- public var characterExtractionFingerprint: String?- public var citationsData: Data?-- public init() {}- }-- @Model- public final class Work {- public var id: UUID = UUID()- public var displayTitle: String = ""- public var lastParsedTitle: String?- public var genericNotes: String = ""- public var workTypeID: UUID?- public var genreTags: [String] = []- public var titleProvenanceRaw: String = TitleProvenance.manual.rawValue- /// V10's three additions. Their property initialisers are the Core Data- /// attribute defaults the V9 → V10 stage wrote into every existing row,- /// which is why the two enum spellings are frozen here (see the header).- public var workStatusRaw: String = WorkStatus.ongoing.rawValue- public var readingStatusRaw: String = ReadingStatus.reading.rawValue- public var verdict: String = ""- /// V11's two additions, both **optional**: nil is "this work is in no- /// series", so the V10 → V11 stage had no attribute default to write.- public var seriesID: UUID?- public var seriesPosition: Double?- /// V15's one addition, and the only **defaulted** column any stage has- /// added to this table since V10's three: a `[String]` on the- /// `genreTags` shape (`update-schedule` Q27). Its property initialiser- /// `= []` is the Core Data attribute default the V14 → V15 stage wrote- /// into every existing row, which is why the empty array — and not any- /// `ReleaseDay` spelling — is what is baked in here.- public var releaseDaysRaw: [String] = []- /// V14's three additions, all **optional**, so the V13 → V14 stage had- /// no attribute default to write either.- ///- /// **`.externalStorage` is part of the stored shape**, not a hint: it- /// puts the blob in a sidecar under the store's `_SUPPORT` directory and- /// leaves a reference on the row (`work-thumbnails` Decision 2). It is- /// the schema's only `@Attribute`, and it is carried across verbatim- /// here for the reason this whole file exists — a snapshot whose stored- /// shape differs from the recorded one by so much as an option makes a- /// V14-recorded store refuse to open.- @Attribute(.externalStorage)- public var thumbnailData: Data?- public var thumbnailShapeRaw: String?- public var thumbnailDigest: String?- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)- public var genericNotesExtractionFingerprint: String?- @Relationship(deleteRule: .nullify, inverse: \Entry.work)- public var entries: [Entry]?- @Relationship(deleteRule: .nullify, inverse: \Character.work)- public var characters: [Character]?- @Relationship(deleteRule: .nullify, inverse: \CharacterSuppression.work)- public var characterSuppressions: [CharacterSuppression]?- @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.work)- public var siteMemberships: [WorkSiteMembership]? = []-- public init() {}- }-- @Model- public final class Site {- public var hostname: String = ""- public var displayName: String = ""- public var modeRaw: String = SiteMode.untaught.rawValue- @Relationship(deleteRule: .cascade, inverse: \TitlePattern.site)- public var patterns: [TitlePattern]?- @Relationship(deleteRule: .cascade, inverse: \URLRulePattern.site)- public var urlRules: [URLRulePattern]?- /// Inverse of `Entry.site`, present only because CloudKit requires every- /// relationship to have one. Internal for the same reason the live class- /// keeps it internal (Q17): traversing it faults every Entry for a- /// hostname.- @Relationship(deleteRule: .nullify, inverse: \Entry.site)- var entries: [Entry]?- /// Inverse of `WorkSiteMembership.site`. Same reasoning again.- @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.site)- var workMemberships: [WorkSiteMembership]?- public var junkSuffixRule: JunkSuffixRule?-- public init() {}- }-- @Model- public final class TitlePattern {- public var id: UUID = UUID()- public var version: Int = 1- public var isActive: Bool = false- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var definitionData: Data?- public var site: Site?-- public init() {}- }-- @Model- public final class URLRulePattern {- public var id: UUID = UUID()- public var version: Int = 1- public var isCurrent: Bool = false- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var originRaw: String = URLRuleOrigin.readerTaught.rawValue- public var definitionData: Data = Data()- public var site: Site?-- public init() {}- }-- @Model- public final class WorkTypeEntity {- public var id: UUID = UUID()- public var name: String = ""- public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)- public var stateRaw: String = WorkTypeState.active.rawValue- public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)- public var canonicalID: UUID?- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-- @Model- public final class Character {- public var id: UUID = UUID()- public var name: String = ""- public var nameKey: String = ""- public var aliases: [String] = []- public var note: String = ""- public var factsData: Data?- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)- public var work: Work?-- public init() {}- }-- @Model- public final class CharacterSuppression {- public var id: UUID = UUID()- public var work: Work?- public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue- public var nameKey: String = ""- public var sourceKindRaw: String?- public var sourceEntryID: UUID?- public var evidence: String?- public var statusRaw: String = CharacterSuppressionStatus.active.rawValue- public var actionAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-- @Model- public final class WorkSiteMembership {- public var id: UUID = UUID()- public var hostname: String = ""- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var urlIdentity: String?- public var urlIdentityStateRaw: String = WorkURLIdentityState.none.rawValue- public var urlIdentityRuleID: UUID?- public var workURLString: String?- public var workID: UUID?- public var work: Work?- public var site: Site?-- public init() {}- }-- @Model- public final class WorkDistinctPair {- public var id: UUID = UUID()- public var lowerWorkID: UUID = UUID()- public var higherWorkID: UUID = UUID()- public var recordedAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-- @Model- public final class Series {- public var id: UUID = UUID()- public var name: String = ""- public var notes: String = ""- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-- @Model- public final class WorkLink {- public var id: UUID = UUID()- public var lowerWorkID: UUID = UUID()- public var higherWorkID: UUID = UUID()- public var linkType: String = ""- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-- /// V12's three additions. `stateRaw` defaults to the **literal** `"active"`- /// rather than to `CreatorState.active.rawValue`, which is why neither of- /// the two new enums appears in the header's frozen-spelling list.- @Model- public final class Creator {- public var id: UUID = UUID()- public var name: String = ""- public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)- public var notes: String = ""- public var notesModifiedAt: Date = Date(timeIntervalSince1970: 0)- public var stateRaw: String = "active"- public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)- public var canonicalID: UUID?- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-- @Model- public final class CreatorRole {- public var id: UUID = UUID()- public var name: String = ""- public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)- public var position: Int = 0- public var positionModifiedAt: Date = Date(timeIntervalSince1970: 0)- public var stateRaw: String = "active"- public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)- public var canonicalID: UUID?- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-- @Model- public final class WorkCredit {- public var id: UUID = UUID()- public var workID: UUID = UUID()- public var creatorID: UUID = UUID()- public var roleIDs: [String] = []- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-- /// V13's two additions. Both name their work by **UUID column** rather than- /// by relationship, which is why neither declares a `@Relationship` at all,- /// and both enum columns default to the *shared* suppression enums already- /// frozen through `CharacterSuppression` above — so V13 brought no new- /// frozen spelling into this file either.- @Model- public final class Place {- public var id: UUID = UUID()- public var name: String = ""- public var nameKey: String = ""- public var aliases: [String] = []- public var note: String = ""- public var factsData: Data?- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)- public var workID: UUID = UUID()-- public init() {}- }-- @Model- public final class PlaceSuppression {- public var id: UUID = UUID()- public var workID: UUID = UUID()- public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue- public var nameKey: String = ""- public var sourceKindRaw: String?- public var sourceEntryID: UUID?- public var evidence: String?- public var statusRaw: String = CharacterSuppressionStatus.active.rawValue- public var actionAt: Date = Date(timeIntervalSince1970: 0)-- public init() {}- }-}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV16.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV16.swiftindex 506a63d2..536570d8 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV16.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV16.swift@@ -1,36 +1,8 @@ import Foundation import SwiftData -/// The runtime schema. Its body is `Models.swift`, which opens-/// `extension AsterismSchemaV16`.-///-/// V16 is V15 **minus one `Site` column** — `junkSuffixRule`, the title cleaner-/// only articles mode ever wrote (`remove-article-mode`). Nothing else moves: no-/// table is added or removed, no existing column changes type, no relationship-/// changes shape, and the entity list stays at seventeen.-///-/// **It is the second stage in the project's history to remove anything**, after-/// V8 → V9, and the first since. A removing stage has no attribute default to-/// write: the column simply stops existing, and Core Data drops it inside-/// `ModelContainer.init`. There is no data pass, and there is nothing for one to-/// do — the value the column held has no reader left, which is what-/// `remove-article-mode`'s first commit established.-///-/// A store that arrives here carrying `modeRaw = "articles"` — written by a V15-/// build on another device — keeps that value. It is a stored *value*, not a-/// stored shape, and the live build reads it as any other unknown mode:-/// quarantined under `.siteTuple`, omitted from the sites list, refused by name-/// on export, and no obstacle to the library opening or to marker `"16"` being-/// published (Req 3.4, Decision 1).-///-/// # What this generation freezes-///-/// The next freeze inherits everything V15's header named, unchanged:-/// `ThumbnailShape`'s two raw spellings, the SHA-256 digest function,-/// `@Attribute(.externalStorage)` on `thumbnailData` — part of the *stored*-/// shape rather than a hint — and `ReleaseDay`'s seven lowercase English day-/// names. V16 brings nothing of its own: a stage that only removes bakes no new-/// raw value in anywhere.+/// Frozen V16 stored shape, the `from` side of the V16 → V17 stage.+/// Keep its stored columns, relationships, defaults, and referenced wire types unchanged. public enum AsterismSchemaV16: VersionedSchema { public static let versionIdentifier = Schema.Version(16, 0, 0) @@ -44,52 +16,309 @@ public enum AsterismSchemaV16: VersionedSchema { } } -/// The migration plan: `[V15, V16]`, one lightweight stage.-///-/// The V14 → V15 stage retired here, with `AsterismSchemaV14`,-/// `V14RecordedStoreFixture` and `V14RecordedStoreTests`, on-/// `retire-migration-chain` Decision 6's population precondition: every device-/// was confirmed on marker `"15"` on 2026-09-21 (`remove-article-mode` Q10). As-/// at the previous five bumps, the verification landed *before* the freeze-/// rather than a commit after it, so the marker set and the plan have never-/// disagreed at this generation.-///-/// The retirement is **one commit** with the freeze, because a fixture that-/// opens a deleted snapshot does not compile (Q43 of `work-and-reading-status`,-/// Q60 of `series-and-related-works`, Q15 of `work-creators`, Q65 of-/// `place-extraction`, and `work-thumbnails` and `update-schedule` again).-///-/// A store older than V15 fails closed — `NSCocoaErrorDomain` 134504, "Cannot-/// use staged migration with an unknown model version" — and the recovery is the-/// backup archive, which is what `V4RecordedStoreTests` pins.-///-/// The stage is `.lightweight` and purely **removes**. `.custom` is not an-/// option here, and for a removing stage the reason is sharper than usual: a-/// custom stage would also run inside the share extension, which must never-/// migrate, and a concurrent share-sheet open part-way through a *removal* is-/// destructive rather than merely early. The extension is kept out by the-/// marker instead — it opens `"16"` only.-///-/// V8 → V9 is the precedent for the shape of this stage: it dropped optional-/// `Codable` struct attributes of exactly `JunkSuffixRule`'s kind-/// (`Site.urlIdentityRule`, `TitlePattern.segmentWorkAnchor`) under one-/// lightweight stage, which is why no spike preceded this one (Q14).-///-/// The live stored shape is a strict **subset** of the frozen one again, for the-/// first time since V9 — V16 only removes — so a stale snapshot registration-/// cannot meet a live key it is unable to answer. That is a safety net V10-/// through V15 did not have, and it is not the one being relied on:-/// `V15RecordedStoreFixture`'s create-seed-save-**release** ordering, together-/// with `make test-core`'s `--no-parallel`, is still what holds SwiftData's-/// global entity registry coherent (`docs/agent-notes/schema-migration.md`).-public enum AsterismV16MigrationPlan: SchemaMigrationPlan {- public static var schemas: [any VersionedSchema.Type] {- [AsterismSchemaV15.self, AsterismSchemaV16.self]- }-- public static var stages: [MigrationStage] {- [- .lightweight(fromVersion: AsterismSchemaV15.self, toVersion: AsterismSchemaV16.self),- ]+extension AsterismSchemaV16 {+ @Model+ public final class Entry {+ public var id: UUID = UUID()+ public var captureTitle: String = ""+ public var captureTitleSourceRaw: String = CaptureTitleSource.manual.rawValue+ public var rawURLString: String = ""+ public var canonicalURLString: String?+ public var hostname: String = ""+ public var site: Site?+ public var entryIdentityKey: String = ""+ public var conservativeIdentityKey: String = ""+ public var identityBasisRaw: String = EntryIdentityBasis.conservative.rawValue+ public var urlWorkIdentity: String?+ public var chapterSequence: String?+ public var chapterTitle: String?+ public var note: String = ""+ public var ratingRaw: String?+ public var firstCapturedAt: Date = Date(timeIntervalSince1970: 0)+ public var lastSharedAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var work: Work?+ public var intentionallyUnattached: Bool = false+ public var characterExtractionFingerprint: String?+ public var citationsData: Data?++ public init() {}+ }++ @Model+ public final class Work {+ public var id: UUID = UUID()+ public var displayTitle: String = ""+ public var lastParsedTitle: String?+ public var genericNotes: String = ""+ public var workTypeID: UUID?+ public var genreTags: [String] = []+ public var titleProvenanceRaw: String = TitleProvenance.manual.rawValue+ /// V10's three additions. Their property initialisers are the Core Data+ /// attribute defaults the V9 → V10 stage wrote into every existing row,+ /// which is why the two enum spellings are frozen here (see the header).+ public var workStatusRaw: String = WorkStatus.ongoing.rawValue+ public var readingStatusRaw: String = ReadingStatus.reading.rawValue+ public var verdict: String = ""+ /// V11's two additions, both **optional**: nil is "this work is in no+ /// series", so the V10 → V11 stage had no attribute default to write.+ public var seriesID: UUID?+ public var seriesPosition: Double?+ /// V15's one addition, and the only **defaulted** column any stage has+ /// added to this table since V10's three: a `[String]` on the+ /// `genreTags` shape (`update-schedule` Q27). Its property initialiser+ /// `= []` is the Core Data attribute default the V14 → V15 stage wrote+ /// into every existing row, which is why the empty array — and not any+ /// `ReleaseDay` spelling — is what is baked in here.+ public var releaseDaysRaw: [String] = []+ /// V14's three additions, all **optional**, so the V13 → V14 stage had+ /// no attribute default to write either.+ ///+ /// **`.externalStorage` is part of the stored shape**, not a hint: it+ /// puts the blob in a sidecar under the store's `_SUPPORT` directory and+ /// leaves a reference on the row (`work-thumbnails` Decision 2). It is+ /// the schema's only `@Attribute`, and it is carried across verbatim+ /// here for the reason this whole file exists — a snapshot whose stored+ /// shape differs from the recorded one by so much as an option makes a+ /// V14-recorded store refuse to open.+ @Attribute(.externalStorage)+ public var thumbnailData: Data?+ public var thumbnailShapeRaw: String?+ public var thumbnailDigest: String?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var genericNotesExtractionFingerprint: String?+ @Relationship(deleteRule: .nullify, inverse: \Entry.work)+ public var entries: [Entry]?+ @Relationship(deleteRule: .nullify, inverse: \Character.work)+ public var characters: [Character]?+ @Relationship(deleteRule: .nullify, inverse: \CharacterSuppression.work)+ public var characterSuppressions: [CharacterSuppression]?+ @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.work)+ public var siteMemberships: [WorkSiteMembership]? = []++ public init() {}+ }++ @Model+ public final class Site {+ public var hostname: String = ""+ public var displayName: String = ""+ public var modeRaw: String = SiteMode.untaught.rawValue+ @Relationship(deleteRule: .cascade, inverse: \TitlePattern.site)+ public var patterns: [TitlePattern]?+ @Relationship(deleteRule: .cascade, inverse: \URLRulePattern.site)+ public var urlRules: [URLRulePattern]?+ /// Inverse of `Entry.site`, present only because CloudKit requires every+ /// relationship to have one. Internal for the same reason the live class+ /// keeps it internal (Q17): traversing it faults every Entry for a+ /// hostname.+ @Relationship(deleteRule: .nullify, inverse: \Entry.site)+ var entries: [Entry]?+ /// Inverse of `WorkSiteMembership.site`. Same reasoning again.+ @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.site)+ var workMemberships: [WorkSiteMembership]?++ public init() {}+ }++ @Model+ public final class TitlePattern {+ public var id: UUID = UUID()+ public var version: Int = 1+ public var isActive: Bool = false+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var definitionData: Data?+ public var site: Site?++ public init() {}+ }++ @Model+ public final class URLRulePattern {+ public var id: UUID = UUID()+ public var version: Int = 1+ public var isCurrent: Bool = false+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var originRaw: String = URLRuleOrigin.readerTaught.rawValue+ public var definitionData: Data = Data()+ public var site: Site?++ public init() {}+ }++ @Model+ public final class WorkTypeEntity {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = WorkTypeState.active.rawValue+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+ }++ @Model+ public final class Character {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameKey: String = ""+ public var aliases: [String] = []+ public var note: String = ""+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var work: Work?++ public init() {}+ }++ @Model+ public final class CharacterSuppression {+ public var id: UUID = UUID()+ public var work: Work?+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ public var sourceKindRaw: String?+ public var sourceEntryID: UUID?+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+ }++ @Model+ public final class WorkSiteMembership {+ public var id: UUID = UUID()+ public var hostname: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var urlIdentity: String?+ public var urlIdentityStateRaw: String = WorkURLIdentityState.none.rawValue+ public var urlIdentityRuleID: UUID?+ public var workURLString: String?+ public var workID: UUID?+ public var work: Work?+ public var site: Site?++ public init() {}+ }++ @Model+ public final class WorkDistinctPair {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ public var recordedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+ }++ @Model+ public final class Series {+ public var id: UUID = UUID()+ public var name: String = ""+ public var notes: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+ }++ @Model+ public final class WorkLink {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ public var linkType: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+ }++ /// V12's three additions. `stateRaw` defaults to the **literal** `"active"`+ /// rather than to `CreatorState.active.rawValue`, which is why neither of+ /// the two new enums appears in the header's frozen-spelling list.+ @Model+ public final class Creator {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var notes: String = ""+ public var notesModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+ }++ @Model+ public final class CreatorRole {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var position: Int = 0+ public var positionModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+ }++ @Model+ public final class WorkCredit {+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var creatorID: UUID = UUID()+ public var roleIDs: [String] = []+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+ }++ /// V13's two additions. Both name their work by **UUID column** rather than+ /// by relationship, which is why neither declares a `@Relationship` at all,+ /// and both enum columns default to the *shared* suppression enums already+ /// frozen through `CharacterSuppression` above — so V13 brought no new+ /// frozen spelling into this file either.+ @Model+ public final class Place {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameKey: String = ""+ public var aliases: [String] = []+ public var note: String = ""+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var workID: UUID = UUID()++ public init() {}+ }++ @Model+ public final class PlaceSuppression {+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ public var sourceKindRaw: String?+ public var sourceEntryID: UUID?+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init() {} } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17.swiftnew file mode 100644index 00000000..2a3c4ccd--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17.swift@@ -0,0 +1,29 @@+import Foundation+import SwiftData++/// The live V17 schema. Its stored models are in `Models.swift`.+/// V17 adds only two optional Data columns to Work. Existing V16 rows migrate+/// with nil values; no table, relationship, or existing column changes.+public enum AsterismSchemaV17: VersionedSchema {+ public static let versionIdentifier = Schema.Version(17, 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]+ }+}++/// The V16 → V17 migration adds two optional Work blobs with no data pass.+public enum AsterismV17MigrationPlan: SchemaMigrationPlan {+ public static var schemas: [any VersionedSchema.Type] {+ [AsterismSchemaV16.self, AsterismSchemaV17.self]+ }++ public static var stages: [MigrationStage] {+ [.lightweight(fromVersion: AsterismSchemaV16.self, toVersion: AsterismSchemaV17.self)]+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swiftindex 6e4d8a4b..831065ec 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift@@ -15,14 +15,14 @@ private let exportLogger = Logger(subsystem: "AsterismCore", category: "BackupEx /// the Work mapper, plus the identity groups it needs. internal struct ArchiveCommonProjection { let groups: BackupGroupProjection.Projection- let entries: [BackupV15Entry]- let sites: [BackupV15Site]- let titlePatterns: [BackupV15TitlePattern]- let urlRules: [BackupV15URLRule]+ let entries: [BackupV16Entry]+ let sites: [BackupV16Site]+ let titlePatterns: [BackupV16TitlePattern]+ let urlRules: [BackupV16URLRule] /// One record per Work and hostname (Req 9.1), enumerated whole rather than /// works→children (Q17): a membership whose Work has not arrived exports /// naming the Work it belongs to instead of vanishing from the backup.- let memberships: [BackupV15Membership]+ let memberships: [BackupV16Membership] } /// Every Entry row's citations, decoded **once** for the whole projection.@@ -129,7 +129,7 @@ extension LibraryRepository { var additionalPatterns: [String: [TitlePattern]] = [:] for pattern in archivablePatterns where pattern.site == nil { guard let hostname = citers[pattern.id] else {- throw BackupV15ExportError.referencesStillArriving(+ throw BackupV16ExportError.referencesStillArriving( detail: "title rule \(pattern.id) has no site and no entry naming one") } additionalPatterns[hostname, default: []].append(pattern)@@ -137,7 +137,7 @@ extension LibraryRepository { var additionalURLRules: [String: [URLRulePattern]] = [:] for rule in archivableURLRules where rule.site == nil { guard let hostname = citers[rule.id] else {- throw BackupV15ExportError.referencesStillArriving(+ throw BackupV16ExportError.referencesStillArriving( detail: "URL rule \(rule.id) has no site and no record naming one") } additionalURLRules[hostname, default: []].append(rule)@@ -164,25 +164,25 @@ extension LibraryRepository { ruleMembership: .oneRowPerIdentityGroup) try requireProjectedTuplesRepresentable(projected) - var wireSites: [BackupV15Site] = []- var wirePatterns: [BackupV15TitlePattern] = []- var wireRules: [BackupV15URLRule] = []+ var wireSites: [BackupV16Site] = []+ var wirePatterns: [BackupV16TitlePattern] = []+ var wireRules: [BackupV16URLRule] = [] for site in projected {- wireSites.append(mapV15SiteRecord(site))+ wireSites.append(mapV16SiteRecord(site)) for projectedPattern in site.patterns where !omittedTitlePatternIDs.contains(projectedPattern.pattern.id) { wirePatterns.append(- try mapV15TitlePatternRecord(projectedPattern, hostname: site.hostname))+ try mapV16TitlePatternRecord(projectedPattern, hostname: site.hostname)) } for projectedRule in site.urlRules where !omittedURLRuleIDs.contains(projectedRule.rule.id) {- wireRules.append(try mapV15URLRuleRecord(projectedRule, hostname: site.hostname))+ wireRules.append(try mapV16URLRuleRecord(projectedRule, hostname: site.hostname)) } } return ArchiveCommonProjection( groups: groups,- entries: try groups.entries.map { try mapV15EntryRecord($0, citations: citations) },+ entries: try groups.entries.map { try mapV16EntryRecord($0, citations: citations) }, sites: wireSites.sorted { $0.hostname < $1.hostname }, titlePatterns: wirePatterns.sorted { $0.id.uuidString < $1.id.uuidString }, urlRules: wireRules.sorted { $0.id.uuidString < $1.id.uuidString },@@ -225,12 +225,26 @@ extension LibraryRepository { // than reached by a mapper that would throw a raw `DecodingError`. do { _ = try citations.value(of: entry) } catch {- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: record, field: "citations", value: String(describing: error)) } } for work in works { let record = "Work \(work.id)"+ if let data = work.catchUpConfirmationData {+ do { _ = try JSONBlob.decode(CatchUpConfirmation.self, from: data) }+ catch {+ throw BackupV16ExportError.unrepresentableValue(+ record: record, field: "catch-up confirmation", value: String(describing: error))+ }+ }+ if let data = work.lastChapterOverrideData {+ do { _ = try JSONBlob.decode(LastChapterOverride.self, from: data) }+ catch {+ throw BackupV16ExportError.unrepresentableValue(+ record: record, field: "last chapter override", value: String(describing: error))+ }+ } try require(TitleProvenance(rawValue: work.titleProvenanceRaw), record, "title provenance", work.titleProvenanceRaw) // Req 8.3. Both accessors read through `ToleratedEnum` so the app@@ -252,22 +266,22 @@ extension LibraryRepository { case (nil, nil): break case (let id?, nil):- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: record, field: "series membership", value: "series \(id) with no position") case (nil, let position?):- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: record, field: "series membership", value: "position \(position) with no series") case (_?, let position?): guard position.isFinite else {- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: record, field: "series position", value: String(position)) } // Q15: at most one fraction digit. Rounding here would move a // reader's value inside their own backup. guard position == SeriesPosition.rounded(position) else {- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: record, field: "series position", value: String(position)) } }@@ -275,7 +289,7 @@ extension LibraryRepository { // one refusal of this generation that is not: the cover the file // carries is chosen over the whole identity group rather than off // one row, so the row this loop is holding may not be the row the- // archive exports. It is refused in `mapV15WorkRecord`, against+ // archive exports. It is refused in `mapV16WorkRecord`, against // exactly the bytes the record takes (Q79). // // `update-schedule` Req 8.3, on the statuses' terms: the accessor@@ -315,7 +329,7 @@ extension LibraryRepository { // `formRaw` that no longer exists. do { _ = try pattern.storedDefinition } catch {- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: record, field: "definition", value: String(describing: error)) } }@@ -353,7 +367,7 @@ extension LibraryRepository { var omitted: Set<UUID> = [] for (id, rule) in unreadable.sorted(by: { $0.key.uuidString < $1.key.uuidString }) { guard !cited.contains(id) else {- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: "URL rule \(id)", field: "definition", value: "\(rule.definitionData.count) bytes that do not decode") }@@ -404,7 +418,7 @@ extension LibraryRepository { var omitted: Set<UUID> = [] for (id, pattern) in unreadable.sorted(by: { $0.key.uuidString < $1.key.uuidString }) { guard !pattern.isActive, !cited.contains(id) else {- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: "Title rule \(id)", field: "definition", value: pattern.definitionData.map { "\($0.count) bytes that do not decode" } ?? "no stored definition")@@ -460,7 +474,7 @@ extension LibraryRepository { _ value: Value?, _ record: String, _ field: String, _ raw: String ) throws { guard value == nil else { return }- throw BackupV15ExportError.unrepresentableValue(record: record, field: field, value: raw)+ throw BackupV16ExportError.unrepresentableValue(record: record, field: field, value: raw) } /// Req 3.7's third face: a hostname whose *projected* tuple the archive@@ -485,7 +499,7 @@ extension LibraryRepository { switch site.mode { case .taught: guard activePatterns != 1 else { continue }- throw BackupV15ExportError.referencesStillArriving(+ throw BackupV16ExportError.referencesStillArriving( detail: "site \(site.hostname) is taught, and the one active title rule " + "that state needs is not in the library") case .untaught:@@ -493,7 +507,7 @@ extension LibraryRepository { $0.rule.origin == .importedV2 && !$0.isCurrent } guard !site.patterns.isEmpty || currentRules > 0 || !historyOnly else { continue }- throw BackupV15ExportError.referencesStillArriving(+ throw BackupV16ExportError.referencesStillArriving( detail: "site \(site.hostname) is untaught while still holding rules, " + "so the teaching that owns them has not arrived") }@@ -514,10 +528,10 @@ extension LibraryRepository { /// problem surfacing as a broken file, which is exactly what this gate /// exists to say first. internal static func requireCitationsResolve(- entries: [BackupV15Entry],- memberships: [BackupV15Membership],- titlePatterns: [BackupV15TitlePattern],- urlRules: [BackupV15URLRule]+ entries: [BackupV16Entry],+ memberships: [BackupV16Membership],+ titlePatterns: [BackupV16TitlePattern],+ urlRules: [BackupV16URLRule] ) throws { let rulesByID = Dictionary(urlRules.map { ($0.id, $0) }, uniquingKeysWith: { lhs, _ in lhs }) let patternHostnames = Dictionary(@@ -557,14 +571,14 @@ extension LibraryRepository { private static func crossSiteCitation( _ record: String, _ field: String, taughtFor hostname: String- ) -> BackupV15ExportError {+ ) -> BackupV16ExportError { .referencesStillArriving( detail: "\(record) names \(field), which is taught for \(hostname)") } private static func missingCitation( _ record: String, _ field: String- ) -> BackupV15ExportError {+ ) -> BackupV16ExportError { .referencesStillArriving( detail: "\(record) names \(field), which the library does not hold") }@@ -611,9 +625,9 @@ extension LibraryRepository { /// a citation of a rule the projection renumbered was archived at the /// version the archive actually held (Decision 7). A citation is a UUID /// (T-2281) and nothing renumbers, so the map and the parameter are gone.- internal static func mapV15EntryRecord(+ internal static func mapV16EntryRecord( _ group: EntryGroup, citations cache: EntryCitationsCache- ) throws -> BackupV15Entry {+ ) throws -> BackupV16Entry { let snap = try snapshot(group) let entry = group.representative let carrier = group.carrier@@ -623,7 +637,7 @@ extension LibraryRepository { citations.chapterTitle = carried.chapterTitle citations.workAssignment = carried.workAssignment }- return BackupV15Entry(+ return BackupV16Entry( id: snap.id, captureTitle: snap.captureTitle, captureTitleSource: snap.captureTitleSource,@@ -703,32 +717,32 @@ extension LibraryRepository { guard let raw = group.carrier.thumbnailShapeRaw else { return nil } let titled = "Work “\(group.carrier.displayTitle)”" guard let shape = ThumbnailShape(rawValue: raw) else {- throw BackupV15ExportError.unrepresentableValue(- record: titled, field: BackupV15ExportError.thumbnailField, value: raw)+ throw BackupV16ExportError.unrepresentableValue(+ record: titled, field: BackupV16ExportError.thumbnailField, value: raw) } guard let identity = group.carrier.thumbnailIdentity, let bytes = GroupOrdering.thumbnailBytes(forDigest: identity.digest, in: group.rows) else { return nil } guard ThumbnailCodec.validate(bytes, shape: shape) else {- throw BackupV15ExportError.unrepresentableValue(- record: titled, field: BackupV15ExportError.thumbnailField,+ throw BackupV16ExportError.unrepresentableValue(+ record: titled, field: BackupV16ExportError.thumbnailField, value: "\(bytes.count) bytes that are not a \(raw) cover") } return bytes } - internal static func mapV15WorkRecord(+ internal static func mapV16WorkRecord( _ group: WorkGroup, canonicalWorkIDs: [UUID: UUID], types: WorkTypeDirectory- ) throws -> BackupV15Work {+ ) throws -> BackupV16Work { let snap = try snapshot( group, canonicalWorkIDs: canonicalWorkIDs, types: types, series: .empty, // An **empty** credit index for the empty directory's reason: this // mapper reads the `Work` record's own fields, and a credit is a // record of its own that the archive projects beside them // (`work-creators` Decision 6). Folding the whole credit table per- // exported work to fill a field no `BackupV15Work` carries is a read+ // exported work to fill a field no `BackupV16Work` carries is a read // this path skips. credits: .empty) let thumbnailBytes = try requireRepresentableCover(group)@@ -742,7 +756,7 @@ extension LibraryRepository { case .configured(let id): (workTypeID, typeName) = (id, types.resolve(id)?.name) }- return BackupV15Work(+ return BackupV16Work( id: snap.id, displayTitle: snap.displayTitle, lastParsedTitle: snap.lastParsedTitle,@@ -795,7 +809,20 @@ extension LibraryRepository { // spelling travels verbatim; `requireRepresentableCover` above has // already refused one this build cannot name. thumbnailShape: thumbnailShapeRaw,- thumbnail: thumbnailBytes+ thumbnail: thumbnailBytes,+ latestReleasedChapter: snap.catchUp.latest,+ latestConfirmedAt: snap.catchUp.confirmation.map {+ MillisecondInstant.date(fromMilliseconds: $0.confirmedAtMilliseconds)+ },+ countsUpOnReleaseDays: snap.catchUp.countsUp,+ latestIsEstimate: snap.catchUp.confirmation?.isEstimate ?? false,+ lastChapterOverride: {+ if case .value(let number, _) = snap.catchUp.override { return number }+ return nil+ }(),+ lastChapterOverrideAt: snap.catchUp.override.map {+ MillisecondInstant.date(fromMilliseconds: $0.atMilliseconds)+ } ) } @@ -813,7 +840,7 @@ extension LibraryRepository { /// there. private static func mapMembershipRecords( _ rows: [WorkSiteMembership]- ) -> [BackupV15Membership] {+ ) -> [BackupV16Membership] { var byKey: [MembershipReconciler.Key: [WorkSiteMembership]] = [:] var unattributed: [WorkSiteMembership] = [] for row in rows {@@ -824,8 +851,8 @@ extension LibraryRepository { byKey[MembershipReconciler.Key(workID: workID, hostname: row.hostname), default: []] .append(row) }- func record(_ row: WorkSiteMembership, workURLString: String?) -> BackupV15Membership {- BackupV15Membership(+ func record(_ row: WorkSiteMembership, workURLString: String?) -> BackupV16Membership {+ BackupV16Membership( id: row.id, workID: row.resolvedWorkID, hostname: row.hostname, createdAt: row.createdAt, urlIdentity: row.urlIdentity, urlIdentityState: row.urlIdentityState,@@ -840,7 +867,7 @@ extension LibraryRepository { // [4.2](../../../../specs/wrong-host-work-url-heal/requirements.md#42) // cannot survive. Nothing is written back: the fold returns the value // and the record carries it (Q54).- var records: [BackupV15Membership] = []+ var records: [BackupV16Membership] = [] for rows in byKey.values { let ordered = MembershipReconciler.survivorFirst(rows) guard let keeper = ordered.first else { continue }@@ -878,7 +905,7 @@ extension LibraryRepository { /// clauses are this projection's own: the directory's tie-break is the /// identifier, which two rows of one series share, and a tie the fetch order /// broke would put two devices' archives one byte apart.- internal static func projectSeries(context: ModelContext) throws -> [BackupV15Series] {+ internal static func projectSeries(context: ModelContext) throws -> [BackupV16Series] { var byID: [UUID: Series] = [:] for row in try context.fetch(FetchDescriptor<Series>()) { guard let held = byID[row.id] else {@@ -889,7 +916,7 @@ extension LibraryRepository { } return byID.values .map {- BackupV15Series(+ BackupV16Series( id: $0.id, name: $0.name, notes: $0.notes, createdAt: $0.createdAt, modifiedAt: $0.modifiedAt) }@@ -911,7 +938,7 @@ extension LibraryRepository { /// a self-naming pair is — Req 6.1 forbids a link from a work to itself, so /// such a row is not a link a reader can have meant, and `dedupeLinks` /// deletes it too.- internal static func projectLinks(context: ModelContext) throws -> [BackupV15Link] {+ internal static func projectLinks(context: ModelContext) throws -> [BackupV16Link] { var byKey: [WorkPairKey: [WorkLink]] = [:] for row in try context.fetch(FetchDescriptor<WorkLink>()) where row.lowerWorkID != row.higherWorkID {@@ -921,7 +948,7 @@ extension LibraryRepository { guard let survivor = MembershipReconciler.survivorFirstLinks(rows).first else { return nil }- return BackupV15Link(+ return BackupV16Link( id: survivor.id, lowerWorkID: key.lower, higherWorkID: key.higher, linkType: survivor.linkType, createdAt: survivor.createdAt, modifiedAt: survivor.modifiedAt)@@ -953,7 +980,7 @@ extension LibraryRepository { /// the same number the next local pass would. internal static func projectCredits( context: ModelContext, creators: CreatorDirectory- ) throws -> [BackupV15Credit] {+ ) throws -> [BackupV16Credit] { var byKey: [CreditReconciler.Key: [WorkCredit]] = [:] for row in try context.fetch(FetchDescriptor<WorkCredit>()) { let key = CreditReconciler.Key(@@ -963,7 +990,7 @@ extension LibraryRepository { return byKey.compactMap { _, rows in let ordered = WorkCreditSupport.survivorFirstCredits(rows) guard let head = ordered.first else { return nil }- return BackupV15Credit(+ return BackupV16Credit( id: head.id, workID: head.workID, creatorID: head.creatorID, roleIDs: WorkCreditSupport.roleIDs(ordered.flatMap(\.roleIDs)), createdAt: head.createdAt,@@ -974,7 +1001,7 @@ extension LibraryRepository { internal static func projectDistinctPairs( context: ModelContext- ) throws -> [BackupV15DistinctPair] {+ ) throws -> [BackupV16DistinctPair] { var byKey: [WorkPairKey: [WorkDistinctPair]] = [:] for row in try context.fetch(FetchDescriptor<WorkDistinctPair>()) where row.lowerWorkID != row.higherWorkID {@@ -986,7 +1013,7 @@ extension LibraryRepository { guard let survivor = MembershipReconciler.survivorFirstPairs(rows).first else { return nil }- return BackupV15DistinctPair(+ return BackupV16DistinctPair( id: survivor.id, lowerWorkID: key.lower, higherWorkID: key.higher, recordedAt: survivor.recordedAt) }@@ -996,20 +1023,20 @@ extension LibraryRepository { /// The wire Site for a hostname: exactly one, whatever the store holds /// (Q38). It names no children (Req 9.3) — the union still decides which /// rules are archived, and each of them names this hostname back.- internal static func mapV15SiteRecord(+ internal static func mapV16SiteRecord( _ projected: SiteUnionProjection.ProjectedSite- ) -> BackupV15Site {- BackupV15Site(+ ) -> BackupV16Site {+ BackupV16Site( hostname: projected.hostname, displayName: projected.displayName, mode: projected.mode ) } - internal static func mapV15TitlePatternRecord(+ internal static func mapV16TitlePatternRecord( _ projected: SiteUnionProjection.ProjectedTitlePattern, hostname: String- ) throws -> BackupV15TitlePattern {- BackupV15TitlePattern(+ ) throws -> BackupV16TitlePattern {+ BackupV16TitlePattern( id: projected.pattern.id, siteHostname: hostname, // The version stored on the row the per-UUID reduction kept, without@@ -1024,17 +1051,17 @@ extension LibraryRepository { /// `throws` because the definition does (Req 4.5): the mapper needs a typed /// `URLRuleDefinition` for every row it writes, so a row that will not /// decode cannot be archived at all.- internal static func mapV15URLRuleRecord(+ internal static func mapV16URLRuleRecord( _ projected: SiteUnionProjection.ProjectedURLRule, hostname: String- ) throws -> BackupV15URLRule {+ ) throws -> BackupV16URLRule { let definition: URLRuleDefinition do { definition = try projected.rule.definition } catch {- throw BackupV15ExportError.unrepresentableValue(+ throw BackupV16ExportError.unrepresentableValue( record: "URL rule \(projected.rule.id)", field: "definition", value: "\(projected.rule.definitionData.count) bytes that do not decode") }- return BackupV15URLRule(+ return BackupV16URLRule( id: projected.rule.id, version: projected.rule.version, isCurrent: projected.isCurrent,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swiftindex 9871da2b..ccec9f43 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift@@ -24,18 +24,18 @@ internal enum BackupArchiveReferenceChecks { /// refusal — the one message here that has to say which archive format it /// is talking about. static func validate(- entries: [BackupV15Entry],- works: [BackupV15Work],- memberships: [BackupV15Membership],- distinctPairs: [BackupV15DistinctPair],- sites: [BackupV15Site],- titlePatterns: [BackupV15TitlePattern],- urlRules: [BackupV15URLRule],- series: [BackupV15Series],- links: [BackupV15Link],- creators: [BackupV15Creator],- creatorRoles: [BackupV15CreatorRole],- credits: [BackupV15Credit],+ entries: [BackupV16Entry],+ works: [BackupV16Work],+ memberships: [BackupV16Membership],+ distinctPairs: [BackupV16DistinctPair],+ sites: [BackupV16Site],+ titlePatterns: [BackupV16TitlePattern],+ urlRules: [BackupV16URLRule],+ series: [BackupV16Series],+ links: [BackupV16Link],+ creators: [BackupV16Creator],+ creatorRoles: [BackupV16CreatorRole],+ credits: [BackupV16Credit], formatLabel: String ) throws { let siteHostnames = Set(sites.map(\.hostname))@@ -278,6 +278,14 @@ internal enum BackupArchiveReferenceChecks { } for work in works {+ for (field, number) in [+ ("latest released chapter", work.latestReleasedChapter),+ ("last chapter override", work.lastChapterOverride),+ ] {+ if let number, !(0...9_999).contains(number) {+ throw invalid("Work", work.id.uuidString, "\(field) must be from 0 to 9,999")+ }+ } // Both or neither (Req 13.5): a position without a series says where // in nothing, and a series without a position has no place in it. switch (work.seriesID, work.seriesPosition) {@@ -306,9 +314,9 @@ internal enum BackupArchiveReferenceChecks { // MARK: Site closed tuple (supersedes M3 8.1) private static func validateSiteTuple(- _ site: BackupV15Site,- patterns: [BackupV15TitlePattern],- rules: [BackupV15URLRule]+ _ site: BackupV16Site,+ patterns: [BackupV16TitlePattern],+ rules: [BackupV16URLRule] ) throws { let id = site.hostname guard !M2Unicode.isBlank(site.hostname) else { throw invalid("Site", id, "hostname is blank") }@@ -369,9 +377,9 @@ internal enum BackupArchiveReferenceChecks { /// (Req 9.5, Q22); its own tuple is still checked, because an orphan is a /// row like any other. private static func validateMembership(- _ membership: BackupV15Membership,+ _ membership: BackupV16Membership, siteHostnames: Set<String>,- rulesByID: [UUID: BackupV15URLRule]+ rulesByID: [UUID: BackupV16URLRule] ) throws { let id = membership.id.uuidString guard !M2Unicode.isBlank(membership.hostname) else {@@ -400,12 +408,12 @@ internal enum BackupArchiveReferenceChecks { // MARK: Entry (Entry-state enumeration, supersedes M3 8.12) private static func validateEntry(- _ entry: BackupV15Entry,+ _ entry: BackupV16Entry, siteHostnames: Set<String>, workIDs: Set<UUID>, hostnamesByWork: [UUID: Set<String>],- patternsByID: [UUID: BackupV15TitlePattern],- rulesByID: [UUID: BackupV15URLRule]+ patternsByID: [UUID: BackupV16TitlePattern],+ rulesByID: [UUID: BackupV16URLRule] ) throws { let id = entry.id.uuidString guard siteHostnames.contains(entry.hostname) else {@@ -486,15 +494,15 @@ internal enum BackupArchiveReferenceChecks { /// dangling citation is an unresolved reference — so the predicate is stated /// once and each caller names its own failure. private static func resolvesSameSite(- _ cited: CitedRule, entry: BackupV15Entry, rulesByID: [UUID: BackupV15URLRule]+ _ cited: CitedRule, entry: BackupV16Entry, rulesByID: [UUID: BackupV16URLRule] ) -> Bool { rulesByID[cited.id]?.siteHostname == entry.hostname } private static func requireSameSiteRule( _ cited: CitedRule,- entry: BackupV15Entry,- rulesByID: [UUID: BackupV15URLRule]+ entry: BackupV16Entry,+ rulesByID: [UUID: BackupV16URLRule] ) throws { guard resolvesSameSite(cited, entry: entry, rulesByID: rulesByID) else { throw invalid(@@ -504,10 +512,10 @@ internal enum BackupArchiveReferenceChecks { } private static func validateEntryRuleReference(- _ entry: BackupV15Entry,+ _ entry: BackupV16Entry, field: String, cited: CitedRule?,- rulesByID: [UUID: BackupV15URLRule]+ rulesByID: [UUID: BackupV16URLRule] ) throws { guard let cited else { return } guard resolvesSameSite(cited, entry: entry, rulesByID: rulesByID) else {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swiftindex e638c784..3a8d3287 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swift@@ -1,7 +1,7 @@ import Foundation /// The file a completed backup export produced, handed to the share sheet and-/// cleaned up afterwards. `BackupV15Exporter` is the only producer.+/// cleaned up afterwards. `BackupV16Exporter` is the only producer. public struct BackupExportResult: Sendable { public let fileURL: URL
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swiftindex 56806ed6..b1ad158c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift@@ -76,7 +76,7 @@ enum BackupGroupProjection { let places: [RecordGroup<Place>] } - /// - Throws: `BackupV15ExportError.tornGroups` when the store holds a torn+ /// - Throws: `BackupV16ExportError.tornGroups` when the store holds a torn /// group — the biconditional of Req 8.1, since nothing else here refuses. /// - Parameter distinctPairs: the reader's recorded "not the same work" /// dismissals (Req 5.6). **Not defaulted**: an export that cannot see them@@ -112,7 +112,7 @@ enum BackupGroupProjection { let tornPlaces = placeGroups.values.filter(\.isTorn) guard tornEntries.isEmpty, tornWorks.isEmpty, tornCharacters.isEmpty, tornPlaces.isEmpty else {- throw BackupV15ExportError.tornGroups(+ throw BackupV16ExportError.tornGroups( tornGroupsPayload( tornEntries: tornEntries, tornWorks: tornWorks, tornRecordCount: tornCharacters.count + tornPlaces.count,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swiftindex 0be29954..6f588658 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swift@@ -34,8 +34,8 @@ extension LibraryRepository { /// of which are the reader acting *now* and have to assert over what is /// already there. internal static func mergeImportedCreatorDirectories(- creators: [BackupV15Creator],- creatorRoles: [BackupV15CreatorRole],+ creators: [BackupV16Creator],+ creatorRoles: [BackupV16CreatorRole], importedAt: Date, context: ModelContext, saveStrategy: any RepositorySaveStrategy@@ -72,7 +72,7 @@ extension LibraryRepository { /// - Returns: whether anything was written. private static func mergeImportedCreators(- _ records: [BackupV15Creator], context: ModelContext+ _ records: [BackupV16Creator], context: ModelContext ) throws -> Bool { guard !records.isEmpty else { return false } let rows = try context.fetch(FetchDescriptor<Creator>())@@ -149,7 +149,7 @@ extension LibraryRepository { /// that is absent or itself merged; anything the checks tolerate and this /// does not answer for leaves the local record as it stands. private static func answersForACreator(- _ survivor: UUID, local: CreatorDirectory, archive: [UUID: BackupV15Creator]+ _ survivor: UUID, local: CreatorDirectory, archive: [UUID: BackupV16Creator] ) -> Bool { if let record = archive[survivor], ToleratedEnum.read(record.stateRaw, default: CreatorState.active) != .merged@@ -172,7 +172,7 @@ extension LibraryRepository { /// sides follows the per-field rule either way, so an order the archive /// recorded later than the local one still wins. private static func mergeImportedCreatorRoles(- _ records: [BackupV15CreatorRole], importedAt: Date, context: ModelContext+ _ records: [BackupV16CreatorRole], importedAt: Date, context: ModelContext ) throws -> Bool { guard !records.isEmpty else { return false } let rows = try context.fetch(FetchDescriptor<CreatorRole>())@@ -257,7 +257,7 @@ extension LibraryRepository { /// `answersForACreator` over the role table. private static func answersForARole(- _ survivor: UUID, local: CreatorRoleDirectory, archive: [UUID: BackupV15CreatorRole]+ _ survivor: UUID, local: CreatorRoleDirectory, archive: [UUID: BackupV16CreatorRole] ) -> Bool { if let record = archive[survivor], ToleratedEnum.read(record.stateRaw, default: CreatorRoleState.active) != .merged
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swiftindex fca71690..64caca2f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift@@ -61,22 +61,22 @@ internal protocol ArchivedSuppression { var actionAt: Date { get } } -extension BackupV15Character: ArchivedRecord {+extension BackupV16Character: ArchivedRecord { var recordID: UUID { id } var archivedWorkID: UUID? { workID } } -extension BackupV15Place: ArchivedRecord {+extension BackupV16Place: ArchivedRecord { var recordID: UUID { id } var archivedWorkID: UUID? { workID } } -extension BackupV15Suppression: ArchivedSuppression {+extension BackupV16Suppression: ArchivedSuppression { var recordID: UUID { id } var archivedWorkID: UUID? { workID } } -extension BackupV15PlaceSuppression: ArchivedSuppression {+extension BackupV16PlaceSuppression: ArchivedSuppression { var recordID: UUID { id } var archivedWorkID: UUID? { workID } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swiftindex df1689f6..8546abf5 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swift@@ -31,8 +31,8 @@ extension LibraryRepository { /// restore of an entry this library already held. That one write is the /// reader acting now, and it has to assert over a removal older than it. internal static func mergeImportedWorkTypes(- workTypes: [BackupV15WorkType],- works: [BackupV15Work],+ workTypes: [BackupV16WorkType],+ works: [BackupV16Work], exportedAt: Date, importedAt: Date, context: ModelContext,@@ -171,7 +171,7 @@ extension LibraryRepository { /// Returned in identifier order, so an interrupted import resumes into the /// same shape on any device. private static func archivedTypeIdentities(- _ records: [BackupV15WorkType]+ _ records: [BackupV16WorkType] ) -> [ArchivedTypeIdentity] { let directory = WorkTypeDirectory( rows: records.map {@@ -266,7 +266,7 @@ extension LibraryRepository { /// A citation with no snapshot is deliberately absent: it stays on the work /// as unresolved rather than being invented a name (Q24). private static func unresolvedTypeCitations(- _ works: [BackupV15Work], in local: WorkTypeDirectory+ _ works: [BackupV16Work], in local: WorkTypeDirectory ) -> [ArchivedTypeCitation] { var seen: Set<UUID> = [] var citations: [ArchivedTypeCitation] = []
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swiftindex 316e16ab..e1aadd6a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift@@ -11,47 +11,47 @@ import OSLog /// longer exist and every accessor answered the same arm three times. What /// remains is the payload's arrays, named. ///-/// This is `BackupV15Payload`'s content rather than the type itself: the wire+/// This is `BackupV16Payload`'s content rather than the type itself: the wire /// struct is a `Codable` frozen shape and the plan is what the commit reads, and /// keeping them separate is what lets a future generation arrive without the /// upsert learning its envelope. public struct BackupImportPayload: Sendable, Equatable {- public let entries: [BackupV15Entry]- public let works: [BackupV15Work]- public let sites: [BackupV15Site]- public let titlePatterns: [BackupV15TitlePattern]- public let urlRules: [BackupV15URLRule]- public let workTypes: [BackupV15WorkType]- public let memberships: [BackupV15Membership]- public let distinctPairs: [BackupV15DistinctPair]- public let characters: [BackupV15Character]- public let suppressions: [BackupV15Suppression]- public let places: [BackupV15Place]- public let placeSuppressions: [BackupV15PlaceSuppression]- public let series: [BackupV15Series]- public let links: [BackupV15Link]- public let creators: [BackupV15Creator]- public let creatorRoles: [BackupV15CreatorRole]- public let credits: [BackupV15Credit]+ public let entries: [BackupV16Entry]+ public let works: [BackupV16Work]+ public let sites: [BackupV16Site]+ public let titlePatterns: [BackupV16TitlePattern]+ public let urlRules: [BackupV16URLRule]+ public let workTypes: [BackupV16WorkType]+ public let memberships: [BackupV16Membership]+ public let distinctPairs: [BackupV16DistinctPair]+ public let characters: [BackupV16Character]+ public let suppressions: [BackupV16Suppression]+ public let places: [BackupV16Place]+ public let placeSuppressions: [BackupV16PlaceSuppression]+ public let series: [BackupV16Series]+ public let links: [BackupV16Link]+ public let creators: [BackupV16Creator]+ public let creatorRoles: [BackupV16CreatorRole]+ public let credits: [BackupV16Credit] public init(- entries: [BackupV15Entry],- works: [BackupV15Work],- sites: [BackupV15Site],- titlePatterns: [BackupV15TitlePattern],- urlRules: [BackupV15URLRule],- workTypes: [BackupV15WorkType] = [],- memberships: [BackupV15Membership] = [],- distinctPairs: [BackupV15DistinctPair] = [],- characters: [BackupV15Character] = [],- suppressions: [BackupV15Suppression] = [],- places: [BackupV15Place] = [],- placeSuppressions: [BackupV15PlaceSuppression] = [],- series: [BackupV15Series] = [],- links: [BackupV15Link] = [],- creators: [BackupV15Creator] = [],- creatorRoles: [BackupV15CreatorRole] = [],- credits: [BackupV15Credit] = []+ entries: [BackupV16Entry],+ works: [BackupV16Work],+ sites: [BackupV16Site],+ titlePatterns: [BackupV16TitlePattern],+ urlRules: [BackupV16URLRule],+ workTypes: [BackupV16WorkType] = [],+ memberships: [BackupV16Membership] = [],+ distinctPairs: [BackupV16DistinctPair] = [],+ characters: [BackupV16Character] = [],+ suppressions: [BackupV16Suppression] = [],+ places: [BackupV16Place] = [],+ placeSuppressions: [BackupV16PlaceSuppression] = [],+ series: [BackupV16Series] = [],+ links: [BackupV16Link] = [],+ creators: [BackupV16Creator] = [],+ creatorRoles: [BackupV16CreatorRole] = [],+ credits: [BackupV16Credit] = [] ) { self.entries = entries self.works = works@@ -83,7 +83,7 @@ public struct BackupImportPayload: Sendable, Equatable { self.credits = credits.map(\.normalized) } - public init(_ payload: BackupV15Payload) {+ public init(_ payload: BackupV16Payload) { self.init( entries: payload.entries, works: payload.works, sites: payload.sites, titlePatterns: payload.titlePatterns, urlRules: payload.urlRules,@@ -134,7 +134,7 @@ public struct BackupImportPlan: Sendable, Equatable { /// A plan over a wire payload, which is how every archive reaches one. public init(- metadata: BackupImportMetadata, payload: BackupV15Payload,+ metadata: BackupImportMetadata, payload: BackupV16Payload, counts: LibraryRecordCounts ) { self.init(@@ -252,7 +252,7 @@ public enum BackupImporter { /// constants, so the accepted pair moves with the generation rather than /// being restated here. private static let supportedVersions = (- format: BackupV15Document.formatVersion, schema: BackupV15Document.schemaVersion+ format: BackupV16Document.formatVersion, schema: BackupV16Document.schemaVersion ) // MARK: - Plan Dispatch (Req 5.1, 5.2, Decision 2)@@ -283,9 +283,9 @@ public enum BackupImporter { } private static func planFromArchive(_ data: Data) throws -> BackupImportPlan {- let document: BackupV15Document+ let document: BackupV16Document do {- document = try BackupV15Codec.decode(data)+ document = try BackupV16Codec.decode(data) } catch { throw BackupImportError.decodingFailed(reason: String(describing: error)) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swiftindex e1370b71..5009227f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swift@@ -1,7 +1,7 @@ import Foundation // Extracted from the retired `LegacyBackupV2Codec` when the 2/2 and 3/3 import-// paths were removed. Both helpers are used by the live `BackupV15Codec`: the+// paths were removed. Both helpers are used by the live `BackupV16Codec`: the // date formatter fixes the archive's timestamp encoding, and the duplicate-key // validator is what makes a decode strict rather than last-key-wins. //@@ -166,7 +166,7 @@ internal enum BackupArchiveDateFormatter { /// /// Load-bearing on the live decode path: it is the only thing standing between a /// two-`payload` archive and importing the wrong one, and it enforces-/// no-trailing-bytes. `BackupV15ArchiveTests` covers both properties by editing+/// no-trailing-bytes. `BackupV16ArchiveTests` covers both properties by editing /// encoded bytes directly. /// /// **The root keys come from here because this walk is already paying for
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV15Codec.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV16Codec.swiftsimilarity index 88%rename from Packages/AsterismCore/Sources/AsterismCore/BackupV15Codec.swiftrename to Packages/AsterismCore/Sources/AsterismCore/BackupV16Codec.swiftindex 2fecc082..b5b3a4df 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupV15Codec.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV16Codec.swift@@ -1,6 +1,6 @@ import Foundation -/// The strict 15/16 archive codec: canonical JSON, a SHA-256 checksum over the+/// The strict 16/17 archive codec: canonical JSON, a SHA-256 checksum over the /// payload bytes, entry/work counts, root-strict envelope validation, typed /// nested decode, and a reference validator over the shared record checks plus /// this generation's own rules.@@ -15,16 +15,16 @@ import Foundation /// /// The capability gate is pinned to the literal `"multi-site"`: the payload is /// frozen the moment it ships, and a later `AsterismCapabilities.current` must-/// not change what a 15/16 backup declares. 15/16 changes neither the store shape+/// not change what a 16/17 backup declares. 16/17 changes neither the store shape /// the gate names nor the rule-form set, so it keeps stamping it /// (`rule-citation-by-uuid` Q19).-public enum BackupV15Codec {- /// Pinned literally. 15/16 ships at the multi-site gate; a future gate flip+public enum BackupV16Codec {+ /// Pinned literally. 16/17 ships at the multi-site gate; a future gate flip /// cannot retroactively change what these files say. static let gate = "multi-site" /// The generation this codec speaks, as it appears in decode diagnostics.- static let label = "V15"+ static let label = "V16" // MARK: - Encode @@ -32,7 +32,7 @@ public enum BackupV15Codec { /// sorts after it. /// /// The payload is encoded once, for the checksum, and then spliced into the- /// envelope rather than encoded a second time as `BackupV15Document.payload`+ /// envelope rather than encoded a second time as `BackupV16Document.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.@@ -56,8 +56,8 @@ public enum BackupV15Codec { } public static func encode(- payload: BackupV15Payload,- metadata: BackupV15Metadata+ payload: BackupV16Payload,+ metadata: BackupV16Metadata ) throws -> Data { let encoder = BackupCanonicalJSON.encoder() @@ -66,10 +66,10 @@ public enum BackupV15Codec { let head = try encoder.encode(EnvelopeHead( appBuild: metadata.appBuild,- backupFormatVersion: BackupV15Document.formatVersion,+ backupFormatVersion: BackupV16Document.formatVersion, capabilityGate: Self.gate, checksum: checksum,- databaseSchemaVersion: BackupV15Document.schemaVersion,+ databaseSchemaVersion: BackupV16Document.schemaVersion, entryCount: payload.entries.count, exportedAt: metadata.exportedAt)) let tail = try encoder.encode(EnvelopeTail(workCount: payload.works.count))@@ -91,7 +91,7 @@ public enum BackupV15Codec { // MARK: - Decode - /// Decodes and validates a 15/16 document. Validates: envelope format/schema,+ /// Decodes and validates a 16/17 document. Validates: envelope format/schema, /// capability gate, duplicate keys, strict root shape, entry/work counts, /// payload checksum, and all references and tuples. ///@@ -101,21 +101,21 @@ public enum BackupV15Codec { /// /// The checksum step is also a refusal in its own right: it is taken over /// the bytes as they arrived and compared against a re-encoding of what- /// decoded, so a 15/16 file carrying a key this build does not write back —+ /// decoded, so a 16/17 file carrying a key this build does not write back — /// a citation `version`, the shape a build before T-2281 wrote — fails here /// rather than importing with the key silently dropped.- public static func decode(_ data: Data) throws -> BackupV15Document {+ public static func decode(_ data: Data) throws -> BackupV16Document { do { let rootKeys = try DuplicateJSONKeyValidator.validate(data) try BackupArchiveShapeValidator.validate(rootKeys: rootKeys) let document = try BackupCanonicalJSON.decoder()- .decode(BackupV15Document.self, from: data)+ .decode(BackupV16Document.self, from: data) - guard document.backupFormatVersion == BackupV15Document.formatVersion else {+ guard document.backupFormatVersion == BackupV16Document.formatVersion else { throw BackupCodecError.invalidFormatVersion(document.backupFormatVersion) }- guard document.databaseSchemaVersion == BackupV15Document.schemaVersion else {+ guard document.databaseSchemaVersion == BackupV16Document.schemaVersion else { throw BackupCodecError.invalidSchemaVersion(document.databaseSchemaVersion) } guard document.capabilityGate == Self.gate else {@@ -147,7 +147,7 @@ public enum BackupV15Codec { ) } - try BackupV15ReferenceValidator.validate(payload: document.payload)+ try BackupV16ReferenceValidator.validate(payload: document.payload) return document } catch let error as BackupCodecError { throw error }@@ -157,9 +157,9 @@ public enum BackupV15Codec { } } -// MARK: - V15 Metadata+// MARK: - V16 Metadata -public struct BackupV15Metadata: Sendable {+public struct BackupV16Metadata: Sendable { public let appBuild: String public let exportedAt: Date @@ -199,7 +199,7 @@ internal enum BackupArchiveShapeValidator { } } -// MARK: - V15 Reference Validator+// MARK: - V16 Reference Validator /// The shared record checks, the type-list rules, the two character arrays and /// the two place arrays.@@ -214,8 +214,8 @@ internal enum BackupArchiveShapeValidator { /// character or suppression, and a character or suppression naming a Work the /// file does not hold. The work reference is **optional, checked when present** /// — the `validateEntry` `workID` pattern — so an orphan passes.-internal enum BackupV15ReferenceValidator {- static func validate(payload: BackupV15Payload) throws {+internal enum BackupV16ReferenceValidator {+ static func validate(payload: BackupV16Payload) throws { do { try BackupArchiveReferenceChecks.validate( entries: payload.entries,@@ -230,7 +230,7 @@ internal enum BackupV15ReferenceValidator { creators: payload.creators, creatorRoles: payload.creatorRoles, credits: payload.credits,- formatLabel: BackupV15Codec.label)+ formatLabel: BackupV16Codec.label) } catch let issue as BackupArchiveReferenceIssue { throw BackupCodecError(issue) }@@ -238,7 +238,7 @@ internal enum BackupV15ReferenceValidator { let typeIDs = Set(payload.workTypes.map(\.id)) guard typeIDs.count == payload.workTypes.count else { throw BackupCodecError.invalidStateTuple(- type: "Payload", id: BackupV15Codec.label, reason: "duplicate work type ID")+ type: "Payload", id: BackupV16Codec.label, reason: "duplicate work type ID") } let workIDs = Set(payload.works.map(\.id))@@ -247,7 +247,7 @@ internal enum BackupV15ReferenceValidator { for character in payload.characters { guard characterIDs.insert(character.id).inserted else { throw BackupCodecError.invalidStateTuple(- type: "Payload", id: BackupV15Codec.label, reason: "duplicate Character ID")+ type: "Payload", id: BackupV16Codec.label, reason: "duplicate Character ID") } if let workID = character.workID, !workIDs.contains(workID) { throw BackupCodecError.unresolvedReference(@@ -259,7 +259,7 @@ internal enum BackupV15ReferenceValidator { for suppression in payload.suppressions { guard suppressionIDs.insert(suppression.id).inserted else { throw BackupCodecError.invalidStateTuple(- type: "Payload", id: BackupV15Codec.label, reason: "duplicate CharacterSuppression ID")+ type: "Payload", id: BackupV16Codec.label, reason: "duplicate CharacterSuppression ID") } if let workID = suppression.workID, !workIDs.contains(workID) { throw BackupCodecError.unresolvedReference(@@ -279,7 +279,7 @@ internal enum BackupV15ReferenceValidator { for place in payload.places { guard placeIDs.insert(place.id).inserted else { throw BackupCodecError.invalidStateTuple(- type: "Payload", id: BackupV15Codec.label, reason: "duplicate Place ID")+ type: "Payload", id: BackupV16Codec.label, reason: "duplicate Place ID") } } @@ -287,7 +287,7 @@ internal enum BackupV15ReferenceValidator { for suppression in payload.placeSuppressions { guard placeSuppressionIDs.insert(suppression.id).inserted else { throw BackupCodecError.invalidStateTuple(- type: "Payload", id: BackupV15Codec.label,+ type: "Payload", id: BackupV16Codec.label, reason: "duplicate PlaceSuppression ID") } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV15Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV16Exporter.swiftsimilarity index 85%rename from Packages/AsterismCore/Sources/AsterismCore/BackupV15Exporter.swiftrename to Packages/AsterismCore/Sources/AsterismCore/BackupV16Exporter.swiftindex 444f5b71..de3c99fd 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupV15Exporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV16Exporter.swift@@ -3,10 +3,10 @@ import SwiftData // MARK: - Snapshot Providing -/// Provides one coherent 15/16 payload under a shared lock. Isolated from+/// Provides one coherent 16/17 payload under a shared lock. Isolated from /// persistence so export can be unit-tested with injected snapshots.-public protocol BackupV15SnapshotProviding: Sendable {- func backupV15Snapshot() async throws -> BackupV15Payload+public protocol BackupV16SnapshotProviding: Sendable {+ func backupV16Snapshot() async throws -> BackupV16Payload } // MARK: - Export Errors@@ -24,7 +24,7 @@ public protocol BackupV15SnapshotProviding: Sendable { /// the reader wrote exactly as it covers a torn Entry or Work. What does *not* /// refuse is a fact whose citation dangles — `character-extraction` Decision 2 /// makes that a tolerated state.-public enum BackupV15ExportError: Error, Equatable, Sendable, CustomStringConvertible {+public enum BackupV16ExportError: Error, Equatable, Sendable, CustomStringConvertible { /// The store holds a **torn** identity group: one application UUID over rows /// that disagree about something the reader wrote. The archive keys records /// by UUID and cannot hold both variants, and silently dropping one is data@@ -85,8 +85,8 @@ public enum BackupV15ExportError: Error, Equatable, Sendable, CustomStringConver // MARK: - LibraryRepository Snapshot -extension LibraryRepository: BackupV15SnapshotProviding {- /// Provides a coherent 15/16 backup payload under a shared lock.+extension LibraryRepository: BackupV16SnapshotProviding {+ /// Provides a coherent 16/17 backup payload under a shared lock. /// /// **The quarantine and unresolved gates are gone** (Req 3.1 of /// `cloudkit-mirroring`). They refused a file at exactly the moment one is@@ -104,16 +104,16 @@ extension LibraryRepository: BackupV15SnapshotProviding { /// backup cannot mutate the library on the way out (Q38); the archive it /// produces is nonetheless the shape reconciliation settles on, which is what /// makes Req 3.5's round-trip hold.- public func backupV15Snapshot() async throws -> BackupV15Payload {- let outcome: Result<BackupV15Payload, BackupV15ExportError> =+ public func backupV16Snapshot() async throws -> BackupV16Payload {+ let outcome: Result<BackupV16Payload, BackupV16ExportError> = try await withLockedBackupContext { context in- do { return .success(try Self.projectV15Payload(context: context)) }- catch let error as BackupV15ExportError { return .failure(error) }+ do { return .success(try Self.projectV16Payload(context: context)) }+ catch let error as BackupV16ExportError { return .failure(error) } } return try outcome.get() } - /// The whole 15/16 snapshot, from a context. Static and pure so the projection+ /// The whole 16/17 snapshot, from a context. Static and pure so the projection /// can be exercised without an actor. /// /// **One projection pass.** `projectCommonArchiveRecords` already enumerated@@ -122,7 +122,7 @@ extension LibraryRepository: BackupV15SnapshotProviding { /// vanishing), already refused a torn group, and already sorted by UUID. /// Re-deriving any of it would be a second walk of the two largest tables and /// a second chance to describe two moments.- internal static func projectV15Payload(context: ModelContext) throws -> BackupV15Payload {+ internal static func projectV16Payload(context: ModelContext) throws -> BackupV16Payload { let common = try projectCommonArchiveRecords(context: context) // Req 7.2 and Q32: the **folded** list, one record per identity. Rows@@ -132,14 +132,14 @@ extension LibraryRepository: BackupV15SnapshotProviding { // devices holding the same rows write the same bytes. let directory = common.groups.types let workTypes = directory.identities.map {- BackupV15WorkType(+ BackupV16WorkType( id: $0.id, name: $0.name, stateRaw: $0.state.rawValue, canonicalID: $0.canonicalID, createdAt: $0.createdAt, modifiedAt: $0.modifiedAt) } let works = try common.groups.works.map {- try mapV15WorkRecord(+ try mapV16WorkRecord( $0, canonicalWorkIDs: common.groups.canonicalWorkIDs, types: directory) } @@ -153,20 +153,20 @@ extension LibraryRepository: BackupV15SnapshotProviding { titlePatterns: common.titlePatterns, urlRules: common.urlRules) - let characters = common.groups.characters.map(mapV15CharacterRecord)+ let characters = common.groups.characters.map(mapV16CharacterRecord) let suppressions = try context.fetch(FetchDescriptor<CharacterSuppression>())- .map(mapV15SuppressionRecord)+ .map(mapV16SuppressionRecord) .sorted { $0.id.uuidString < $1.id.uuidString } // `place-extraction` Req 5.1. The place groups the common projection // already formed — enumerated whole and already refused if torn — and // the suppression table read whole beside them, on the character arms' // terms exactly.- let places = common.groups.places.map(mapV15PlaceRecord)+ let places = common.groups.places.map(mapV16PlaceRecord) let placeSuppressions = try context.fetch(FetchDescriptor<PlaceSuppression>())- .map(mapV15PlaceSuppressionRecord)+ .map(mapV16PlaceSuppressionRecord) .sorted { $0.id.uuidString < $1.id.uuidString } // `work-creators` Req 9.1: the two directories folded, one record per@@ -182,7 +182,7 @@ extension LibraryRepository: BackupV15SnapshotProviding { let creators = electedCreators(try creatorDirectory(context: context)) let creatorRoles = electedCreatorRoles(try creatorRoleDirectory(context: context)) - return BackupV15Payload(+ return BackupV16Payload( entries: common.entries, works: works, sites: common.sites,@@ -200,8 +200,8 @@ extension LibraryRepository: BackupV15SnapshotProviding { // keep, so an archive never carries a row that pass deletes. series: try projectSeries(context: context), links: try projectLinks(context: context),- creators: mapV15CreatorRecords(creators),- creatorRoles: mapV15CreatorRoleRecords(creatorRoles),+ creators: mapV16CreatorRecords(creators),+ creatorRoles: mapV16CreatorRoleRecords(creatorRoles), // Req 9.2: one record per work-and-creator pair, the row // `dedupeCredits` would keep carrying the union it would write — // so an archive never carries a state the next pass changes.@@ -282,11 +282,11 @@ extension LibraryRepository: BackupV15SnapshotProviding { /// (Q68). Both shapes read identically on every device (unresolved, and /// healing when the target arrives), and only one of them is a file the /// reference checks accept.- private static func mapV15CreatorRecords(+ private static func mapV16CreatorRecords( _ directory: CreatorDirectory- ) -> [BackupV15Creator] {+ ) -> [BackupV16Creator] { directory.identities.map { identity in- BackupV15Creator(+ BackupV16Creator( id: identity.id, name: identity.name, nameModifiedAt: identity.nameModifiedAt, notes: identity.notes, notesModifiedAt: identity.notesModifiedAt,@@ -298,11 +298,11 @@ extension LibraryRepository: BackupV15SnapshotProviding { } } - private static func mapV15CreatorRoleRecords(+ private static func mapV16CreatorRoleRecords( _ directory: CreatorRoleDirectory- ) -> [BackupV15CreatorRole] {+ ) -> [BackupV16CreatorRole] { directory.identities.map { identity in- BackupV15CreatorRole(+ BackupV16CreatorRole( id: identity.id, name: identity.name, nameModifiedAt: identity.nameModifiedAt, position: identity.position,@@ -338,9 +338,9 @@ extension LibraryRepository: BackupV15SnapshotProviding { /// The group's presented content, plus the immutable evidence its carrier /// holds. One record per identity, like every other archive record: rows /// sharing a UUID are one character everywhere else in the app.- private static func mapV15CharacterRecord(_ group: CharacterGroup) -> BackupV15Character {+ private static func mapV16CharacterRecord(_ group: CharacterGroup) -> BackupV16Character { let content = group.presentedContent- return BackupV15Character(+ return BackupV16Character( id: group.id, workID: group.carrier.ownerWorkID, name: content.name,@@ -355,28 +355,28 @@ extension LibraryRepository: BackupV15SnapshotProviding { /// Suppression rows travel one-for-one, duplicates included (Q82): the store /// reads them through by `actionAt` rather than folding them, so folding /// here would be a second convergence rule that only archives obey.- private static func mapV15SuppressionRecord(+ private static func mapV16SuppressionRecord( _ row: CharacterSuppression- ) -> BackupV15Suppression {- BackupV15Suppression(+ ) -> BackupV16Suppression {+ BackupV16Suppression( id: row.id, workID: row.ownerWorkID, kindRaw: row.kindRaw, nameKey: row.nameKey, sourceKindRaw: row.sourceKindRaw, sourceEntryID: row.sourceEntryID, evidence: row.evidence, statusRaw: row.statusRaw, actionAt: row.actionAt) } - /// `mapV15CharacterRecord` over a place group. The owner comes from the+ /// `mapV16CharacterRecord` over a place group. The owner comes from the /// carrier's **column**, resolved or not: a place whose work has not arrived /// exports naming it, which is the only thing that lets Req 5.5's orphan /// round-trip (Q60). /// /// It names `workID` rather than `RecordRow.ownerWorkID` because the two- /// archive records genuinely differ here: `BackupV15Place.workID` is a- /// `UUID` and `BackupV15Character.workID` a `UUID?`, which is the same+ /// archive records genuinely differ here: `BackupV16Place.workID` is a+ /// `UUID` and `BackupV16Character.workID` a `UUID?`, which is the same /// asymmetry the two tables have. That is also why the pair does not /// collapse into one generic mapper.- private static func mapV15PlaceRecord(_ group: RecordGroup<Place>) -> BackupV15Place {+ private static func mapV16PlaceRecord(_ group: RecordGroup<Place>) -> BackupV16Place { let content = group.presentedContent- return BackupV15Place(+ return BackupV16Place( id: group.id, workID: group.carrier.workID, name: content.name,@@ -388,11 +388,11 @@ extension LibraryRepository: BackupV15SnapshotProviding { modifiedAt: group.modifiedAt) } - /// One-for-one, duplicates included, for `mapV15SuppressionRecord`'s reason.- private static func mapV15PlaceSuppressionRecord(+ /// One-for-one, duplicates included, for `mapV16SuppressionRecord`'s reason.+ private static func mapV16PlaceSuppressionRecord( _ row: PlaceSuppression- ) -> BackupV15PlaceSuppression {- BackupV15PlaceSuppression(+ ) -> BackupV16PlaceSuppression {+ BackupV16PlaceSuppression( id: row.id, workID: row.workID, kindRaw: row.kindRaw, nameKey: row.nameKey, sourceKindRaw: row.sourceKindRaw, sourceEntryID: row.sourceEntryID, evidence: row.evidence, statusRaw: row.statusRaw, actionAt: row.actionAt)@@ -401,48 +401,48 @@ extension LibraryRepository: BackupV15SnapshotProviding { // MARK: - The Exporter -/// Orchestrates coherent 15/16 snapshot → validated encoding → staging.+/// Orchestrates coherent 16/17 snapshot → validated encoding → staging. /// /// The only exporter. It decode-validates its own bytes before sharing, so a-/// produced file is always a valid strict 15/16 document.-public final class BackupV15Exporter: Sendable {- private let repository: any BackupV15SnapshotProviding+/// produced file is always a valid strict 16/17 document.+public final class BackupV16Exporter: Sendable {+ private let repository: any BackupV16SnapshotProviding private let stagingDirectory: URL public init(- repository: any BackupV15SnapshotProviding,+ repository: any BackupV16SnapshotProviding, stagingDirectory: URL ) { self.repository = repository self.stagingDirectory = stagingDirectory } - public func export(metadata: BackupV15Metadata) async throws -> BackupExportResult {- let payload: BackupV15Payload+ public func export(metadata: BackupV16Metadata) async throws -> BackupExportResult {+ let payload: BackupV16Payload do {- payload = try await repository.backupV15Snapshot()- } catch let error as BackupV15ExportError {+ payload = try await repository.backupV16Snapshot()+ } catch let error as BackupV16ExportError { throw error } catch {- throw BackupV15ExportError.snapshotFailed(reason: String(describing: error))+ throw BackupV16ExportError.snapshotFailed(reason: String(describing: error)) } let encoded: Data do {- encoded = try BackupV15Codec.encode(payload: payload, metadata: metadata)+ encoded = try BackupV16Codec.encode(payload: payload, metadata: metadata) } catch {- throw BackupV15ExportError.encodingFailed(reason: String(describing: error))+ throw BackupV16ExportError.encodingFailed(reason: String(describing: error)) } do {- let decoded = try BackupV15Codec.decode(encoded)+ let decoded = try BackupV16Codec.decode(encoded) guard decoded.payload == payload else {- throw BackupV15ExportError.encodingFailed(reason: "decode-validation payload mismatch")+ throw BackupV16ExportError.encodingFailed(reason: "decode-validation payload mismatch") }- } catch let error as BackupV15ExportError {+ } catch let error as BackupV16ExportError { throw error } catch {- throw BackupV15ExportError.encodingFailed(reason: "decode-validation failed: \(error)")+ throw BackupV16ExportError.encodingFailed(reason: "decode-validation failed: \(error)") } do {@@ -450,18 +450,18 @@ public final class BackupV15Exporter: Sendable { at: stagingDirectory, withIntermediateDirectories: true) let fileURL = stagingDirectory.appending( path: ExportStaging.backupFilename(- version: "v\(BackupV15Document.formatVersion)",+ version: "v\(BackupV16Document.formatVersion)", exportedAt: metadata.exportedAt)) do { try ExportStaging.write(encoded, to: fileURL) } catch {- throw BackupV15ExportError.stagingFailed(reason: String(describing: error))+ throw BackupV16ExportError.stagingFailed(reason: String(describing: error)) } return BackupExportResult(fileURL: fileURL)- } catch let error as BackupV15ExportError {+ } catch let error as BackupV16ExportError { throw error } catch {- throw BackupV15ExportError.stagingFailed(+ throw BackupV16ExportError.stagingFailed( reason: "preparing staging directory failed: \(error)") } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV15Types.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV16Types.swiftsimilarity index 85%rename from Packages/AsterismCore/Sources/AsterismCore/BackupV15Types.swiftrename to Packages/AsterismCore/Sources/AsterismCore/BackupV16Types.swiftindex 570becd6..071ba022 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupV15Types.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV16Types.swift@@ -1,30 +1,24 @@ import Foundation -// MARK: - Backup V15 Document+// MARK: - Backup V16 Document -/// The 15/16 backup envelope: format version 15 over schema version 16-/// (`remove-article-mode` Req 5.1). The schema number names the store schema the-/// archive was taken from, which is V16.+/// The 16/17 backup envelope: format version 16 over live schema version 17.+/// The schema number names the store schema the archive was taken from. ///-/// It **replaces** the 14/15 set outright rather than standing beside it-/// (`rule-citation-by-uuid` Q14, restated at every generation since, and-/// `remove-article-mode` Q12): a Site no longer carries a junk-suffix rule,-/// because the store no longer has the column, and a 14/15 file carries one for-/// a mode this build does not know — which is exactly what one supported pair-/// per build exists to stop arriving silently. An archive written before 15/16-/// is refused by version, with the message naming the pair it declares-/// (`remove-article-mode` Req 5.3).+/// It replaces the 15/16 importer outright. A pre-feature archive has no+/// catch-up progress fields, so this build refuses it by version before a+/// library write begins (`catch-up-progress` Req 8.3). /// /// The schema number is **pinned to the live schema by a test**-/// (`BackupV15ArchiveTests.envelopeVersionsFollowTheLiveSchema`, Q66): a schema+/// (`BackupV16ArchiveTests.envelopeVersionsFollowTheLiveSchema`): a schema /// bump moves four things and this is the only one of them that fails silently /// when it is forgotten. /// /// The envelope keys are 4/4's, unchanged through every generation since. /// Everything this one changes is inside `payload`.-public struct BackupV15Document: Codable, Equatable, Sendable {- public static let formatVersion = 15- public static let schemaVersion = 16+public struct BackupV16Document: Codable, Equatable, Sendable {+ public static let formatVersion = 16+ public static let schemaVersion = 17 public let backupFormatVersion: Int public let databaseSchemaVersion: Int@@ -34,7 +28,7 @@ public struct BackupV15Document: Codable, Equatable, Sendable { public let entryCount: Int public let workCount: Int public let checksum: String- public let payload: BackupV15Payload+ public let payload: BackupV16Payload public init( appBuild: String,@@ -43,7 +37,7 @@ public struct BackupV15Document: Codable, Equatable, Sendable { entryCount: Int, workCount: Int, checksum: String,- payload: BackupV15Payload+ payload: BackupV16Payload ) { backupFormatVersion = Self.formatVersion databaseSchemaVersion = Self.schemaVersion@@ -57,9 +51,9 @@ public struct BackupV15Document: Codable, Equatable, Sendable { } } -// MARK: - V15 Payload+// MARK: - V16 Payload -/// The seventeen arrays a 15/16 archive holds.+/// The seventeen arrays a 16/17 archive holds. /// /// **Every record kind is enumerated whole**, and no parent record carries a /// list of its children (Req 9.3). The 6/7 payload had a Site naming its rules,@@ -69,67 +63,67 @@ public struct BackupV15Document: Codable, Equatable, Sendable { /// distinct pairs arrive under the same rule the characters do (Q17): a row /// whose Work has not arrived exports naming the Work it belongs to, and imports /// unattached (Req 9.5, Q22).-public struct BackupV15Payload: Codable, Equatable, Sendable {- public let entries: [BackupV15Entry]- public let works: [BackupV15Work]- public let sites: [BackupV15Site]- public let titlePatterns: [BackupV15TitlePattern]- public let urlRules: [BackupV15URLRule]- public let workTypes: [BackupV15WorkType]+public struct BackupV16Payload: Codable, Equatable, Sendable {+ public let entries: [BackupV16Entry]+ public let works: [BackupV16Work]+ public let sites: [BackupV16Site]+ public let titlePatterns: [BackupV16TitlePattern]+ public let urlRules: [BackupV16URLRule]+ public let workTypes: [BackupV16WorkType] /// One row per Work and hostname (Req 9.1). The Work's site presence lives /// here and nowhere else.- public let memberships: [BackupV15Membership]+ public let memberships: [BackupV16Membership] /// The reader's "not the same work" over an unordered pair (Req 5.5).- public let distinctPairs: [BackupV15DistinctPair]- public let characters: [BackupV15Character]- public let suppressions: [BackupV15Suppression]+ public let distinctPairs: [BackupV16DistinctPair]+ public let characters: [BackupV16Character]+ public let suppressions: [BackupV16Suppression] /// The reader's places (`place-extraction` Req 5.1), enumerated whole for /// the reason the characters are — and one more: a `Place` declares no /// relationship at all, so an orphan is reachable only this way (Req 5.5).- public let places: [BackupV15Place]+ public let places: [BackupV16Place] /// The place half of the suppression ledger. A separate array rather than a /// kind column on `suppressions`, because the store keeps the two in /// separate tables (Decision 2) and a shared array would be a second /// spelling of that split.- public let placeSuppressions: [BackupV15PlaceSuppression]+ public let placeSuppressions: [BackupV16PlaceSuppression] /// The reader's series (`series-and-related-works` Req 13.1). A work's /// **membership** is not here: it is part of the work's own record, and /// travels on it.- public let series: [BackupV15Series]+ public let series: [BackupV16Series] /// One row per linked pair, the survivor the next reconcile would keep /// (Req 13.2, Q14). A link naming a work the archive does not carry is /// legal and imports unresolved, exactly as a distinct pair does.- public let links: [BackupV15Link]+ public let links: [BackupV16Link] /// The reader's creators, one record per folded identity /// (`work-creators` Req 9.1).- public let creators: [BackupV15Creator]+ public let creators: [BackupV16Creator] /// The reader's role list, one record per folded identity, carrying the /// list order every credit is read in.- public let creatorRoles: [BackupV15CreatorRole]+ public let creatorRoles: [BackupV16CreatorRole] /// One record per work-and-creator pair, as /// [10.5](../../../../specs/work-creators/requirements.md#10.5) would keep /// it (Req 9.2). A credit naming a work, creator or role the archive does /// not carry is legal and imports unresolved (Req 9.5).- public let credits: [BackupV15Credit]+ public let credits: [BackupV16Credit] public init(- entries: [BackupV15Entry],- works: [BackupV15Work],- sites: [BackupV15Site],- titlePatterns: [BackupV15TitlePattern],- urlRules: [BackupV15URLRule],- workTypes: [BackupV15WorkType] = [],- memberships: [BackupV15Membership] = [],- distinctPairs: [BackupV15DistinctPair] = [],- characters: [BackupV15Character] = [],- suppressions: [BackupV15Suppression] = [],- places: [BackupV15Place] = [],- placeSuppressions: [BackupV15PlaceSuppression] = [],- series: [BackupV15Series] = [],- links: [BackupV15Link] = [],- creators: [BackupV15Creator] = [],- creatorRoles: [BackupV15CreatorRole] = [],- credits: [BackupV15Credit] = []+ entries: [BackupV16Entry],+ works: [BackupV16Work],+ sites: [BackupV16Site],+ titlePatterns: [BackupV16TitlePattern],+ urlRules: [BackupV16URLRule],+ workTypes: [BackupV16WorkType] = [],+ memberships: [BackupV16Membership] = [],+ distinctPairs: [BackupV16DistinctPair] = [],+ characters: [BackupV16Character] = [],+ suppressions: [BackupV16Suppression] = [],+ places: [BackupV16Place] = [],+ placeSuppressions: [BackupV16PlaceSuppression] = [],+ series: [BackupV16Series] = [],+ links: [BackupV16Link] = [],+ creators: [BackupV16Creator] = [],+ creatorRoles: [BackupV16CreatorRole] = [],+ credits: [BackupV16Credit] = [] ) { self.entries = entries self.works = works@@ -151,13 +145,13 @@ public struct BackupV15Payload: Codable, Equatable, Sendable { } } -// MARK: - V15 Records+// MARK: - V16 Records /// One Site. **No child lists** (Req 9.3): a title rule and a URL rule each name /// their hostname, so the Site naming them back was a second spelling of one /// relationship — and the one the reference checks had to cross-examine. ///-/// **14/15 → 15/16 drops the junk-suffix rule** (`remove-article-mode` Req 5.1):+/// **14/15 → 16/17 drops the junk-suffix rule** (`remove-article-mode` Req 5.1): /// articles mode is gone and V16 has no `Site.junkSuffixRule` column for the /// field to import into, so it leaves the wire rather than travelling as a value /// nothing can read back.@@ -166,7 +160,7 @@ public struct BackupV15Payload: Codable, Equatable, Sendable { /// this build cannot name — `articles`, written by a build before this one — /// fails the decode and refuses the archive as malformed, which is what Req 5.1 /// asks for. Reading a store row is tolerant; reading a backup never is.-public struct BackupV15Site: Codable, Equatable, Sendable {+public struct BackupV16Site: Codable, Equatable, Sendable { public let hostname: String public let displayName: String public let mode: SiteMode@@ -185,7 +179,7 @@ public struct BackupV15Site: Codable, Equatable, Sendable { /// One title rule. The arm and both trims travel as one `StoredPatternDefinition` /// — the value V8 stores in `TitlePattern.definitionData` (Q25) — rather than as /// a definition beside two loose trim columns.-public struct BackupV15TitlePattern: Codable, Equatable, Sendable {+public struct BackupV16TitlePattern: Codable, Equatable, Sendable { public let id: UUID public let siteHostname: String public let version: Int@@ -212,7 +206,7 @@ public struct BackupV15TitlePattern: Codable, Equatable, Sendable { /// One URL rule, unchanged from the generation that froze it: it never carried a /// child list and its definition was already one value.-public struct BackupV15URLRule: Codable, Equatable, Sendable {+public struct BackupV16URLRule: Codable, Equatable, Sendable { public let id: UUID public let version: Int public let isCurrent: Bool@@ -246,7 +240,7 @@ public struct BackupV15URLRule: Codable, Equatable, Sendable { /// one UUID are a normal permanent state in the live store, so the exporter /// writes the directory's folded identity rather than the rows, and `modifiedAt` /// on the wire is the fold's max.-public struct BackupV15WorkType: Codable, Equatable, Sendable {+public struct BackupV16WorkType: Codable, Equatable, Sendable { public let id: UUID public let name: String /// `active` / `removed` / `merged`, carried raw so an archive written by a@@ -292,7 +286,7 @@ public struct BackupV15WorkType: Codable, Equatable, Sendable { /// build accepts is one it wrote, so a record missing them is malformed, and a /// default on decode would restore a reader's abandoned work as one they are /// still reading rather than saying so.-public struct BackupV15Work: Codable, Equatable, Sendable {+public struct BackupV16Work: Codable, Equatable, Sendable { public let id: UUID public let displayTitle: String public let lastParsedTitle: String?@@ -306,7 +300,7 @@ public struct BackupV15Work: Codable, Equatable, Sendable { /// The reader's own line about it, trimmed on write and carried verbatim /// here — empty when they have not written one. public let verdict: String- /// Cites a `BackupV15WorkType`, or an entry this archive could not carry — a+ /// Cites a `BackupV16WorkType`, or an entry this archive could not carry — a /// dangling id exports verbatim and imports as unresolved rather than /// refusing or inventing a name (`configurable-work-types` Q24). public let workTypeID: UUID?@@ -362,13 +356,37 @@ public struct BackupV15Work: Codable, Equatable, Sendable { /// **Required**, on the statuses' precedent above — no `decodeIfPresent`, /// no default. An empty set is written explicitly, so "no release days" and /// "a record from a build that had none" cannot be confused: a record- /// lacking the key is a malformed 15/16 file, not a pre-feature one (Q22).+ /// lacking the key is a malformed 16/17 file, not a pre-feature one (Q22). /// /// The **typed** enum rather than the raw strings, unlike `thumbnailShape` /// beside it: a spelling this build cannot name fails decoding, which is /// what Req 8.1 asks for, and the export path refuses one by name before it /// ever gets here (Req 8.3). There is no tolerant reading of a backup. public let releaseDays: [ReleaseDay]+ /// The two timestamped progress values are flattened on the archive wire.+ /// Optional keys are omitted when absent by synthesized Codable.+ public let latestReleasedChapter: Int?+ public let latestConfirmedAt: Date?+ public let countsUpOnReleaseDays: Bool+ public let latestIsEstimate: Bool+ public let lastChapterOverride: Int?+ public let lastChapterOverrideAt: Date?++ public var catchUpRecord: CatchUpRecord {+ let confirmation = latestConfirmedAt.map {+ CatchUpConfirmation(+ latest: latestReleasedChapter,+ confirmedAtMilliseconds: MillisecondInstant.milliseconds($0),+ countsUp: countsUpOnReleaseDays, isEstimate: latestIsEstimate)+ }+ let override = lastChapterOverrideAt.map { moment -> LastChapterOverride in+ let milliseconds = MillisecondInstant.milliseconds(moment)+ return lastChapterOverride.map {+ .value($0, atMilliseconds: milliseconds)+ } ?? .cleared(atMilliseconds: milliseconds)+ }+ return CatchUpRecord(confirmation: confirmation, override: override)+ } public init( id: UUID,@@ -392,13 +410,25 @@ public struct BackupV15Work: Codable, Equatable, Sendable { seriesID: UUID? = nil, seriesPosition: Double? = nil, thumbnailShape: String? = nil,- thumbnail: Data? = nil+ thumbnail: Data? = nil,+ latestReleasedChapter: Int? = nil,+ latestConfirmedAt: Date? = nil,+ countsUpOnReleaseDays: Bool = true,+ latestIsEstimate: Bool = false,+ lastChapterOverride: Int? = nil,+ lastChapterOverrideAt: Date? = nil ) { self.releaseDays = ReleaseDay.canonical(releaseDays) self.seriesID = seriesID self.seriesPosition = seriesPosition self.thumbnailShape = thumbnailShape self.thumbnail = thumbnail+ self.latestReleasedChapter = latestReleasedChapter+ self.latestConfirmedAt = latestConfirmedAt.map(MillisecondInstant.quantize)+ self.countsUpOnReleaseDays = countsUpOnReleaseDays+ self.latestIsEstimate = latestIsEstimate+ self.lastChapterOverride = lastChapterOverride+ self.lastChapterOverrideAt = lastChapterOverrideAt.map(MillisecondInstant.quantize) self.id = id self.displayTitle = displayTitle self.lastParsedTitle = lastParsedTitle@@ -428,7 +458,7 @@ public struct BackupV15Work: Codable, Equatable, Sendable { /// payload (Req 9.3). Names need not be unique (Q11), so there is nothing here /// to elect and nothing to fold — two rows sharing an id would be duplicate rows /// of one series, and the reference checks refuse a payload holding both.-public struct BackupV15Series: Codable, Equatable, Sendable {+public struct BackupV16Series: Codable, Equatable, Sendable { public let id: UUID /// Stored trimmed and non-empty; an empty trimmed name is refused at the /// door (Req 13.5).@@ -450,12 +480,12 @@ public struct BackupV15Series: Codable, Equatable, Sendable { /// One related-work link (`series-and-related-works` Req 13.1). ///-/// `BackupV15DistinctPair`'s shape, because the store's row is: two UUIDs in the+/// `BackupV16DistinctPair`'s shape, because the store's row is: two UUIDs in the /// canonical sorted order, naming works the archive may not carry — an /// unresolved link imports verbatim and is tolerated (Req 13.5, 11.2). What it /// adds is the reader's type and a modification time, which is the survivor key /// over a duplicated pair (Req 11.4, Q27).-public struct BackupV15Link: Codable, Equatable, Sendable {+public struct BackupV16Link: Codable, Equatable, Sendable { public let id: UUID public let lowerWorkID: UUID public let higherWorkID: UUID@@ -476,14 +506,14 @@ public struct BackupV15Link: Codable, Equatable, Sendable { } /// The record with its two ids in the canonical order, whatever order they- /// arrived in — `BackupV15DistinctPair.sorted`'s reason exactly: an unsorted+ /// arrived in — `BackupV16DistinctPair.sorted`'s reason exactly: an unsorted /// pair is a second spelling of one link, and `MembershipReconciler.dedupeLinks` /// groups on the sorted form, so a hand-built archive's row is normalised on /// the way in rather than left as a duplicate nothing would ever match.- public var sorted: BackupV15Link {+ public var sorted: BackupV16Link { let ids = WorkDistinctPair.sortedIDs(lowerWorkID, higherWorkID) guard ids.lower != lowerWorkID || ids.higher != higherWorkID else { return self }- return BackupV15Link(+ return BackupV16Link( id: id, lowerWorkID: ids.lower, higherWorkID: ids.higher, linkType: linkType, createdAt: createdAt, modifiedAt: modifiedAt) }@@ -491,7 +521,7 @@ public struct BackupV15Link: Codable, Equatable, Sendable { /// One creator (`work-creators` Req 9.1). ///-/// **One record per folded identity**, `BackupV15WorkType`'s rule — rows sharing+/// **One record per folded identity**, `BackupV16WorkType`'s rule — rows sharing /// a UUID are one record everywhere else in the app — but carrying the **per-field /// modification times** the directory fold reads (Q50). A single `modifiedAt` /// cannot drive a per-field fold, and stamping it onto every field would make@@ -500,7 +530,7 @@ public struct BackupV15Link: Codable, Equatable, Sendable { /// A `merged` record names its **final** survivor (Q33): the exporter chases the /// alias chain, so an archive never carries a pointer at a record that is itself /// merged, and the reference checks refuse one.-public struct BackupV15Creator: Codable, Equatable, Sendable {+public struct BackupV16Creator: Codable, Equatable, Sendable { public let id: UUID /// The stored spelling, trimmed. Normalized names are computed, never /// stored, so the file carries what the reader typed.@@ -548,10 +578,10 @@ public struct BackupV15Creator: Codable, Equatable, Sendable { /// One role of the reader's list (`work-creators` Req 9.1). ///-/// `BackupV15Creator`'s shape with `position` in the place of notes, and a third+/// `BackupV16Creator`'s shape with `position` in the place of notes, and a third /// state: a removed role is retained so that re-adding its name restores it and /// the credits holding it keep the identifier (Decision 4).-public struct BackupV15CreatorRole: Codable, Equatable, Sendable {+public struct BackupV16CreatorRole: Codable, Equatable, Sendable { public let id: UUID public let name: String public let nameModifiedAt: Date@@ -593,7 +623,7 @@ public struct BackupV15CreatorRole: Codable, Equatable, Sendable { /// One credit: that one creator worked on one work, in the roles it holds /// (`work-creators` Req 9.1). ///-/// `BackupV15Link`'s shape, because the store's row is: plain identifier columns+/// `BackupV16Link`'s shape, because the store's row is: plain identifier columns /// naming records the archive may not carry. A credit whose work, creator or role /// is absent imports **unresolved** and is tolerated (Req 9.5, /// [10.2](../../../../specs/work-creators/requirements.md#10.2)) — it is never a@@ -604,7 +634,7 @@ public struct BackupV15CreatorRole: Codable, Equatable, Sendable { /// so a restore after a remove-then-restore would lose pairings /// [2.2](../../../../specs/work-creators/requirements.md#2.2) promises to bring /// back. It is sorted and deduplicated, as every write leaves it.-public struct BackupV15Credit: Codable, Equatable, Sendable {+public struct BackupV16Credit: Codable, Equatable, Sendable { public let id: UUID public let workID: UUID public let creatorID: UUID@@ -633,15 +663,15 @@ public struct BackupV15Credit: Codable, Equatable, Sendable { /// The record with its role identifiers in the one order a stored set has — /// sorted and deduplicated, as every writer leaves them. ///- /// `BackupV15Link.sorted`'s role and its reason: an unsorted or repeated+ /// `BackupV16Link.sorted`'s role and its reason: an unsorted or repeated /// list is a second spelling of one role set, and every comparison the /// import makes is an equality on the array. The wire check refuses a /// repeat *as stored* first (Req 9.5), so this normalises a hand-built file /// on the way to the commit rather than hiding a refusal.- public var normalized: BackupV15Credit {+ public var normalized: BackupV16Credit { let roles = WorkCreditSupport.roleIDs(roleIDs) guard roles != roleIDs else { return self }- return BackupV15Credit(+ return BackupV16Credit( id: id, workID: workID, creatorID: creatorID, roleIDs: roles, createdAt: createdAt, modifiedAt: modifiedAt) }@@ -657,7 +687,7 @@ public struct BackupV15Credit: Codable, Equatable, Sendable { /// /// The cited rule is a **bare UUID**: a membership names the rule row and /// carries no rule version (Req 10.4, Q28).-public struct BackupV15Membership: Codable, Equatable, Sendable {+public struct BackupV16Membership: Codable, Equatable, Sendable { public let id: UUID public let workID: UUID? public let hostname: String@@ -694,7 +724,7 @@ public struct BackupV15Membership: Codable, Equatable, Sendable { /// unordered, so it has one spelling, and it names Works the archive may not /// carry — a pair whose Works have not arrived imports verbatim and is tolerated /// (Req 8.3).-public struct BackupV15DistinctPair: Codable, Equatable, Sendable {+public struct BackupV16DistinctPair: Codable, Equatable, Sendable { public let id: UUID public let lowerWorkID: UUID public let higherWorkID: UUID@@ -712,10 +742,10 @@ public struct BackupV15DistinctPair: Codable, Equatable, Sendable { /// `MembershipReconciler.dedupePairs` groups on the sorted form — so a /// hand-built or older archive's row is normalised on the way in rather than /// left as a duplicate nothing would ever match (task 20/21 review).- public var sorted: BackupV15DistinctPair {+ public var sorted: BackupV16DistinctPair { let ids = WorkDistinctPair.sortedIDs(lowerWorkID, higherWorkID) guard ids.lower != lowerWorkID || ids.higher != higherWorkID else { return self }- return BackupV15DistinctPair(+ return BackupV16DistinctPair( id: id, lowerWorkID: ids.lower, higherWorkID: ids.higher, recordedAt: recordedAt) } }@@ -735,7 +765,7 @@ public struct BackupV15DistinctPair: Codable, Equatable, Sendable { /// /// `characterExtractionFingerprint` rides on the record whose `note` it /// describes (Req 9.4), for the reason the Work's does.-public struct BackupV15Entry: Codable, Equatable, Sendable {+public struct BackupV16Entry: Codable, Equatable, Sendable { public let id: UUID public let captureTitle: String public let captureTitleSource: CaptureTitleSource@@ -818,7 +848,7 @@ public struct BackupV15Entry: Codable, Equatable, Sendable { /// has not arrived is a tolerated in-flight state /// (`character-extraction` Q78), a reference to a work the archive does not /// carry is a file contradicting itself.-public struct BackupV15Character: Codable, Equatable, Sendable {+public struct BackupV16Character: Codable, Equatable, Sendable { public let id: UUID public let workID: UUID? public let name: String@@ -856,11 +886,11 @@ public struct BackupV15Character: Codable, Equatable, Sendable { /// One suppression row. ///-/// The enum columns travel **raw**, for the reason `BackupV15WorkType`'s+/// The enum columns travel **raw**, for the reason `BackupV16WorkType`'s /// `stateRaw` does: an archive written by a later build's wider set decodes here /// rather than refusing, and the store's own coercion answers for a value this /// build cannot name.-public struct BackupV15Suppression: Codable, Equatable, Sendable {+public struct BackupV16Suppression: Codable, Equatable, Sendable { public let id: UUID public let workID: UUID? public let kindRaw: String@@ -912,7 +942,7 @@ public struct BackupV15Suppression: Codable, Equatable, Sendable { /// One place, as the archive holds it (`place-extraction` Req 5.1). ///-/// `BackupV15Character`'s fields with **one difference**: `workID` is not+/// `BackupV16Character`'s fields with **one difference**: `workID` is not /// optional. A place names its owner in a UUID column rather than through a /// relationship, so the two kinds of absence a character has — no relationship, /// and a relationship pointing at a row that has not arrived — collapse into@@ -923,7 +953,7 @@ public struct BackupV15Suppression: Codable, Equatable, Sendable { /// contradicting itself and refuses, while a place naming one is the tolerated /// orphan of Req 5.5 and is carried verbatim. There is no shape it could be /// rewritten to that would say anything truer.-public struct BackupV15Place: Codable, Equatable, Sendable {+public struct BackupV16Place: Codable, Equatable, Sendable { public let id: UUID /// The owning work, as the row states it. Kept whether or not it resolves — /// the import writes it back unchanged, so an orphan round-trips.@@ -963,11 +993,11 @@ public struct BackupV15Place: Codable, Equatable, Sendable { /// One place-suppression row. ///-/// `BackupV15Suppression`'s shape with `BackupV15Place`'s ownership column, and+/// `BackupV16Suppression`'s shape with `BackupV16Place`'s ownership column, and /// the same tolerance: the enum columns travel **raw** so a value a later /// build's wider set wrote survives the round trip, and the owner is carried /// whether or not it resolves.-public struct BackupV15PlaceSuppression: Codable, Equatable, Sendable {+public struct BackupV16PlaceSuppression: Codable, Equatable, Sendable { public let id: UUID public let workID: UUID public let kindRaw: String
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CatchUpFixtureWriter.swift b/Packages/AsterismCore/Sources/AsterismCore/CatchUpFixtureWriter.swiftnew file mode 100644index 00000000..47343698--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/CatchUpFixtureWriter.swift@@ -0,0 +1,52 @@+import Foundation+import SwiftData++// Fixture-only progress, absent from Personal builds.+#if DEBUG || ASTERISM_PERFORMANCE_TESTING+public enum CatchUpFixtureWriter {+ public static func record(+ latest: Int?, confirmedAt: Date, countsUp: Bool = true,+ isEstimate: Bool = false, override: LastChapterOverride? = nil+ ) -> CatchUpRecord {+ CatchUpRecord(+ confirmation: CatchUpConfirmation(+ latest: latest,+ confirmedAtMilliseconds: MillisecondInstant.milliseconds(confirmedAt),+ countsUp: countsUp, isEstimate: isEstimate),+ override: override)+ }++ @discardableResult+ public static func apply(+ latest: Int?, confirmedAt: Date, countsUp: Bool = true,+ isEstimate: Bool = false, override: LastChapterOverride? = nil,+ to rows: [Work]+ ) -> Bool {+ CatchUpWriter.apply(+ record(+ latest: latest, confirmedAt: confirmedAt, countsUp: countsUp,+ isEstimate: isEstimate, override: override),+ to: rows)+ }+}++extension LibraryRepository {+ /// Seeds a real Work identity group with a caller-chosen past confirmation.+ public func seedCatchUpFixture(+ workID: UUID, latest: Int?, confirmedAt: Date, countsUp: Bool = true,+ isEstimate: Bool = false, override: LastChapterOverride? = nil+ ) async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding catch-up progress") { context in+ let rows = try context.fetch(+ FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID }))+ guard !rows.isEmpty else {+ throw LibraryRepositoryError.recordNotFound(type: "Work", id: workID)+ }+ CatchUpFixtureWriter.apply(+ latest: latest, confirmedAt: confirmedAt, countsUp: countsUp,+ isEstimate: isEstimate, override: override, to: rows)+ try self.saveStrategy.save(context)+ }+ }+}+#endif
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift b/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swiftnew file mode 100644index 00000000..a4399565--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift@@ -0,0 +1,138 @@+import Foundation++public struct NumberedNote: Equatable, Sendable {+ public let number: Int+ public let firstCapturedAt: Date+ public let title: String++ public init(number: Int, firstCapturedAt: Date, title: String) {+ self.number = number+ self.firstCapturedAt = firstCapturedAt+ self.title = title+ }++ public static func from(_ entries: [EntrySnapshot]) -> [NumberedNote] {+ entries.compactMap { entry in+ guard let number = ChapterNumber.whole(+ chapterSequence: entry.chapterSequence,+ chapterTitle: entry.chapterTitle)+ else { return nil }+ return NumberedNote(+ number: number, firstCapturedAt: entry.firstCapturedAt,+ title: entry.chapterTitle ?? entry.captureTitle)+ }+ }+}++public enum LastReadSource: Equatable, Sendable {+ case note(String)+ case override+}++/// Progress for one selected civil day, derived without reading or writing a store.+public struct CatchUpProgress: Equatable, Sendable {+ public enum State: Equatable, Sendable { case unknown, exact, estimated, caughtUp }++ public let state: State+ public let lastRead: Int?+ public let lastReadSource: LastReadSource?+ public let readDay: CivilDay?+ public let effectiveLatest: Int?+ public let confirmedDay: CivilDay?+ public var behind: Int? {+ guard let effectiveLatest, let lastRead else { return nil }+ return effectiveLatest - lastRead+ }++ public static func build(+ record: CatchUpRecord, notes: [NumberedNote], releaseDays: [ReleaseDay],+ workStatus: WorkStatus, day: CivilDay, calendar: Calendar+ ) -> CatchUpProgress {+ let override: (number: Int, at: Date)?+ if case .value(let number, let moment) = record.override {+ override = (number, MillisecondInstant.date(fromMilliseconds: moment))+ } else {+ override = nil+ }+ let counted = notes.filter { override == nil || $0.firstCapturedAt > override!.at }+ let maxNote = counted.map(\.number).max()+ let lastRead = [maxNote, override?.number].compactMap { $0 }.max()+ let candidates = counted+ .filter { $0.number == lastRead }+ .map { (at: $0.firstCapturedAt, source: LastReadSource.note($0.title)) }+ let overrideCandidate: (at: Date, source: LastReadSource)? =+ override.flatMap { $0.number == lastRead ? (at: $0.at, source: .override) : nil }+ // A note wins an exact time tie, so the source is deterministic even if+ // an override was set in the same millisecond as its capture.+ let chosen = (candidates + [overrideCandidate].compactMap { $0 }).min {+ if $0.at != $1.at { return $0.at < $1.at }+ switch ($0.source, $1.source) {+ case (.note(let left), .note(let right)): return left < right+ case (.note, .override): return true+ default: return false+ }+ }+ let readDay = chosen.map { CivilDay($0.at, calendar: calendar) }+ let confirmedDay = record.confirmation.map {+ CivilDay(MillisecondInstant.date(fromMilliseconds: $0.confirmedAtMilliseconds), calendar: calendar)+ }++ func releases(after start: CivilDay?) -> Int {+ guard record.countsUp, workStatus == .ongoing, let start, start < day else { return 0 }+ return TodayDayPlan.releaseCount(+ of: releaseDays, after: start, through: day, calendar: calendar) ?? 0+ }++ let effectiveLatest: Int?+ if let latest = record.latest {+ let confirmedBound = latest + releases(after: confirmedDay)+ let readBound: Int+ if let lastRead {+ let start = [readDay, confirmedDay].compactMap { $0 }.max()+ readBound = lastRead + releases(after: start)+ } else {+ readBound = 0+ }+ effectiveLatest = min(9_999, max(confirmedBound, readBound))+ } else {+ effectiveLatest = nil+ }++ let state: State+ if let effectiveLatest, let lastRead {+ if effectiveLatest == lastRead { state = .caughtUp }+ else if effectiveLatest == record.latest && record.confirmation?.isEstimate == false {+ state = .exact+ } else { state = .estimated }+ } else { state = .unknown }++ return CatchUpProgress(+ state: state, lastRead: lastRead, lastReadSource: chosen?.source,+ readDay: readDay, effectiveLatest: effectiveLatest, confirmedDay: confirmedDay)+ }++ public static func build(work: WorkSnapshot, day: CivilDay, calendar: Calendar) -> CatchUpProgress {+ build(+ record: work.catchUp, notes: NumberedNote.from(work.entries),+ releaseDays: work.releaseDays, workStatus: work.workStatus,+ day: day, calendar: calendar)+ }++ public static func rebased(+ record: CatchUpRecord, notes: [NumberedNote], releaseDays: [ReleaseDay],+ workStatus: WorkStatus, now: Date, calendar: Calendar+ ) -> CatchUpRecord? {+ guard record.latest != nil else { return nil }+ let day = CivilDay(now, calendar: calendar)+ let progress = build(+ record: record, notes: notes, releaseDays: releaseDays,+ workStatus: workStatus, day: day, calendar: calendar)+ guard let effectiveLatest = progress.effectiveLatest else { return nil }+ return CatchUpRecord(+ confirmation: CatchUpConfirmation(+ latest: effectiveLatest,+ confirmedAtMilliseconds: MillisecondInstant.milliseconds(now),+ countsUp: record.countsUp, isEstimate: true),+ override: record.override)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CatchUpRecord.swift b/Packages/AsterismCore/Sources/AsterismCore/CatchUpRecord.swiftnew file mode 100644index 00000000..b7e15ba2--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/CatchUpRecord.swift@@ -0,0 +1,93 @@+import Foundation++/// The reader's latest confirmation travels as one value through sync.+public struct CatchUpConfirmation: Codable, Equatable, Sendable {+ public var latest: Int?+ public var confirmedAtMilliseconds: Int64+ public var countsUp: Bool+ public var isEstimate: Bool++ public init(latest: Int?, confirmedAtMilliseconds: Int64, countsUp: Bool, isEstimate: Bool) {+ self.latest = latest+ self.confirmedAtMilliseconds = confirmedAtMilliseconds+ self.countsUp = countsUp+ self.isEstimate = isEstimate+ }+}++/// A clear keeps its moment so it can win over an older numeric override.+public enum LastChapterOverride: Equatable, Sendable, Codable {+ case value(Int, atMilliseconds: Int64)+ case cleared(atMilliseconds: Int64)++ public var atMilliseconds: Int64 {+ switch self {+ case .value(_, let moment), .cleared(let moment): moment+ }+ }++ private enum CodingKeys: String, CodingKey { case kind, number, atMilliseconds }+ private enum Kind: String, Codable { case value, cleared }++ public init(from decoder: Decoder) throws {+ let values = try decoder.container(keyedBy: CodingKeys.self)+ let kind = try values.decode(Kind.self, forKey: .kind)+ let moment = try values.decode(Int64.self, forKey: .atMilliseconds)+ switch kind {+ case .value: self = .value(try values.decode(Int.self, forKey: .number), atMilliseconds: moment)+ case .cleared: self = .cleared(atMilliseconds: moment)+ }+ }++ public func encode(to encoder: Encoder) throws {+ var values = encoder.container(keyedBy: CodingKeys.self)+ switch self {+ case .value(let number, let moment):+ try values.encode(Kind.value, forKey: .kind)+ try values.encode(number, forKey: .number)+ try values.encode(moment, forKey: .atMilliseconds)+ case .cleared(let moment):+ try values.encode(Kind.cleared, forKey: .kind)+ try values.encode(moment, forKey: .atMilliseconds)+ }+ }+}++public struct CatchUpRecord: Equatable, Sendable {+ public var confirmation: CatchUpConfirmation?+ public var override: LastChapterOverride?++ public init(confirmation: CatchUpConfirmation?, override: LastChapterOverride?) {+ self.confirmation = confirmation+ self.override = override+ }++ public var latest: Int? { confirmation?.latest }+ public var countsUp: Bool { confirmation?.countsUp ?? true }+ public static let pristine = CatchUpRecord(confirmation: nil, override: nil)+}++/// Elects both timestamped values independently, without a clock or row order.+public enum CatchUpFold {+ public static func elect(_ records: [CatchUpRecord]) -> CatchUpRecord {+ CatchUpRecord(+ confirmation: records.compactMap(\.confirmation).max(by: confirmationPrecedes),+ override: records.compactMap(\.override).max(by: overridePrecedes))+ }++ private static func confirmationPrecedes(_ left: CatchUpConfirmation, _ right: CatchUpConfirmation) -> Bool {+ let leftKey = (left.confirmedAtMilliseconds, left.latest ?? -1, left.countsUp ? 1 : 0, left.isEstimate ? 1 : 0)+ let rightKey = (right.confirmedAtMilliseconds, right.latest ?? -1, right.countsUp ? 1 : 0, right.isEstimate ? 1 : 0)+ return leftKey < rightKey+ }++ private static func overridePrecedes(_ left: LastChapterOverride, _ right: LastChapterOverride) -> Bool {+ func key(_ value: LastChapterOverride) -> (Int64, Int, Int) {+ switch value {+ case .value(let number, let moment): (moment, 1, number)+ case .cleared(let moment): (moment, 0, -1)+ }+ }+ return key(left) < key(right)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CatchUpWriter.swift b/Packages/AsterismCore/Sources/AsterismCore/CatchUpWriter.swiftnew file mode 100644index 00000000..1bfbaf03--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/CatchUpWriter.swift@@ -0,0 +1,35 @@+import Foundation++extension Work {+ /// Each blob is tolerated independently, so a damaged override cannot hide+ /// a valid confirmation (and conversely).+ internal var catchUpRecord: CatchUpRecord {+ CatchUpRecord(+ confirmation: catchUpConfirmationData.flatMap {+ try? JSONBlob.decode(CatchUpConfirmation.self, from: $0)+ },+ override: lastChapterOverrideData.flatMap {+ try? JSONBlob.decode(LastChapterOverride.self, from: $0)+ })+ }+}++/// Applies a logical record to every physical row of a Work identity group.+public enum CatchUpWriter {+ @discardableResult+ public static func apply(_ record: CatchUpRecord, to rows: [Work]) -> Bool {+ var wrote = false+ for row in rows {+ let current = row.catchUpRecord+ if current.confirmation != record.confirmation {+ row.catchUpConfirmationData = record.confirmation.map { try! JSONBlob.encode($0) }+ wrote = true+ }+ if current.override != record.override {+ row.lastChapterOverrideData = record.override.map { try! JSONBlob.encode($0) }+ wrote = true+ }+ }+ return wrote+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ChapterNumber.swift b/Packages/AsterismCore/Sources/AsterismCore/ChapterNumber.swiftnew file mode 100644index 00000000..37b73b20--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/ChapterNumber.swift@@ -0,0 +1,14 @@+import Foundation++/// The whole-number chapter interpretation shared by Today and catch-up progress.+public enum ChapterNumber {+ public static func whole(chapterSequence: String?, chapterTitle: String?) -> Int? {+ guard let key = ChapterKeyDerivation.key(+ chapterSequence: chapterSequence, chapterTitle: chapterTitle),+ key.components.count == 1,+ let number = key.components.first,+ (0...9_999).contains(number)+ else { return nil }+ return number+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swiftindex 6ab8f649..d1443d39 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift@@ -567,6 +567,8 @@ enum DuplicateReconciler { else { continue } wrote = apply(carrier, to: survivor, types: types) || wrote }+ let electedCatchUp = CatchUpFold.elect(allRows.map(\.catchUpRecord))+ wrote = CatchUpWriter.apply(electedCatchUp, to: survivor) || wrote // Q74: the group's rows must not differ in `modifiedAt` — it is the // last slot of the representative ordering, so a divergence there // moves which row represents the record.@@ -1304,6 +1306,7 @@ enum DuplicateReconciler { repointEntries(from: losers, to: survivor) carrySeries(from: losers, to: survivor) carryThumbnail(from: losers, to: survivor)+ carryCatchUp(from: losers, to: survivor) try collapseMemberships( from: losers, to: survivor, distinctPairs: distinctPairs, links: links, creditsByWork: &creditsByWork, creators: creators, context: context)@@ -1321,6 +1324,14 @@ enum DuplicateReconciler { } } + /// Re-elect at the deletion boundary. The Work fingerprint excludes progress,+ /// so a newer confirmation can arrive after the write phase without aborting+ /// the deletion. The survivor must receive it before the loser disappears.+ static func carryCatchUp(from losers: [Work], to survivor: [Work]) {+ let elected = CatchUpFold.elect((losers + survivor).map(\.catchUpRecord))+ CatchUpWriter.apply(elected, to: survivor)+ }+ /// Req 9.6: the collapse of **distinct works** never refuses, so a /// membership one of the losers held has to have an answer that needs no /// reader.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift b/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swiftindex e5a8ebf7..1627cd5a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift@@ -208,7 +208,7 @@ extension Entry { /// One citation row, as every pass that walks them sees it. /// /// It used to be a table of key paths into the model and into- /// `BackupV15Entry`, hand-enumerated nowhere else. With the citations folded+ /// `BackupV16Entry`, hand-enumerated nowhere else. With the citations folded /// into one blob the key paths have nothing to point at, so the row is a /// *value* now — but the seven rows, their order and their labels are /// unchanged, because `citerHostnames` still keeps the first hostname it
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex 2bdc3ee5..80cb3ef8 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift@@ -252,7 +252,19 @@ public protocol LibraryProviding: Sendable { func createWork(_ draft: NewWorkDraft) async throws -> WorkSnapshot func updateWork(- id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft+ id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar+ ) async throws -> LibraryWriteOutcome++ func catchUpSheetState(+ workID: UUID, day: CivilDay, calendar: Calendar+ ) async throws -> CatchUpSheetState++ func commitCatchUpProgress(+ id: UUID, basis: CatchUpRecord, draft: CatchUpDraft+ ) async throws -> LibraryWriteOutcome++ func setReadingStatus(+ id: UUID, expected: ReadingStatus, to: ReadingStatus ) async throws -> LibraryWriteOutcome func moveEntry(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swiftindex da2d44c1..5cbd8226 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.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 c3c77f32..117d4bdf 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift@@ -2,50 +2,11 @@ import Foundation import OSLog import SwiftData -/// Runtime opening of the live library, classified then acted on.-///-/// Every store the app can reach is recorded at V15 or above, and the conversion-/// left is the one `.lightweight` stage `ModelContainer.init` runs — V15 → V16:-/// the sidecar, the V3 reader, the completion pass and every stage below V15 are-/// retired (Decision 1; Q2 of `drop-superseded-columns`, Q18 of-/// `work-and-reading-status`, Q60 of `series-and-related-works`, Q15 of-/// `work-creators`, Q48 of `place-extraction`, and `work-thumbnails`). What-/// survives is the readiness contract.-/// The app validates with `LibraryValidator` and clears residual evidence; the-/// marker it publishes contains `"16"` (`extensionOpenableMarkerVersion`), the-/// only version the extension opens (Q14).-///-/// An *empty* store is marked ready as soon as it exists, so the app either opens-/// a ready library or throws — there is no third state for the reader to resolve.-/// It is marked at `"16"` directly: there is nothing in it to bring forward (Q26).-///-/// **There is one lagging generation: `"15"`.** V16 **removes** one `Site`-/// column, `junkSuffixRule`, and adds nothing, and the whole of that is the-/// lightweight stage `ModelContainer` runs — a removed column needs no-/// attribute default and no pass to fill one — so the `.markerLagging` arm-/// opens, validates, and publishes `"16"`, with no data pass and no-/// reconciler. The digit matters more for a removing stage than it did for the-/// adding ones, because it is what keeps the *extension* out of a conversion it-/// must never run (Q3), and a concurrent share-sheet open part-way through a-/// removal is destructive rather than merely early: `openContainer` passes the-/// migration plan for both roles, and only the marker check stops that-/// invocation from performing it.-///-/// `"14"` is **gone** rather than kept beside `"15"`, on the substitution the-/// schema-migration note allows once the population has passed the old digit.-/// Like the four substitutions before it and unlike the `"10"` one, which ran a-/// commit ahead of its verification (Q32 and then Q60 of-/// `series-and-related-works`), this one is behind it: the owner confirmed every-/// device on marker `"15"` on 2026-09-21 before the freeze-/// (`remove-article-mode` Q10), so the marker set and-/// `AsterismV16MigrationPlan`'s `[V15, V16]` have never disagreed at this-/// generation.-///-/// A store found on any other digit is refused, naming it, and the recovery is-/// the backup archive, exactly as for a store recorded below V5. The two roles-/// differ in what they accept and in what they may do about it: the app opens-/// `"15"` and `"16"` (`appOpenableMarkerVersions`) and may create, convert and-/// mark a store; the extension opens `"16"` only and writes nothing.+/// Opens the live V17 library after classifying the fixed-path store.+/// The app accepts markers `"16"` and `"17"`; the extension accepts only `"17"`.+/// A V16 store migrates through one lightweight stage that adds two optional+/// Work blobs. The app validates before publishing `"17"`, so the extension+/// never performs a conversion while holding its shared lock. public extension LibraryRepository { /// The result of evaluating the live library's fixed-path state under an /// exclusive lease.@@ -53,7 +14,7 @@ public extension LibraryRepository { case ready(LibraryRecordCounts) } - /// Extension-only readiness result. The extension opens only a `"16"` marker.+ /// Extension-only readiness result. The extension opens only a `"17"` marker. enum ExtensionResult: Equatable, Sendable { case ready(LibraryRecordCounts) }@@ -201,31 +162,21 @@ public extension LibraryRepository { case .markerLagging(let generation): // open (which drops the junk-suffix column) → validate →- // publish `"16"`.+ // publish `"17"`. //- // **No data pass and no reconciler.** The `"7"` arm ran- // `V8PopulationPass` and `MembershipReconciler` because V8 *added*- // tables and blobs that something had to fill; V16 **removes** one- // column, so there is nothing to fill and nothing to convert — the- // stage drops it inside `ModelContainer.init` and the value it held- // had no reader left before the column went. The launch reconcile- // runs moments later on the same store for anything else.- //- // **Validation is the gate, and the marker goes after it.**- // There is no pass to certify itself with, so what certifies the- // conversion is the store validating: a throw here leaves `"15"` on- // disk, fails the open, and the next open re-enters this arm over a- // store the stage has already converted — which is safe, because- // removing a column that is already gone is a no-op.+ // The V16 → V17 lightweight stage adds two optional Work blobs.+ // It needs no data pass: a converted row reads nil in both columns.+ // Validation certifies the converted store before readiness moves;+ // a failed validation leaves `"16"` for the next app open. // // The residual evidence goes **last**, after the publish rather than // with the validation: a publish that fails on a full disk leaves- // the library at `"15"` with its historical marker and sidecar still+ // the library at `"16"` with its historical marker and sidecar still // beside it, which is the state the next open wants to find. let container = try openCertificationContainer(configuration, hooks: hooks) let context = ModelContext(container) bootstrapLogger.debug(- "Marker generation \(generation, privacy: .public) is lagging; certifying the V16 conversion")+ "Marker generation \(generation, privacy: .public) is lagging; certifying the V17 conversion") let diagnostics = try validateStore(context: context) try publishReadiness(at: configuration.readinessMarkerURL) clearResidualEvidence(configuration)@@ -425,38 +376,15 @@ extension LibraryRepository { var quarantined: [String: LibraryValidationError] { diagnostics.quarantineMap() } } - /// Opens the fixed-path store with the live V16 schema and- /// `AsterismV16MigrationPlan`, which declares `[V15, V16]` and one- /// lightweight stage: this call is where an installed V15 library is- /// converted, and the only place it happens.- ///- /// **The stage removes exactly one column.** V15 → V16 drops- /// `Site.junkSuffixRule` and adds nothing at all; a removed column has no- /// attribute default to write and nothing for a data pass to fill- /// (Req 4.3). It is the second removing stage in the project's history,- /// after V8 → V9.- /// The V14 → V15 stage retired with its snapshot once every device was- /// confirmed on marker `"15"`, as the V13 → V14 stage did before it- /// (`update-schedule`), the V12 → V13 one before that (`work-thumbnails`),- /// the V11 → V12 one before that (Q48 of `place-extraction`), the- /// V10 → V11 one before that (Q15) and the V9 → V10 one before that (Q60).- ///- /// A store recorded below V15 has no stage and is refused here — `classify`- /// already refuses one before any container is constructed (Req 2.9,- /// Decision 1 of `retire-migration-chain`), so the refusal is a second- /// closed door rather than a new one.- ///- /// Mirroring defaults to off, and every certification-phase caller takes the- /// default: the store is opened `.none` for creation and validation, and only- /// the app's post-certification open passes `.private` (Q35). The share extension never passes it at all (Req 5.1).- // `public` so the app target can open a store for the isolated UI-test- // bootstrap of the composed teaching surface (Req 7.3); production opens via- // `openForApp` (task 25's runtime switch).+ /// Opens the fixed-path store under V17 and the `[V16, V17]` migration+ /// plan. The single lightweight stage adds two optional Work blob columns;+ /// existing rows read nil in both, with no data pass.+ /// The classifier refuses older markers before this constructs a container. public static func openContainer( at storeURL: URL, mirroring cloudKitDatabase: ModelConfiguration.CloudKitDatabase = .none ) throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let storeConfiguration = ModelConfiguration( // **Frozen persisted state (Req 3.5).** This names the store // configuration *inside* the container, not the file — `url:` below is@@ -470,7 +398,7 @@ extension LibraryRepository { ) return try ModelContainer( for: schema,- migrationPlan: AsterismV16MigrationPlan.self,+ migrationPlan: AsterismV17MigrationPlan.self, configurations: [storeConfiguration] ) }@@ -614,7 +542,7 @@ extension LibraryRepository { /// (`work-thumbnails` `prerequisites.md`), on `"14"` on 2026-09-15 /// (`update-schedule` `prerequisites.md`) and on `"15"` on 2026-09-21 /// (`remove-article-mode` Q10), so the set moved to- /// `["15", "16"]` and `AsterismV16MigrationPlan` shipped as `[V15, V16]` in+ /// `["15", "16"]` and `AsterismV17MigrationPlan` shipped as `[V15, V16]` in /// the same commit. A `"14"` marker is refused by a build that could not /// convert its store anyway; the recovery is the backup archive, as for any /// unrecognised marker.@@ -623,16 +551,16 @@ extension LibraryRepository { ] /// The one lagging generation the app still opens: a library certified by a- /// V15 build, which `.markerLagging` converts and re-marks. Frozen persisted+ /// V16 build, which `.markerLagging` converts and re-marks. Frozen persisted /// state, like its successor below.- static let laggingOpenableMarkerVersion = "15"+ static let laggingOpenableMarkerVersion = "16" /// The only version the **extension** opens, and the one `publishReadiness` /// writes (Q14). Frozen persisted state — these are the bytes on disk in an /// 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 = "16"+ static let extensionOpenableMarkerVersion = "17" // 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+BootstrapState.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BootstrapState.swiftindex 2507f708..a5566f77 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BootstrapState.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BootstrapState.swift@@ -93,8 +93,8 @@ extension LibraryRepository { /// overlapping evidence resolvable at all (Q15). The rows, in order: /// /// 1. a positively below-V5 recorded version (Req 2.9)- /// 2. marker `"16"` and a store present (Req 2.2)- /// 3. marker `"15"` — a generation the app still opens — and a store present+ /// 2. marker `"17"` and a store present (Req 2.2)+ /// 3. marker `"16"` — a generation the app still opens — and a store present /// 4. any evidence with no store present (Req 2.6) /// 5. a store present with no readiness marker of any generation (Req 2.4) /// 6. nothing on disk (Req 2.5)@@ -115,7 +115,7 @@ extension LibraryRepository { /// `"10"` substitution that confirmation was still outstanding, so /// `AsterismV11MigrationPlan` kept the V9 → V10 stage the marker set no /// longer reached until the follow-up retired it (Q60). At the five- /// substitutions since it came first, so `AsterismV16MigrationPlan` ships+ /// substitutions since it came first, so `AsterismV17MigrationPlan` ships /// as `[V15, V16]` in the same commit. A digit outside the set still falls /// to the last row and is refused naming itself, with the backup archive as /// the recovery.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swiftnew file mode 100644index 00000000..607e1451--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swift@@ -0,0 +1,117 @@+import Foundation++public struct CatchUpSheetState: Sendable {+ public let work: WorkSnapshot+ public let record: CatchUpRecord+ public let progress: CatchUpProgress++ public init(work: WorkSnapshot, record: CatchUpRecord, progress: CatchUpProgress) {+ self.work = work+ self.record = record+ self.progress = progress+ }+}++public enum OverrideEdit: Equatable, Sendable {+ case unchanged+ case set(Int)+ case clear+}++public struct CatchUpDraft: Equatable, Sendable {+ public let latest: Int?+ public let countsUp: Bool+ public let override: OverrideEdit++ public init(latest: Int?, countsUp: Bool, override: OverrideEdit) {+ self.latest = latest+ self.countsUp = countsUp+ self.override = override+ }+}++extension LibraryRepository {+ /// Opens the sheet from one fresh, coherent read rather than a cached card.+ public func catchUpSheetState(+ workID: UUID, day: CivilDay, calendar: Calendar+ ) async throws -> CatchUpSheetState {+ try await withLockedContext(mode: .shared, operation: "reading catch-up progress") { context in+ let group = try Self.fetchWorkGroup(id: workID, context: context)+ let work = try Self.snapshot(+ group, canonicalWorkIDs: [:],+ types: Self.workTypeDirectory(context: context),+ series: Self.seriesDirectory(context: context), credits: .empty)+ return CatchUpSheetState(+ work: work, record: work.catchUp,+ progress: CatchUpProgress.build(work: work, day: day, calendar: calendar))+ }+ }++ /// A Save confirms the shown number even if only the override or switch moved.+ public func commitCatchUpProgress(+ id: UUID, basis: CatchUpRecord, draft: CatchUpDraft+ ) async throws -> LibraryWriteOutcome {+ func valid(_ number: Int?) -> Bool { number.map { (0...9_999).contains($0) } ?? true }+ let overrideNumber: Int?+ if case .set(let number) = draft.override { overrideNumber = number }+ else { overrideNumber = nil }+ guard valid(draft.latest), valid(overrideNumber) else {+ throw LibraryRepositoryError.invalidInput(+ operation: "saving catch-up progress", reason: "chapter number must be from 0 to 9,999")+ }+ return try await withLockedContext(+ mode: .exclusive, operation: "saving catch-up progress"+ ) { context in+ let group = try self.resolveWorkWriteTarget(id: id, context: context)+ if let refusal = Self.tornRefusal(group) { return refusal }+ guard CatchUpFold.elect(group.rows.map(\.catchUpRecord)) == basis else {+ return .conflict(.recordChanged(recordID: id))+ }+ let timestamp = MillisecondInstant.quantize(clock.now())+ let moment = MillisecondInstant.milliseconds(timestamp)+ var record = basis+ record.confirmation = CatchUpConfirmation(+ latest: draft.latest, confirmedAtMilliseconds: moment,+ countsUp: draft.countsUp, isEstimate: false)+ switch draft.override {+ case .unchanged: break+ case .set(let number): record.override = .value(number, atMilliseconds: moment)+ case .clear: record.override = .cleared(atMilliseconds: moment)+ }+ CatchUpWriter.apply(record, to: group.rows)+ for row in group.rows { row.modifiedAt = timestamp }+ do { try saveStrategy.save(context) }+ catch {+ throw LibraryRepositoryError.libraryUnavailable(+ operation: "atomically saving catch-up progress", reason: String(describing: error))+ }+ return .committed+ }+ }++ /// The banner changes only the reader's status after checking its visible basis.+ public func setReadingStatus(+ id: UUID, expected: ReadingStatus, to status: ReadingStatus+ ) async throws -> LibraryWriteOutcome {+ try await withLockedContext(+ mode: .exclusive, operation: "setting reading status"+ ) { context in+ let group = try self.resolveWorkWriteTarget(id: id, context: context)+ if let refusal = Self.tornRefusal(group) { return refusal }+ guard group.carrier.readingStatus == expected else {+ return .conflict(.recordChanged(recordID: id))+ }+ let timestamp = MillisecondInstant.quantize(clock.now())+ for row in group.rows {+ row.readingStatus = status+ row.modifiedAt = timestamp+ }+ do { try saveStrategy.save(context) }+ catch {+ throw LibraryRepositoryError.libraryUnavailable(+ operation: "atomically setting reading status", reason: String(describing: error))+ }+ return .committed+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swiftindex eb6bc699..f8753494 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift@@ -17,13 +17,13 @@ public struct InterruptedImportReport: Codable, Sendable, Equatable { } } -/// The one field the off-host pre-pass rewrites. `BackupV15Membership`'s+/// The one field the off-host pre-pass rewrites. `BackupV16Membership`'s /// properties are `let`, so the value is rebuilt through the memberwise /// initialiser rather than mutated — which is what keeps the record a value the /// commit path can treat as verbatim.-extension BackupV15Membership {- fileprivate func withWorkURLString(_ value: String?) -> BackupV15Membership {- BackupV15Membership(+extension BackupV16Membership {+ fileprivate func withWorkURLString(_ value: String?) -> BackupV16Membership {+ BackupV16Membership( id: id, workID: workID, hostname: hostname, createdAt: createdAt, urlIdentity: urlIdentity, urlIdentityState: urlIdentityState, urlIdentityRuleID: urlIdentityRuleID, workURLString: value)@@ -200,7 +200,7 @@ extension LibraryRepository { // (Decision 10), because the archive's own rules are part of what makes // its designation legal: a `.taught` restore is legal precisely because // the active title rule arrives in this same step.- var matchedRecords: [BackupV15Site] = []+ var matchedRecords: [BackupV16Site] = [] for record in payload.sites { if sitesByHostname[record.hostname] != nil { matchedRecords.append(record)@@ -491,7 +491,7 @@ extension LibraryRepository { /// Every write is guarded by a comparison, so re-importing the same archive /// dirties nothing — the same property `SiteReconciler.applyUnion` keeps. internal static func applyDesignation(- _ record: BackupV15Site,+ _ record: BackupV16Site, to site: Site, patterns: [TitlePattern], urlRules: [URLRulePattern]@@ -538,7 +538,7 @@ extension LibraryRepository { /// Work's site presence either, and a group skipped as torn must not be /// half-updated through its memberships. private static func commitWorks(- _ records: [BackupV15Work],+ _ records: [BackupV16Work], into workRows: inout [UUID: [Work]], types: WorkTypeDirectory, context: ModelContext,@@ -560,6 +560,11 @@ extension LibraryRepository { // nothing is dropped, so there is nothing to report either. let thumbnail: ArchiveThumbnail if let rows = workRows[record.id], !rows.isEmpty {+ // Progress is a separate timestamped fact. Fold it even when+ // authored metadata is torn or newer than this archive.+ let elected = CatchUpFold.elect(+ rows.map(\.catchUpRecord) + [record.catchUpRecord])+ CatchUpWriter.apply(elected, to: rows) guard let group = workGroup(id: record.id, rows: rows, types: types), !group.isTorn else {@@ -633,7 +638,7 @@ extension LibraryRepository { /// Inserting stays unconditional: a row the library does not hold cannot be /// regressed, and the upsert's posture is to add (Req 4.1). private static func commitMemberships(- _ records: [BackupV15Membership],+ _ records: [BackupV16Membership], workRows: [UUID: [Work]], workTargets: [UUID: Work], appliedWorkIDs: Set<UUID>,@@ -748,10 +753,10 @@ extension LibraryRepository { /// [1.7]: ../../../../specs/wrong-host-work-url-heal/requirements.md#17 /// [1.8]: ../../../../specs/wrong-host-work-url-heal/requirements.md#18 internal static func normalizedMemberships(- _ records: [BackupV15Membership],+ _ records: [BackupV16Membership], existingMembershipIDs: Set<UUID>, appliedWorkIDs: Set<UUID>- ) -> [BackupV15Membership] {+ ) -> [BackupV16Membership] { var indicesByWork: [UUID: [Int]] = [:] for (index, record) in records.enumerated() { guard let workID = record.workID else { continue }@@ -814,7 +819,7 @@ extension LibraryRepository { /// library — the insert branch, which is unconditional, or the update /// branch, which is gated on the Work's record having been applied. private static func willWriteMembership(- _ record: BackupV15Membership,+ _ record: BackupV16Membership, existingMembershipIDs: Set<UUID>, appliedWorkIDs: Set<UUID> ) -> Bool {@@ -838,7 +843,7 @@ extension LibraryRepository { /// re-importing the same archive must write the same values back, which is /// what makes a repeated import change nothing (Req 13.3). private static func commitSeries(- _ records: [BackupV15Series],+ _ records: [BackupV16Series], context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy@@ -879,7 +884,7 @@ extension LibraryRepository { /// is inserted as it stands: an unresolved link is the tolerated state of /// Req 11.2, and the reader's to remove. private static func commitLinks(- _ records: [BackupV15Link],+ _ records: [BackupV16Link], context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy@@ -934,7 +939,7 @@ extension LibraryRepository { /// A credit naming a work, creator or role this library does not hold is /// inserted as it stands (Req 9.5, 10.2), exactly as an unresolved link is. private static func commitCredits(- _ records: [BackupV15Credit],+ _ records: [BackupV16Credit], context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy@@ -981,7 +986,7 @@ extension LibraryRepository { /// reconciler's latest-wins rule reads — so an older archive cannot undo a /// newer dismissal, and re-importing the same archive writes nothing. private static func commitDistinctPairs(- _ records: [BackupV15DistinctPair],+ _ records: [BackupV16DistinctPair], context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy@@ -1021,7 +1026,7 @@ extension LibraryRepository { /// the materializers so an inserted record and an updated one cannot drift /// apart. Identity, hostname, and `createdAt` are set at construction. internal static func apply(- _ record: BackupV15Work, to work: Work, thumbnail: ArchiveThumbnail+ _ record: BackupV16Work, to work: Work, thumbnail: ArchiveThumbnail ) { // Every scalar below is value-guarded (T-2334): re-importing an archive // the library already matches must write nothing, so a re-export mirrors@@ -1128,7 +1133,7 @@ extension LibraryRepository { /// The mutable half of an archive membership record. Identity, hostname and /// `createdAt` are set at construction, so what an update moves is the /// site-specific content: the URL identity triple and the confirmed Work URL.- internal static func apply(_ record: BackupV15Membership, to membership: WorkSiteMembership) {+ internal static func apply(_ record: BackupV16Membership, to membership: WorkSiteMembership) { // Value-guarded (T-2334): a re-import of a record the row already // matches must write nothing. if membership.hostname != record.hostname { membership.hostname = record.hostname }@@ -1149,7 +1154,7 @@ extension LibraryRepository { if membership.workID != workID { membership.workID = workID } } - internal static func apply(_ record: BackupV15Entry, to entry: Entry) {+ internal static func apply(_ record: BackupV16Entry, to entry: Entry) { // Value-guarded (T-2334): a re-import of a record the row already // matches must write nothing. if entry.captureTitle != record.captureTitle { entry.captureTitle = record.captureTitle }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swiftindex 41b18493..648ae6df 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift@@ -767,6 +767,7 @@ extension LibraryRepository { return (.invalidated(reason: "The chosen copy is not one of this set's."), [], nil) } let allRows = rowsByID.values.flatMap { $0 }+ let electedCatchUp = CatchUpFold.elect(allRows.map(\.catchUpRecord)) let types = try Self.workTypeDirectory(context: context) guard let carrier = GroupOrdering.sortedWorkRows(allRows).first( where: { GroupOrdering.authoredContent(of: $0, types: types) == chosenVariant.content })@@ -888,6 +889,7 @@ extension LibraryRepository { let losers = set.members.dropFirst().map(\.id) let losingRows = losers.flatMap { rowsByID[$0] ?? [] } let survivors = GroupOrdering.sortedWorkRows(survivorRows)+ CatchUpWriter.apply(electedCatchUp, to: survivors) DuplicateReconciler.repointEntries(from: losingRows, to: survivors) // The same collapse's other half (Req 8.4, 5.7): the losers' site // memberships go with them and every distinct pair naming one re-points
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swiftindex 26ed46a0..34bab581 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift@@ -95,7 +95,7 @@ public struct InterruptedEmptyReport: Codable, Sendable, Equatable { /// capture nothing but the model type they were built for. internal struct EmptyLibraryEntity: Sendable { /// The entity name, which is what the contract test compares with- /// `AsterismSchemaV16.models` and what the log line carries.+ /// `AsterismSchemaV17.models` and what the log line carries. let name: String /// Deletes up to one chunk and saves it, returning how many rows went — /// rows the chunk's `prepare` hook took with them included. Zero means the@@ -133,7 +133,7 @@ extension LibraryRepository { /// The deletion order, and the **single place the entity set is written** /// (design, Deletion phases). `ModelContractTests` compares its names with- /// `AsterismSchemaV16.models`, so a schema that gains an entity this pass+ /// `AsterismSchemaV17.models`, so a schema that gains an entity this pass /// does not delete fails the build rather than leaving rows behind. /// /// Children before parents. The order buys two things beyond Req 3.3: every
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swiftindex 24641610..0d52df68 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift@@ -188,7 +188,7 @@ extension LibraryRepository { if let group { // The group's carrier content, so a split work presents the same // title in the export as on its own screen (Req 1.9).- // An **empty** series directory, for `mapV15WorkRecord`'s+ // An **empty** series directory, for `mapV16WorkRecord`'s // reason: the two fields read off this snapshot are the title // and the type label, and the directory only ever fills // `series` — the membership label, which an entry block does not
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swiftindex 98c7d7f9..208f1ac1 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift@@ -410,6 +410,7 @@ extension LibraryRepository { .values .map { try snapshot($0) } .sorted(by: entryActivityOrder)+ let catchUp = CatchUpFold.elect(group.rows.map(\.catchUpRecord)) guard group.isSplit else { return WorkSnapshot( id: base.id, displayTitle: base.displayTitle,@@ -423,7 +424,8 @@ extension LibraryRepository { membership: base.membership, series: base.series, credits: base.credits, thumbnail: base.thumbnail,- releaseDays: base.releaseDays, releaseDaysRaw: base.releaseDaysRaw)+ releaseDays: base.releaseDays, releaseDaysRaw: base.releaseDaysRaw,+ catchUp: catchUp) } // The carrier's assignment, like every other authored field of a split // group: the row holding the content the group presents is the row whose@@ -478,6 +480,7 @@ extension LibraryRepository { // (`update-schedule` Req 6.2): a group appears once in a releases // section, presenting the days of the row whose content it presents. releaseDays: carried.releaseDays,- releaseDaysRaw: carried.releaseDaysRaw)+ releaseDaysRaw: carried.releaseDaysRaw,+ catchUp: catchUp) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swiftindex a11c2c16..551b72c1 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift@@ -161,6 +161,14 @@ extension LibraryRepository { // MARK: - Work + /// Narrow progress/status actions have no authored basis. They may act on+ /// the addressed UUID group only; a collapsed ID must be reopened first.+ internal func resolveWorkWriteTarget(+ id: UUID, context: ModelContext+ ) throws -> WorkGroup {+ try Self.fetchWorkGroup(id: id, context: context)+ }+ internal func resolveWorkWriteTarget( id: UUID, basis: WorkEditBasis, context: ModelContext ) throws -> ResolvedWriteTarget<WorkGroup> {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swiftindex bf4d1f25..11759d78 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift@@ -440,6 +440,8 @@ extension LibraryRepository { return .invalidated(reason: Self.tornRefusalReason(torn.id)) } let target = targetGroup.representative+ let electedCatchUp = CatchUpFold.elect(+ (sourceGroup.rows + targetGroup.rows).map(\.catchUpRecord)) // **Req 4.5, before any mutation.** Every hostname either Work is on // is checked against the quarantine map, and a quarantined one@@ -558,6 +560,7 @@ extension LibraryRepository { } row.modifiedAt = timestamp }+ CatchUpWriter.apply(electedCatchUp, to: targetGroup.rows) // **The union of both Works' memberships** (Req 4.2), and the // dismissal re-point that goes with it (Req 5.7, Q32) — one call,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex 03a3aa6d..18a57912 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -1367,7 +1367,7 @@ public actor LibraryRepository { } public func updateWork(- id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft+ id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar ) async throws -> LibraryWriteOutcome { guard !draft.displayTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw LibraryRepositoryError.invalidInput(operation: "updating Work", reason: "display title is blank")@@ -1419,6 +1419,29 @@ public actor LibraryRepository { { return .conflict(conflict) }+ // Rebase under the values still stored, before the editor replaces+ // the status or schedule. A raw spelling change alone is not a+ // schedule change, and a work with no latest has nothing to rebase.+ let stored = group.carrier+ let storedRecord = CatchUpFold.elect(group.rows.map(\.catchUpRecord))+ let crossesOngoing = (stored.workStatus == .ongoing) != (draft.workStatus == .ongoing)+ let changesDays = stored.releaseDays != ReleaseDay.canonical(draft.releaseDays)+ if storedRecord.latest != nil && (crossesOngoing || changesDays) {+ let workID = group.id+ let entryRows = try context.fetch(FetchDescriptor<Entry>(+ predicate: #Predicate<Entry> { $0.work?.id == workID }))+ let canonicalWorkIDs = try Self.canonicalWorkIDs(+ normalising: entryRows, context: context)+ let notes = try NumberedNote.from(+ Self.entryGroups(entryRows, canonicalWorkIDs: canonicalWorkIDs)+ .values.map { try Self.snapshot($0) })+ if let rebased = CatchUpProgress.rebased(+ record: storedRecord, notes: notes, releaseDays: stored.releaseDays,+ workStatus: stored.workStatus, now: timestamp, calendar: calendar)+ {+ CatchUpWriter.apply(rebased, to: group.rows)+ }+ } for work in group.rows { if work.displayTitle != draft.displayTitle { work.titleProvenance = .manual } work.displayTitle = draft.displayTitle@@ -1771,7 +1794,7 @@ public actor LibraryRepository { // The four `map*Record` mappers stood here — `Entry`/`Work`/`Site`/ // `TitlePattern` to the V2 `*Record` structs, for the snapshot // `validateStore` validated. They went with it; the live export path has its- // own `map*Record` family in `BackupArchiveProjection`, over `BackupV15Entry`+ // own `map*Record` family in `BackupArchiveProjection`, over `BackupV16Entry` // and friends, and never used these. internal func withLockedContext<Value: Sendable>(@@ -2095,7 +2118,8 @@ public actor LibraryRepository { // beside it so the editor can tell a set that merely dropped an // unknown spelling from one the reader left alone. releaseDays: work.releaseDays,- releaseDaysRaw: work.releaseDaysRaw+ releaseDaysRaw: work.releaseDaysRaw,+ catchUp: work.catchUpRecord ) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swiftindex 10b6b21b..bddf385c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift@@ -84,6 +84,9 @@ public enum LibraryWriteOutcome: Sendable, Equatable { /// Why a write refused. public enum WriteConflict: Sendable, Equatable {+ /// A narrow action's expected progress or reading status changed since it was shown.+ case recordChanged(recordID: UUID)+ /// The addressed logical record holds differing authored copies, so the /// write would overwrite a variant the reader has never seen (Req 2.8, Q35). /// Resolution is the only way in.@@ -135,7 +138,8 @@ public enum WriteConflict: Sendable, Equatable { /// The record the write addressed, whether or not it still exists. public var recordID: UUID { switch self {- case .torn(let recordID, _), .survivorDiverged(let recordID, _),+ case .recordChanged(let recordID), .torn(let recordID, _),+ .survivorDiverged(let recordID, _), .disclosureStale(let recordID, _), .seriesMissing(let recordID, _), .creatorMissing(let recordID, _), .roleMissing(let recordID, _): recordID
diff --git a/Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swiftindex 252c47ed..cb2dfc69 100644--- a/Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swift@@ -226,6 +226,13 @@ extension LibraryRepository { ordinal % Self.m4FixtureReleaseDayTable.count] } else if Self.isM4FixtureCatchUpIndex(index) { work.readingStatus = .catchingUp+ let confirmedAt = Date(timeIntervalSince1970: -86_400)+ CatchUpFixtureWriter.apply(+ latest: 100 + index / Self.m4FixtureCatchUpStride,+ confirmedAt: confirmedAt,+ override: .value(+ 5, atMilliseconds: MillisecondInstant.milliseconds(confirmedAt)),+ to: [work]) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swiftindex 362d0228..04253670 100644--- a/Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swift@@ -359,7 +359,7 @@ enum MembershipReconciler { /// alone lands one ULP away from the same instant built through /// `MillisecondInstant`, and the archive's date encoding quantizes on the way /// out — so an unquantized `createdAt` decodes back as a *different* `Date`- /// and `BackupV15Exporter`'s decode-validation refuses the file it just wrote.+ /// and `BackupV16Exporter`'s decode-validation refuses the file it just wrote. /// A library holding a minted membership could not be backed up at all /// ([4.2](../../../../specs/wrong-host-work-url-heal/requirements.md#42)). /// The value stays a pure function of stored content, so two devices healing
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Models.swift b/Packages/AsterismCore/Sources/AsterismCore/Models.swiftindex bab97936..169562ac 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Models.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Models.swift@@ -1,66 +1,66 @@ import Foundation import SwiftData -// The live model classes are V16's, nested inside `AsterismSchemaV16`+// The live model classes are V16's, nested inside `AsterismSchemaV17` // (Decision 6, Q20). Top-level typealiases keep every call site (`Entry`, // `Site`, …) unchanged. //-// The nesting is what makes the frozen `AsterismSchemaV15` snapshot possible+// The nesting is what makes the frozen `AsterismSchemaV17` snapshot possible // beside the live one: both carry nested classes with the same SwiftData entity // names, which is legal only while there is exactly one // *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 = AsterismSchemaV16.Entry-public typealias Work = AsterismSchemaV16.Work-public typealias Site = AsterismSchemaV16.Site-public typealias TitlePattern = AsterismSchemaV16.TitlePattern-public typealias URLRulePattern = AsterismSchemaV16.URLRulePattern-public typealias WorkTypeEntity = AsterismSchemaV16.WorkTypeEntity+public typealias Entry = AsterismSchemaV17.Entry+public typealias Work = AsterismSchemaV17.Work+public typealias Site = AsterismSchemaV17.Site+public typealias TitlePattern = AsterismSchemaV17.TitlePattern+public typealias URLRulePattern = AsterismSchemaV17.URLRulePattern+public typealias WorkTypeEntity = AsterismSchemaV17.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 = AsterismSchemaV16.WorkSiteMembership+public typealias WorkSiteMembership = AsterismSchemaV17.WorkSiteMembership /// V8: a reader's "not the same work" over an unordered pair of Works (Q20).-public typealias WorkDistinctPair = AsterismSchemaV16.WorkDistinctPair+public typealias WorkDistinctPair = AsterismSchemaV17.WorkDistinctPair /// V11: a reader-named, ordered collection a Work belongs to at most once /// (`series-and-related-works` Decision 1).-public typealias Series = AsterismSchemaV16.Series+public typealias Series = AsterismSchemaV17.Series /// V11: an undirected, typed connection between two distinct Works /// (`series-and-related-works` Decision 5).-public typealias WorkLink = AsterismSchemaV16.WorkLink+public typealias WorkLink = AsterismSchemaV17.WorkLink /// V12: a person a work is credited to, a reader-managed directory record /// (`work-creators` Decision 2).-public typealias Creator = AsterismSchemaV16.Creator+public typealias Creator = AsterismSchemaV17.Creator /// V12: one entry in the ordered role list credits reference by identity /// (`work-creators` Decision 1).-public typealias CreatorRole = AsterismSchemaV16.CreatorRole+public typealias CreatorRole = AsterismSchemaV17.CreatorRole /// V12: one work-and-creator pairing, carrying the roles that creator holds on /// that work (`work-creators` Decision 6).-public typealias WorkCredit = AsterismSchemaV16.WorkCredit+public typealias WorkCredit = AsterismSchemaV17.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 = AsterismSchemaV16.Character-public typealias CharacterSuppression = AsterismSchemaV16.CharacterSuppression+public typealias CharacterRecord = AsterismSchemaV17.Character+public typealias CharacterSuppression = AsterismSchemaV17.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 = AsterismSchemaV16.Place+public typealias Place = AsterismSchemaV17.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 = AsterismSchemaV16.PlaceSuppression+public typealias PlaceSuppression = AsterismSchemaV17.PlaceSuppression /// The presentation-enum tolerance policy for the **model accessors**, in one /// place (Q2). /// /// Not the only coercion in the codebase, and not meant to be: the archive /// paths spell their own `?? .default` — `WorkTypeDirectory`,-/// `ArchiveRecordBuilders`, `BackupV15Types`, `BackupArchiveProjection` — each+/// `ArchiveRecordBuilders`, `BackupV16Types`, `BackupArchiveProjection` — each /// answering what *that* wire may say rather than what a stored column may /// hold. Those are deliberately separate policies, not omissions from this one. ///@@ -114,9 +114,9 @@ internal enum ToleratedEnum { /// The one place a JSON blob column is turned into a value and back. ///-/// Three model properties store a value as JSON bytes — `Entry.citationsData`,-/// `TitlePattern.definitionData` and `URLRulePattern.definitionData` — and all-/// three had their own `JSONDecoder().decode(...)` / `JSONEncoder().encode(...)`+/// Model properties store closed values as JSON bytes. Citations, pattern+/// definitions and catch-up progress all use the same coder options.+/// The original three had their own `JSONDecoder().decode(...)` / `JSONEncoder().encode(...)` /// pair. One pair means a coder option can only ever be set for all three, which /// is the property that matters: two of these blobs are compared for equality /// against bytes another writer produced.@@ -129,11 +129,13 @@ enum JSONBlob { } static func encode(_ value: some Encodable) throws -> Data {- try JSONEncoder().encode(value)+ let encoder = JSONEncoder()+ encoder.outputFormatting = .sortedKeys+ return try encoder.encode(value) } } -extension AsterismSchemaV16 {+extension AsterismSchemaV17 { @Model public final class Entry {@@ -418,6 +420,9 @@ public final class Work { /// **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? = nil+ public var lastChapterOverrideData: Data? = nil /// V14: the reader's cover for this work, as JPEG bytes /// (`work-thumbnails` Decision 2, Req 1.1). ///@@ -697,7 +702,7 @@ public final class Site { // `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` type stays in `ValueObjects.swift`, unchanged and with no- // consumer but the frozen `AsterismSchemaV15` snapshot, which is frozen by+ // consumer but the frozen `AsterismSchemaV17` snapshot, which is frozen by // reference to it (Q8). public init(hostname: String, displayName: String? = nil) {@@ -1758,7 +1763,7 @@ public final class PlaceSuppression { } } -} // extension AsterismSchemaV16+} // extension AsterismSchemaV17 /// 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/RecordRow.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swiftindex 40da0882..fa829b21 100644--- a/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift@@ -196,7 +196,7 @@ extension CharacterRecord: RecordRow { timestamp: timestamp, work: work) } - public static func make(imported record: BackupV15Character) -> CharacterRecord {+ public static func make(imported record: BackupV16Character) -> CharacterRecord { ArchiveRecordBuilders.makeCharacter(record) } @@ -238,7 +238,7 @@ extension CharacterSuppression: SuppressionRow { evidence: evidence, status: status, actionAt: actionAt) } - public static func make(imported record: BackupV15Suppression) -> CharacterSuppression {+ public static func make(imported record: BackupV16Suppression) -> CharacterSuppression { ArchiveRecordBuilders.makeSuppression(record) } @@ -296,7 +296,7 @@ extension Place: RecordRow { timestamp: timestamp, workID: work?.id ?? UUID()) } - public static func make(imported record: BackupV15Place) -> Place {+ public static func make(imported record: BackupV16Place) -> Place { ArchiveRecordBuilders.makePlace(record) } @@ -349,7 +349,7 @@ extension PlaceSuppression: SuppressionRow { evidence: evidence, status: status, actionAt: actionAt) } - public static func make(imported record: BackupV15PlaceSuppression) -> PlaceSuppression {+ public static func make(imported record: BackupV16PlaceSuppression) -> PlaceSuppression { ArchiveRecordBuilders.makePlaceSuppression(record) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RepositoryClock.swift b/Packages/AsterismCore/Sources/AsterismCore/RepositoryClock.swiftindex 4599f486..9ddfcda2 100644--- a/Packages/AsterismCore/Sources/AsterismCore/RepositoryClock.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/RepositoryClock.swift@@ -1,14 +1,21 @@ import Foundation public enum MillisecondInstant {- public static func quantize(_ date: Date) -> Date {+ public static func milliseconds(_ date: Date) -> Int64 { let scaled = date.timeIntervalSince1970 * 1_000 // Date stores binary floating-point seconds. Values produced from an // exact millisecond can land infinitesimally below its integer after // multiplication; snap only that representation noise before floor. let nearestInteger = scaled.rounded()- let normalized = abs(scaled - nearestInteger) < 0.000_001 ? nearestInteger : floor(scaled)- return Date(timeIntervalSince1970: normalized / 1_000)+ return Int64(abs(scaled - nearestInteger) < 0.000_001 ? nearestInteger : floor(scaled))+ }++ public static func date(fromMilliseconds milliseconds: Int64) -> Date {+ Date(timeIntervalSince1970: Double(milliseconds) / 1_000)+ }++ public static func quantize(_ date: Date) -> Date {+ Self.date(fromMilliseconds: milliseconds(date)) } public static func isQuantized(_ date: Date) -> Bool {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swiftindex 681be7ee..87634255 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift@@ -186,6 +186,8 @@ public struct WorkSnapshot: Equatable, Sendable { /// leave the unknown value in place forever /// ([1.6](../../../../specs/update-schedule/requirements.md#1.6)). public let releaseDaysRaw: [String]+ /// Elected progress when read from a group; pristine on value-only fixtures.+ public let catchUp: CatchUpRecord public let titleProvenance: TitleProvenance public let createdAt: Date public let modifiedAt: Date@@ -267,13 +269,15 @@ public struct WorkSnapshot: Equatable, Sendable { // canonical one so a caller that states only the days it means cannot // hand the editor a snapshot that reads as dirty the moment it loads. releaseDays: [ReleaseDay] = [],- releaseDaysRaw: [String]? = nil+ releaseDaysRaw: [String]? = nil,+ catchUp: CatchUpRecord = .pristine ) { // Both parameters stay, so no call site moves: a caller reading a row // hands over what the row holds, and a caller stating only the days it // means gets the canonical spelling of them. Only the raw list is kept // — ``releaseDays`` reads back out of it. self.releaseDaysRaw = releaseDaysRaw ?? ReleaseDay.canonical(releaseDays).map(\.rawValue)+ self.catchUp = catchUp self.thumbnail = thumbnail self.credits = credits self.workStatus = workStatus
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swiftindex 145783d9..12d8371a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift@@ -72,7 +72,7 @@ extension LibraryRepository { verdict: reloaded.verdict, releaseDays: reloaded.releaseDays, membership: reloaded.membership,- thumbnail: .set(Self.coveredWorkThumbnail())))+ thumbnail: .set(Self.coveredWorkThumbnail())), calendar: .current) if !withBytes { try await stripCoverBytes(of: covered.id) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/ThumbnailValues.swift b/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/ThumbnailValues.swiftindex 04b5d72b..c31bd44f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/ThumbnailValues.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/ThumbnailValues.swift@@ -16,7 +16,7 @@ nonisolated let thumbnailLog = Logger(subsystem: "AsterismCore", category: "Thum /// because of it. /// /// **The raw spellings are stored bytes and frozen at schema V14**-/// (`AsterismSchemaV16`'s header). They are what `Work.thumbnailShapeRaw`+/// (`AsterismSchemaV17`'s header). They are what `Work.thumbnailShapeRaw` /// holds in every installed library, so renaming a case is a schema bump. /// Reading is tolerant and writing is not, as for every enum column here: a set /// but unrecognised spelling reads as `.portrait`
diff --git a/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift b/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swiftindex 284a5e8c..4ae6fbe1 100644--- a/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift@@ -305,6 +305,9 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { public let typeDisplay: WorkTypeDisplay public let thumbnail: ThumbnailIdentity? public let releaseDays: [ReleaseDay]+ public let catchUp: CatchUpRecord+ public let numberedNotes: [NumberedNote]+ public let workStatus: WorkStatus /// Newest day first, one per day: the entry a release row names for a day is /// the same entry Today's noted section shows first for it. public let notedDays: [NotedDay]@@ -314,6 +317,7 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { public init( id: UUID, title: String, primaryHostname: String, typeDisplay: WorkTypeDisplay, thumbnail: ThumbnailIdentity?, releaseDays: [ReleaseDay], notedDays: [NotedDay],+ catchUp: CatchUpRecord, numberedNotes: [NumberedNote], workStatus: WorkStatus, primaryURL: URL? = nil ) { self.id = id@@ -323,6 +327,9 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { self.thumbnail = thumbnail self.releaseDays = releaseDays self.notedDays = notedDays+ self.catchUp = catchUp+ self.numberedNotes = numberedNotes+ self.workStatus = workStatus self.primaryURL = primaryURL } @@ -336,6 +343,9 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { thumbnail: snapshot.thumbnail, releaseDays: snapshot.releaseDays, notedDays: Self.notedDays(of: snapshot.entries, calendar: calendar),+ catchUp: snapshot.catchUp,+ numberedNotes: NumberedNote.from(snapshot.entries),+ workStatus: snapshot.workStatus, primaryURL: snapshot.primaryURL) } @@ -361,20 +371,13 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { result.append( NotedDay( day: day, chapterLine: entry.chapterTitle ?? entry.chapterSequence,- chapterNumber: chapterNumber(of: entry)))+ chapterNumber: ChapterNumber.whole(+ chapterSequence: entry.chapterSequence,+ chapterTitle: entry.chapterTitle))) } return result } - /// A single whole chapter number, or nil (see `NotedDay.chapterNumber`).- private static func chapterNumber(of entry: EntrySnapshot) -> Int? {- guard- let key = ChapterKeyDerivation.key(- chapterSequence: entry.chapterSequence, chapterTitle: entry.chapterTitle),- key.components.count == 1- else { return nil }- return key.components[0]- } } // MARK: - One day's plan@@ -478,25 +481,39 @@ public struct TodayDayPlan: Equatable, Sendable { /// One row, for a release and for a catch-up work alike: both carry the same /// second line (Q13), and the app draws them as a shelf item and a card row. ///- /// The chapter, day and release count come from the newest note **on or- /// before** the day shown, so a past day's badge never names a chapter read- /// after it. `line` keeps Q16's newest-note-overall, which is a sentence- /// about the work rather than about that day. `countsReleases` is false for- /// the releases section, which never shows the count.+ /// Progress uses R from all eligible notes and the override, and estimates+ /// E for the selected day. The release row's second line still uses the+ /// newest note on or before that day; an unknown catch-up line with R uses+ /// R and its read day instead. Release rows never show the release count. private static func row( for work: ScheduledWork, on day: CivilDay, calendar: Calendar, countsReleases: Bool ) -> ReleaseRow { let latest = work.notedDays.first { $0.day <= day }+ let progress = CatchUpProgress.build(+ record: work.catchUp, notes: work.numberedNotes,+ releaseDays: work.releaseDays, workStatus: work.workStatus,+ day: day, calendar: calendar)+ let unknownReadDay = countsReleases && progress.state == .unknown+ ? progress.readDay : nil+ let unknownLine: ReleaseRow.Line? =+ countsReleases && progress.state == .unknown && progress.lastRead != nil+ ? unknownReadDay.map {+ .lastNoted(+ chapterLine: progress.lastRead.map(String.init),+ when: RelativeDay(noted: $0, selected: day, calendar: calendar))+ }+ : nil return ReleaseRow( id: work.id, title: work.title, primaryHostname: work.primaryHostname, typeDisplay: work.typeDisplay, thumbnail: work.thumbnail,- line: line(for: work, on: day, calendar: calendar),- lastChapter: latest?.chapterNumber,- lastNotedDay: latest?.day,+ line: unknownLine ?? line(for: work, on: day, calendar: calendar),+ progress: progress, workStatus: work.workStatus,+ lastChapter: progress.lastRead,+ lastNotedDay: unknownReadDay ?? latest?.day, releasesSince: countsReleases- ? latest.flatMap {+ ? (unknownReadDay ?? latest?.day).flatMap { releaseCount(- of: work.releaseDays, after: $0.day, through: day, calendar: calendar)+ of: work.releaseDays, after: $0, through: day, calendar: calendar) } : nil, primaryURL: work.primaryURL) }@@ -569,7 +586,7 @@ public struct TodayDayPlan: Equatable, Sendable { } } -/// One work due on the day being shown.+/// One work due or being caught up on for the day being shown. public struct ReleaseRow: Equatable, Sendable, Identifiable { /// The row's second line /// ([5.2](../../../../specs/update-schedule/requirements.md#5.2)). The arm@@ -590,19 +607,25 @@ public struct ReleaseRow: Equatable, Sendable, Identifiable { public let typeDisplay: WorkTypeDisplay public let thumbnail: ThumbnailIdentity? public let line: Line- /// The chapter number of the work's newest note, where it reads as one- /// whole number.+ public let progress: CatchUpProgress+ /// The author's status for the caught-up banner's primary action.+ public let workStatus: WorkStatus+ /// The last chapter read (R): the highest eligible numbered note or the+ /// override, whichever the progress derivation elects. public let lastChapter: Int?- /// The day of the work's newest note, nil where it has none.+ /// The day named by the second line: historical note day, or r for an+ /// unknown catch-up work with a known R. public let lastNotedDay: CivilDay?- /// Release days after that note, up to and including the day being shown.- /// Nil where the work has no release days or no note.+ /// Release days after the line's day, up to and including the day shown.+ /// Nil where the work has no release days or no such day. public let releasesSince: Int? public let primaryURL: URL? public init( id: UUID, title: String, primaryHostname: String, typeDisplay: WorkTypeDisplay,- thumbnail: ThumbnailIdentity?, line: Line, lastChapter: Int? = nil,+ thumbnail: ThumbnailIdentity?, line: Line, progress: CatchUpProgress,+ workStatus: WorkStatus,+ lastChapter: Int? = nil, lastNotedDay: CivilDay? = nil, releasesSince: Int? = nil, primaryURL: URL? = nil ) { self.id = id@@ -611,14 +634,16 @@ public struct ReleaseRow: Equatable, Sendable, Identifiable { self.typeDisplay = typeDisplay self.thumbnail = thumbnail self.line = line+ self.progress = progress+ self.workStatus = workStatus self.lastChapter = lastChapter self.lastNotedDay = lastNotedDay self.releasesSince = releasesSince self.primaryURL = primaryURL } - /// The chapter after the newest note's, where that note has a whole- /// chapter number. Never guessed from anything else.+ /// The chapter after R, where R is known. Never guessed from an+ /// unnumbered note. public var nextChapter: Int? { lastChapter.map { $0 + 1 } } /// Whether the work carries a note on the day being shown.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/TodayFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/TodayFixture.swiftindex eaea3a24..fa814a45 100644--- a/Packages/AsterismCore/Sources/AsterismCore/TodayFixture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/TodayFixture.swift@@ -9,9 +9,10 @@ extension LibraryRepository { /// Moves one Entry's two reader-facing dates back to `date`, so the `today` /// UI fixture can hold a day that is not the day it was seeded on. ///- /// The rest of that fixture — three works, their release days, their- /// entries and the moves that attach them — is ordinary repository writing- /// and lives in `AppLibraryModel`. This one step cannot be: `capture` dates+ /// The fixture's original four entries and their work assignments use+ /// ordinary repository writing in `AppLibraryModel`. Three additional+ /// catch-up works carry progress without adding Recent entries.+ /// This backdating step cannot use a production path: `capture` dates /// every Entry at `clock.now()`, and no write path of ours dates one in the /// past (only the pending-capture drain carries a `capturedAt`, and that /// arrives from the spool, not from a caller). Without it the fixture's
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swiftindex 6c94e365..f413330f 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift@@ -34,7 +34,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(Set(payload.sites.map(\.hostname)) == ["present.example", "orphan.example"]) let synthesised = try #require(payload.sites.first { $0.hostname == "orphan.example" })@@ -75,11 +75,11 @@ struct BackupExportDegradedRefusalTests { #expect(await repository.diagnostics.quarantineMap()["quarantined.example"] != nil) let staging = fixture.directory.appending(path: "staging")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let result = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date())) - let decoded = try BackupV15Codec.decode(try Data(contentsOf: result.fileURL))+ let decoded = try BackupV16Codec.decode(try Data(contentsOf: result.fileURL)) #expect(decoded.payload.entries.count == 1) #expect(decoded.payload.titlePatterns.count == 2) // The union demoted one of the two, which is what makes the archive legal@@ -102,7 +102,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(payload.sites.count == 1) let site = try #require(payload.sites.first)@@ -140,7 +140,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() let pattern = try #require(payload.titlePatterns.first) #expect(pattern.id == patternID)@@ -169,7 +169,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(payload.entries.count == 1) #expect(payload.entries.first?.id == shared)@@ -194,7 +194,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .tornGroups(let payload) = error else { Issue.record("expected .tornGroups, got \(error)")@@ -221,7 +221,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .unrepresentableValue(let record, _, let value) = error else { Issue.record("expected .unrepresentableValue, got \(error)")@@ -253,7 +253,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .unrepresentableValue(let record, let field, let value) = error else { Issue.record("expected .unrepresentableValue, got \(error)")@@ -282,7 +282,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .unrepresentableValue(let record, let field, let value) = error else { Issue.record("expected .unrepresentableValue, got \(error)")@@ -310,7 +310,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() let record = try #require(payload.works.first { $0.id == workID }) #expect(record.workStatus == .hiatus)@@ -338,7 +338,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() let record = try #require(payload.works.first { $0.id == workID }) // The 7/8 record has nowhere to put a legacy type at all (Req 10.3, Q16).@@ -360,7 +360,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .unrepresentableValue(_, _, let value) = error else { Issue.record("expected .unrepresentableValue, got \(error)")@@ -400,7 +400,7 @@ struct BackupExportDegradedRefusalTests { memberships: try context.fetch(FetchDescriptor<WorkSiteMembership>())) #expect(omitted == [staleID]) - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(payload.urlRules.map(\.id) == [currentID]) #expect(payload.urlRules.first?.siteHostname == payload.sites.first?.hostname)@@ -431,11 +431,11 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() let staging = fixture.directory.appending(path: "staging")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date())) } guard case .unrepresentableValue(let record, let field, _) = error else {@@ -479,7 +479,7 @@ struct BackupExportDegradedRefusalTests { entries: try context.fetch(FetchDescriptor<Entry>())) #expect(omitted == [retiredID]) - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(payload.titlePatterns.map(\.id) == [activeID]) #expect(payload.titlePatterns.first?.siteHostname == payload.sites.first?.hostname)@@ -507,11 +507,11 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() let staging = fixture.directory.appending(path: "staging")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date())) } guard case .unrepresentableValue(let record, let field, _) = error else {@@ -543,11 +543,11 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() let staging = fixture.directory.appending(path: "staging")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date())) } guard case .unrepresentableValue(let record, let field, _) = error else {@@ -591,7 +591,7 @@ struct BackupExportDegradedRefusalTests { for order in [activeFirst, retiredFirst] { #expect(order.map(\.id) == [sharedID, sharedID]) let error = try #require(- throws: BackupV15ExportError.self,+ throws: BackupV16ExportError.self, "the partition must refuse an all-unreadable group holding the active row" ) { try LibraryRepository.partitionUnreadableTitlePatterns(order, entries: entries)@@ -605,10 +605,10 @@ struct BackupExportDegradedRefusalTests { } let staging = fixture.directory.appending(path: "staging")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date())) } guard case .unrepresentableValue(let record, _, _) = error else { Issue.record("expected .unrepresentableValue, got \(error)")@@ -637,7 +637,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .referencesStillArriving = error else { Issue.record("expected .referencesStillArriving, got \(error)")@@ -678,7 +678,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .referencesStillArriving(let detail) = error else { Issue.record("expected .referencesStillArriving, got \(error)")@@ -706,7 +706,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .referencesStillArriving(let detail) = error else { Issue.record("expected .referencesStillArriving, got \(error)")@@ -732,11 +732,11 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() let staging = fixture.directory.appending(path: "staging")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date())) } guard case .referencesStillArriving = error else {@@ -755,7 +755,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let error = try await expectRefusal { _ = try await repository.backupV15Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV16Snapshot() } guard case .referencesStillArriving = error else { Issue.record("expected .referencesStillArriving, got \(error)")@@ -780,11 +780,11 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() let staging = fixture.directory.appending(path: "staging")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date())) } guard case .tornGroups = error else {@@ -811,7 +811,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() let target = try Self.importIntoEmptyStore(payload) // What reconciliation would settle on: one row per hostname holding the@@ -836,7 +836,7 @@ struct BackupExportDegradedRefusalTests { } let repository = try fixture.diagnosedRepository() - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() let target = try Self.importIntoEmptyStore(payload) let rows = try target.fetch(FetchDescriptor<Site>())@@ -862,13 +862,13 @@ struct BackupExportDegradedRefusalTests { #expect(await repository.diagnostics.isEmpty) let staging = fixture.directory.appending(path: "staging")- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let result = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date())) - let decoded = try BackupV15Codec.decode(try Data(contentsOf: result.fileURL))- #expect(decoded.backupFormatVersion == 15)- #expect(decoded.databaseSchemaVersion == 16)+ let decoded = try BackupV16Codec.decode(try Data(contentsOf: result.fileURL))+ #expect(decoded.backupFormatVersion == 16)+ #expect(decoded.databaseSchemaVersion == 17) #expect(decoded.payload.entries.count == 1) #expect(decoded.payload.sites.count == 1) exporter.cleanup(result)@@ -878,12 +878,12 @@ struct BackupExportDegradedRefusalTests { private func expectRefusal( _ body: () async throws -> Void- ) async throws -> BackupV15ExportError {+ ) async throws -> BackupV16ExportError { do { try await body() Issue.record("expected a named refusal, but the export proceeded") return .snapshotFailed(reason: "no refusal")- } catch let error as BackupV15ExportError {+ } catch let error as BackupV16ExportError { return error } }@@ -891,13 +891,13 @@ struct BackupExportDegradedRefusalTests { /// The archive's own import path, into a fresh empty store. Both round-trip /// tests go through the strict reference validator on the way in, which is /// what makes "the archive is legal" an assertion rather than a hope.- private static func importIntoEmptyStore(_ payload: BackupV15Payload) throws -> ModelContext {- let encoded = try BackupV15Codec.encode(+ private static func importIntoEmptyStore(_ payload: BackupV16Payload) throws -> ModelContext {+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch))- let decoded = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch))+ let decoded = try BackupV16Codec.decode(encoded) - let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.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/BackupGoldenExportTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swiftindex b7262285..be9d06c5 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift@@ -4,7 +4,7 @@ import Testing @testable import AsterismCore -/// The byte-for-byte pin on the 15/16 export (`remove-article-mode` Req 5.4).+/// The byte-for-byte pin on the 16/17 export (`remove-article-mode` Req 5.4). /// /// Nothing in the other suites would notice a change to a key's spelling, a sort /// order, or a number's formatting: they assert on decoded *values*, and a@@ -25,7 +25,7 @@ import Testing /// is a literal, `M5Fixture` runs on a `FixedRepositoryClock`, and the canonical /// encoder sorts keys while the projection sorts every array by identifier. ///-/// **Recorded at 15/16 for `remove-article-mode`.** A Site record lost its+/// **Recorded at 16/17 for `remove-article-mode`.** A Site record lost its /// junk-suffix rule — V16 has no column for it (Req 5.1, Q12) — and the envelope /// moved with it. The fixture's four Sites are untaught and taught only; the /// articles one became `trimmed.example`, a taught Site holding the fixture's@@ -39,7 +39,7 @@ import Testing /// procedure: run this suite's byte test with `ASTERISM_RECORD_GOLDEN=1` set and /// it writes the fixture and fails, then run it again without the flag /// (`rule-citation-by-uuid` Q22).-@Suite("Backup 15/16 golden export", .serialized)+@Suite("Backup 16/17 golden export", .serialized) struct BackupGoldenExportTests { /// The recorded archive. Regenerating it is a deliberate act — see the@@ -47,10 +47,10 @@ struct BackupGoldenExportTests { private static var goldenURL: URL { URL(fileURLWithPath: #filePath) .deletingLastPathComponent()- .appending(path: "Fixtures/backup-15-16-golden.json")+ .appending(path: "Fixtures/backup-16-17-golden.json") } - /// Every array the 15/16 payload declares is non-empty, so the golden below is+ /// Every array the 16/17 payload declares is non-empty, so the golden below is /// evidence about the whole projection rather than about the half a smaller /// fixture would reach. @Test("The golden library populates every payload array")@@ -93,9 +93,14 @@ struct BackupGoldenExportTests { // `update-schedule` Req 8.1: one work with a non-empty schedule and the // rest with the explicitly-written empty one, so the golden pins both // shapes — the day spellings and canonical order, and the empty array- // that tells a 15/16 record apart from a pre-feature one (Q22).+ // that tells a 16/17 record apart from a pre-feature one (Q22). #expect(payload.works.contains { $0.releaseDays == [.monday, .thursday] }) #expect(payload.works.contains { $0.releaseDays.isEmpty })+ #expect(payload.works.contains {+ $0.latestReleasedChapter == 52 && $0.latestConfirmedAt != nil+ && !$0.countsUpOnReleaseDays && $0.latestIsEstimate+ && $0.lastChapterOverride == nil && $0.lastChapterOverrideAt != nil+ }) #expect(payload.entries.contains { $0.canonicalURL != nil }) // `work-thumbnails` Req 8.1: exactly one covered work, carrying the // committed golden JPEG through an import and back out again — which is@@ -185,10 +190,10 @@ struct BackupGoldenExportTests { == 1) } - @Test("The 15/16 export of the golden library is byte-identical to the recorded archive")+ @Test("The 16/17 export of the golden library is byte-identical to the recorded archive") func exportIsByteIdenticalToTheRecordedArchive() async throws { let payload = try await Self.exportedPayload()- let encoded = try BackupV15Codec.encode(+ let encoded = try BackupV16Codec.encode( payload: payload, metadata: BackupGoldenLibrary.metadata) // Q22: every generation bump used to re-record the golden by hand from@@ -210,7 +215,7 @@ struct BackupGoldenExportTests { #expect( encoded == golden, """- the 15/16 export of the golden library no longer produces the recorded \+ the 16/17 export of the golden library no longer produces the recorded \ bytes. An archive's bytes are its identity — the checksum is taken \ over them — so this is a wire-format change unless it is a bug. \ Establish which before re-recording \(Self.goldenURL.lastPathComponent) \@@ -225,8 +230,8 @@ struct BackupGoldenExportTests { let golden = try Data(contentsOf: Self.goldenURL) let plan = try BackupImporter.plan(from: golden) - #expect(plan.metadata.formatVersion == 15)- #expect(plan.metadata.schemaVersion == 16)+ #expect(plan.metadata.formatVersion == 16)+ #expect(plan.metadata.schemaVersion == 17) #expect(plan.counts.entries == plan.metadata.entryCount) #expect(plan.counts.works == plan.metadata.workCount) }@@ -252,13 +257,13 @@ struct BackupGoldenExportTests { /// `recordedArchiveRestoresIntoAV9Library` went away (Q23). @Test("An export imported into an empty library re-exports the same bytes") func exportImportExportIsByteIdentical() async throws {- let first = try BackupV15Codec.encode(+ let first = try BackupV16Codec.encode( payload: try await Self.exportedPayload(), metadata: BackupGoldenLibrary.metadata) let target = try await M5Fixture() try await target.repository.confirmImport(plan: try BackupImporter.plan(from: first))- let second = try BackupV15Codec.encode(- payload: try await target.repository.backupV15Snapshot(),+ let second = try BackupV16Codec.encode(+ payload: try await target.repository.backupV16Snapshot(), metadata: BackupGoldenLibrary.metadata) #expect(second == first)@@ -270,7 +275,7 @@ struct BackupGoldenExportTests { /// detached, and the dismissed pair imports verbatim. @Test("An orphan membership and a dismissed pair survive the restore") func orphansSurviveTheRestore() async throws {- let archive = try BackupV15Codec.encode(+ let archive = try BackupV16Codec.encode( payload: try await Self.exportedPayload(), metadata: BackupGoldenLibrary.metadata) let target = try await M5Fixture()@@ -287,17 +292,17 @@ struct BackupGoldenExportTests { /// Imports the golden archive into a fresh library, seeds the duplicate rows /// no write path produces, and exports what results.- private static func exportedPayload() async throws -> BackupV15Payload {+ private static func exportedPayload() async throws -> BackupV16Payload { let fixture = try await M5Fixture() let plan = try BackupImporter.plan(- from: try BackupV15Codec.encode(+ from: try BackupV16Codec.encode( payload: BackupGoldenLibrary.payload, metadata: BackupGoldenLibrary.metadata)) try await fixture.repository.confirmImport(plan: plan) try await fixture.repository.seedM5Rows( sites: BackupGoldenLibrary.duplicateSites, works: BackupGoldenLibrary.duplicateWorks, entries: BackupGoldenLibrary.duplicateEntries)- return try await fixture.repository.backupV15Snapshot()+ return try await fixture.repository.backupV16Snapshot() } } @@ -332,7 +337,7 @@ extension LibraryRepository { } /// The archive the golden library is built from: one record of every kind the-/// 15/16 payload can hold, with literal identifiers and one literal date.+/// 16/17 payload can hold, with literal identifiers and one literal date. enum BackupGoldenLibrary { static let created = Date(timeIntervalSince1970: 1_000_000) @@ -436,14 +441,14 @@ enum BackupGoldenLibrary { static let secondSiteWorkURL = "https://plain.example/works/actual-title" static let trimmedTitleSuffix = " - Trimmed Example" - static var metadata: BackupV15Metadata {- BackupV15Metadata(appBuild: "golden", exportedAt: created)+ static var metadata: BackupV16Metadata {+ BackupV16Metadata(appBuild: "golden", exportedAt: created) } // MARK: The archive - static var payload: BackupV15Payload {- BackupV15Payload(+ static var payload: BackupV16Payload {+ BackupV16Payload( entries: [notedEntry, plainEntry, trimmedEntry], works: [typedWork, foldedWork, legacyWork], sites: [taughtSite, plainSite, trimmedSite],@@ -475,7 +480,7 @@ enum BackupGoldenLibrary { /// Two active creators and the alias one of them absorbed. The alias points /// at its final survivor, which is the only shape the reference checks /// accept (Req 9.5).- private static var creators: [BackupV15Creator] {+ private static var creators: [BackupV16Creator] { [ creator(id: creatorID, name: "Mori Ayane", notes: "Also draws."), creator(id: studioID, name: "Studio Lantern"),@@ -489,7 +494,7 @@ enum BackupGoldenLibrary { /// them — pristine on every field, so an import of this archive into a fresh /// library matches them by identifier and writes nothing — plus a role the /// reader added and one they removed.- private static var creatorRoles: [BackupV15CreatorRole] {+ private static var creatorRoles: [BackupV16CreatorRole] { CreatorRoleSeeding.seeds.map { role( id: $0.id, name: $0.name, position: $0.position,@@ -504,7 +509,7 @@ enum BackupGoldenLibrary { /// removed role as well (Q27), the artist credit holding a role identifier /// no record answers for, and a credit whose work this archive never /// carried.- private static var credits: [BackupV15Credit] {+ private static var credits: [BackupV16Credit] { [ credit( id: authorCreditID, workID: typedWorkID, creatorID: creatorID,@@ -521,8 +526,8 @@ enum BackupGoldenLibrary { private static func creator( id: UUID, name: String, notes: String = "", state: CreatorState = .active, canonicalID: UUID? = nil- ) -> BackupV15Creator {- BackupV15Creator(+ ) -> BackupV16Creator {+ BackupV16Creator( id: id, name: name, nameModifiedAt: created, notes: notes, notesModifiedAt: created, stateRaw: state.rawValue, stateModifiedAt: created, canonicalID: canonicalID, createdAt: created, modifiedAt: created)@@ -531,8 +536,8 @@ enum BackupGoldenLibrary { private static func role( id: UUID, name: String, position: Int, state: CreatorRoleState = .active, stamp: Date = created- ) -> BackupV15CreatorRole {- BackupV15CreatorRole(+ ) -> BackupV16CreatorRole {+ BackupV16CreatorRole( id: id, name: name, nameModifiedAt: stamp, position: position, positionModifiedAt: stamp, stateRaw: state.rawValue, stateModifiedAt: stamp, canonicalID: nil, createdAt: stamp, modifiedAt: stamp)@@ -540,40 +545,40 @@ enum BackupGoldenLibrary { private static func credit( id: UUID, workID: UUID, creatorID: UUID, roleIDs: [UUID]- ) -> BackupV15Credit {- BackupV15Credit(+ ) -> BackupV16Credit {+ BackupV16Credit( id: id, workID: workID, creatorID: creatorID, roleIDs: roleIDs.map(\.uuidString).sorted(), createdAt: created, modifiedAt: created) } /// The one series row, carrying notes so the golden pins that column too.- private static var series: BackupV15Series {- BackupV15Series(+ private static var series: BackupV16Series {+ BackupV16Series( id: seriesID, name: "Ashfall Cycle", notes: "Read 2.5 after 2.", createdAt: created, modifiedAt: created) } /// A link over two Works the archive carries.- private static var resolvedLink: BackupV15Link {+ private static var resolvedLink: BackupV16Link { let ids = WorkDistinctPair.sortedIDs(typedWorkID, legacyWorkID)- return BackupV15Link(+ return BackupV16Link( id: resolvedLinkID, lowerWorkID: ids.lower, higherWorkID: ids.higher, linkType: "adaptation", createdAt: created, modifiedAt: created) } /// Req 13.5's tolerated half for links: one end has not arrived. It imports /// verbatim and stays the reader's to remove.- private static var unresolvedLink: BackupV15Link {+ private static var unresolvedLink: BackupV16Link { let ids = WorkDistinctPair.sortedIDs(foldedWorkID, absentWorkID)- return BackupV15Link(+ return BackupV16Link( id: unresolvedLinkID, lowerWorkID: ids.lower, higherWorkID: ids.higher, linkType: "spin-off", createdAt: created, modifiedAt: created) } /// The whole-title rule names the Work by trimming the boilerplate prefix.- private static var pattern: BackupV15TitlePattern {- BackupV15TitlePattern(+ private static var pattern: BackupV16TitlePattern {+ BackupV16TitlePattern( id: patternID, siteHostname: taughtHost, version: 1, isActive: true, createdAt: created, definition: StoredPatternDefinition(@@ -581,8 +586,8 @@ enum BackupGoldenLibrary { } /// The second taught site's active rule, and the fixture's only `trimSuffix`.- private static var trimmedPattern: BackupV15TitlePattern {- BackupV15TitlePattern(+ private static var trimmedPattern: BackupV16TitlePattern {+ BackupV16TitlePattern( id: trimmedPatternID, siteHostname: trimmedHost, version: 1, isActive: true, createdAt: created, definition: StoredPatternDefinition(@@ -590,35 +595,35 @@ enum BackupGoldenLibrary { } /// A sequence-only query rule extracts "94" from the raw URL.- private static var rule: BackupV15URLRule {- BackupV15URLRule(+ private static var rule: BackupV16URLRule {+ BackupV16URLRule( id: ruleID, version: 1, isCurrent: true, createdAt: created, origin: .readerTaught, definition: .sequence(locator: .query(name: ExactScalarString("chapter"))), siteHostname: taughtHost) } - private static var taughtSite: BackupV15Site {- BackupV15Site(+ private static var taughtSite: BackupV16Site {+ BackupV16Site( hostname: taughtHost, displayName: "Golden", mode: .taught) } - private static var plainSite: BackupV15Site {- BackupV15Site(+ private static var plainSite: BackupV16Site {+ BackupV16Site( hostname: plainHost, displayName: "Plain", mode: .untaught) } /// A second taught site, holding the fixture's only `trimSuffix` rule and /// no URL rule at all — the taught tuple the first site does not cover.- private static var trimmedSite: BackupV15Site {- BackupV15Site(+ private static var trimmedSite: BackupV16Site {+ BackupV16Site( hostname: trimmedHost, displayName: "Trimmed", mode: .taught) } private static func workType( id: UUID, name: String, state: WorkTypeState = .active, canonicalID: UUID? = nil- ) -> BackupV15WorkType {- BackupV15WorkType(+ ) -> BackupV16WorkType {+ BackupV16WorkType( id: id, name: name, stateRaw: state.rawValue, canonicalID: canonicalID, createdAt: created, modifiedAt: created) }@@ -627,8 +632,8 @@ enum BackupGoldenLibrary { /// The multi-site Work's first site: a rule-derived identity, its cited rule /// and a confirmed Work URL.- private static var taughtMembership: BackupV15Membership {- BackupV15Membership(+ private static var taughtMembership: BackupV16Membership {+ BackupV16Membership( id: taughtMembershipID, workID: typedWorkID, hostname: taughtHost, createdAt: created, urlIdentity: workIdentity, urlIdentityState: .rule, urlIdentityRuleID: ruleID, workURLString: workURL)@@ -637,22 +642,22 @@ enum BackupGoldenLibrary { /// Its second site (Req 9.1): a different Work URL, no identity, and no /// Entries at all — a membership that outlives its entries (Req 7.1) is the /// ordinary shape after a cross-site merge.- private static var secondSiteMembership: BackupV15Membership {- BackupV15Membership(+ private static var secondSiteMembership: BackupV16Membership {+ BackupV16Membership( id: secondSiteMembershipID, workID: typedWorkID, hostname: plainHost, createdAt: created.addingTimeInterval(1), urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: secondSiteWorkURL) } - private static var plainMembership: BackupV15Membership {- BackupV15Membership(+ private static var plainMembership: BackupV16Membership {+ BackupV16Membership( id: plainMembershipID, workID: foldedWorkID, hostname: plainHost, createdAt: created, urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: nil) } - private static var trimmedMembership: BackupV15Membership {- BackupV15Membership(+ private static var trimmedMembership: BackupV16Membership {+ BackupV16Membership( id: trimmedMembershipID, workID: legacyWorkID, hostname: trimmedHost, createdAt: created, urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: nil)@@ -660,17 +665,17 @@ enum BackupGoldenLibrary { /// Req 8.3, Q22: a membership whose Work has not arrived. It imports /// unattached, keeps the Work it names, and is deleted only with that Work.- private static var orphanMembership: BackupV15Membership {- BackupV15Membership(+ private static var orphanMembership: BackupV16Membership {+ BackupV16Membership( id: orphanMembershipID, workID: absentWorkID, hostname: plainHost, createdAt: created, urlIdentity: "plain.example/absent", urlIdentityState: .legacyUnverified, urlIdentityRuleID: nil, workURLString: nil) } /// Req 5.5: the reader said these two are not the same work.- private static var distinctPair: BackupV15DistinctPair {+ private static var distinctPair: BackupV16DistinctPair { let ids = WorkDistinctPair.sortedIDs(typedWorkID, foldedWorkID)- return BackupV15DistinctPair(+ return BackupV16DistinctPair( id: distinctPairID, lowerWorkID: ids.lower, higherWorkID: ids.higher, recordedAt: created) }@@ -683,8 +688,8 @@ enum BackupGoldenLibrary { /// It is also the Work carrying all three V10 status fields **off** their /// defaults (Req 8.1), so the golden pins their spellings rather than only /// the ones a fresh row would have anyway.- private static var typedWork: BackupV15Work {- BackupV15Work(+ private static var typedWork: BackupV16Work {+ BackupV16Work( id: typedWorkID, displayTitle: workName, lastParsedTitle: workName, genericNotes: genericNotes, genreTags: ["fantasy"], titleProvenance: .parsed, workStatus: .hiatus, readingStatus: .abandoned,@@ -702,13 +707,18 @@ enum BackupGoldenLibrary { // `work-thumbnails` Req 8.1: the one covered work. The shape's raw // spelling and the bytes travel; the digest does not, and import // re-derives it (Q5).- thumbnailShape: ThumbnailShape.portrait.rawValue, thumbnail: coverBytes)+ thumbnailShape: ThumbnailShape.portrait.rawValue, thumbnail: coverBytes,+ latestReleasedChapter: 52,+ latestConfirmedAt: created.addingTimeInterval(12),+ countsUpOnReleaseDays: false,+ latestIsEstimate: true,+ lastChapterOverrideAt: created.addingTimeInterval(14)) } /// The work citing the **folded** type row, so the import's canonical chase /// and the export's directory both have something to resolve.- private static var foldedWork: BackupV15Work {- BackupV15Work(+ private static var foldedWork: BackupV16Work {+ BackupV16Work( id: foldedWorkID, displayTitle: "Plain Work", lastParsedTitle: nil, genericNotes: "", genreTags: [], titleProvenance: .manual, workStatus: .finished, readingStatus: .finished, verdict: "",@@ -721,8 +731,8 @@ enum BackupGoldenLibrary { /// The untyped work. A pre-feature `typeRaw` has not been carried since 7/8 /// (`multi-site-works` Req 10.3, Q16), so this is what such a Work archives /// as.- private static var legacyWork: BackupV15Work {- BackupV15Work(+ private static var legacyWork: BackupV16Work {+ BackupV16Work( id: legacyWorkID, displayTitle: "A Standalone", lastParsedTitle: nil, genericNotes: "", genreTags: [], titleProvenance: .manual, workStatus: .ongoing, readingStatus: .reading, verdict: "",@@ -738,14 +748,14 @@ enum BackupGoldenLibrary { // MARK: The entries /// The v3 key embeds host + resolved Work name + sequence.- private static var notedEntry: BackupV15Entry {+ private static var notedEntry: BackupV16Entry { let rawURL = "https://\(taughtHost)/read?chapter=94&x=1" let key = EntryIdentityKeyV3Codec.encode( try! URLSequenceNameIdentity( hostname: ExactScalarString(taughtHost), workName: ExactScalarString(workName), chapterSequence: ExactScalarString("94")))- return BackupV15Entry(+ return BackupV16Entry( id: notedEntryID, captureTitle: titlePrefix + workName, captureTitleSource: .host, rawURL: rawURL, canonicalURL: nil, hostname: taughtHost, entryIdentityKey: key, conservativeIdentityKey: rawURL,@@ -764,9 +774,9 @@ enum BackupGoldenLibrary { /// The untaught site's Entry: a conservative key, which is what capture /// writes where no rule has been taught.- private static var plainEntry: BackupV15Entry {+ private static var plainEntry: BackupV16Entry { let rawURL = "https://\(plainHost)/read/7"- return BackupV15Entry(+ return BackupV16Entry( id: plainEntryID, captureTitle: "Plain Work", captureTitleSource: .manual, rawURL: rawURL, canonicalURL: nil, hostname: plainHost, entryIdentityKey: rawURL, conservativeIdentityKey: rawURL,@@ -781,9 +791,9 @@ enum BackupGoldenLibrary { /// The trimmed site's Entry, and the fixture's only `canonicalURL`: a /// capture whose raw URL carried a tracking parameter the canonical form /// drops.- private static var trimmedEntry: BackupV15Entry {+ private static var trimmedEntry: BackupV16Entry { let rawURL = "https://\(trimmedHost)/posts/hello?utm_source=share"- return BackupV15Entry(+ return BackupV16Entry( id: trimmedEntryID, captureTitle: "A Standalone" + trimmedTitleSuffix, captureTitleSource: .host, rawURL: rawURL, canonicalURL: "https://\(trimmedHost)/posts/hello",@@ -798,8 +808,8 @@ enum BackupGoldenLibrary { // MARK: The characters - private static var guide: BackupV15Character {- BackupV15Character(+ private static var guide: BackupV16Character {+ BackupV16Character( id: guideID, workID: typedWorkID, name: "Grover", nameKey: "grover", aliases: ["Klar"], note: "The guide.", facts: [@@ -812,14 +822,14 @@ enum BackupGoldenLibrary { } /// The sync orphan: a character whose work has not arrived.- private static var orphan: BackupV15Character {- BackupV15Character(+ private static var orphan: BackupV16Character {+ BackupV16Character( id: orphanID, workID: nil, name: "The Stranger", nameKey: "the stranger", aliases: [], note: "", facts: [], createdAt: created, modifiedAt: created) } - private static var candidateSuppression: BackupV15Suppression {- BackupV15Suppression(+ private static var candidateSuppression: BackupV16Suppression {+ BackupV16Suppression( id: candidateSuppressionID, workID: typedWorkID, kindRaw: CharacterSuppressionKind.candidate.rawValue, nameKey: "the crowned one", sourceKindRaw: nil, sourceEntryID: nil, evidence: nil,@@ -827,8 +837,8 @@ enum BackupGoldenLibrary { } /// A fact suppression, which is the shape that carries a source and evidence.- private static var factSuppression: BackupV15Suppression {- BackupV15Suppression(+ private static var factSuppression: BackupV16Suppression {+ BackupV16Suppression( id: factSuppressionID, workID: typedWorkID, kindRaw: CharacterSuppressionKind.fact.rawValue, nameKey: "grover", sourceKindRaw: SourceRef.entry(notedEntryID).kindRaw, sourceEntryID: notedEntryID,@@ -840,8 +850,8 @@ enum BackupGoldenLibrary { /// The place the reader accepted: aliases, a note and a fact citing the /// noted Entry, so the golden pins every column of the record.- private static var keep: BackupV15Place {- BackupV15Place(+ private static var keep: BackupV16Place {+ BackupV16Place( id: keepID, workID: typedWorkID, name: "The High Keep", nameKey: "high keep", aliases: ["The Keep"], note: "The fortress above the pass.",@@ -856,15 +866,15 @@ enum BackupGoldenLibrary { /// Req 5.5's orphan. A place names its owner in a column, so "no owner" is a /// `workID` no record of this archive answers for — the same absent Work the /// orphan membership names, which keeps the fixture's cast small.- private static var orphanPlace: BackupV15Place {- BackupV15Place(+ private static var orphanPlace: BackupV16Place {+ BackupV16Place( id: orphanPlaceID, workID: absentWorkID, name: "The Drowned Road", nameKey: "drowned road", aliases: [], note: "", facts: [], createdAt: created, modifiedAt: created) } - private static var placeCandidateSuppression: BackupV15PlaceSuppression {- BackupV15PlaceSuppression(+ private static var placeCandidateSuppression: BackupV16PlaceSuppression {+ BackupV16PlaceSuppression( id: placeCandidateSuppressionID, workID: typedWorkID, kindRaw: CharacterSuppressionKind.candidate.rawValue, nameKey: "low road", sourceKindRaw: nil, sourceEntryID: nil, evidence: nil,@@ -873,8 +883,8 @@ enum BackupGoldenLibrary { /// The place fact suppression, which is the shape that carries a source and /// evidence.- private static var placeFactSuppression: BackupV15PlaceSuppression {- BackupV15PlaceSuppression(+ private static var placeFactSuppression: BackupV16PlaceSuppression {+ BackupV16PlaceSuppression( id: placeFactSuppressionID, workID: typedWorkID, kindRaw: CharacterSuppressionKind.fact.rawValue, nameKey: "high keep", sourceKindRaw: SourceRef.entry(notedEntryID).kindRaw, sourceEntryID: notedEntryID,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swiftindex 3ff3d26e..a176116a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swift@@ -36,7 +36,7 @@ struct BackupGroupProjectionTests { store.addEntry(id: shared, key: "chapter-1", capturedAt: 40, sharedAt: 90, title: "Chapter 1") try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.entries.count == 1) let entry = try #require(payload.entries.first)@@ -58,15 +58,15 @@ struct BackupGroupProjectionTests { store.addEntry(id: shared, key: "chapter-1", capturedAt: 40) try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }- let encoded = try BackupV15Codec.encode(+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) }+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch)) // The decode gate is the reference validator, which refuses a payload // holding one UUID twice — the shape the projection exists to prevent // reaching it.- let decoded = try BackupV15Codec.decode(encoded)+ let decoded = try BackupV16Codec.decode(encoded) #expect(decoded.payload.entries.count == 1) } @@ -86,7 +86,7 @@ struct BackupGroupProjectionTests { store.addEntry(key: "chapter-2", capturedAt: 20, work: second, site: site) try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.works.count == 1) let work = try #require(payload.works.first)@@ -114,7 +114,7 @@ struct BackupGroupProjectionTests { store.addEntry(id: entryID, key: "chapter-1", capturedAt: 30, work: second, site: site) try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.entries.count == 1) let work = try #require(payload.works.first)@@ -147,7 +147,7 @@ struct BackupGroupProjectionTests { store.addEntry(id: shared, key: "chapter-1", capturedAt: 40, work: work, site: site) try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } let entry = try #require(payload.entries.first) let archivedWork = try #require(payload.works.first)@@ -157,10 +157,10 @@ struct BackupGroupProjectionTests { // names none (Req 9.3), so an Entry that points nowhere is unattached and // nothing contradicts it. #expect(archivedWork.id == work.id)- let encoded = try BackupV15Codec.encode(+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))- _ = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ _ = try BackupV16Codec.decode(encoded) } /// The Definitions' assignment normalisation, in the export (Q106): rows@@ -195,7 +195,7 @@ struct BackupGroupProjectionTests { rowB.editCitations { $0.workAssignment = .manual } try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.entries.count == 1) let entry = try #require(payload.entries.first)@@ -205,10 +205,10 @@ struct BackupGroupProjectionTests { // `entryIDs` lists is gone with the child lists (Req 9.3), and what is // left is the Entry naming one of them. #expect(payload.works.count == 2)- let encoded = try BackupV15Codec.encode(+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))- _ = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ _ = try BackupV16Codec.decode(encoded) } // MARK: - Req 8.3: unique-UUID set members never block export@@ -224,7 +224,7 @@ struct BackupGroupProjectionTests { store.addEntry(key: "chapter-1", capturedAt: 20, note: "from the laptop") try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.entries.count == 2) #expect(Set(payload.entries.map(\.note)) == ["from the phone", "from the laptop"])@@ -242,7 +242,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) } } #expect(payload.count == 1)@@ -268,7 +268,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) } } #expect(payload.count == 2)@@ -288,7 +288,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) } } #expect(payload.count == 1)@@ -321,7 +321,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) } } #expect(payload.count == 1)@@ -357,7 +357,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) } } #expect(payload.count == 2)@@ -393,7 +393,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) } } #expect(payload.count == 2)@@ -414,7 +414,7 @@ struct BackupGroupProjectionTests { try store.commit() _ = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) } } // The resolution outcome: both rows carry the chosen variant (Req@@ -423,7 +423,7 @@ struct BackupGroupProjectionTests { second.note = "from the phone" try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.entries.count == 1) #expect(payload.entries.first?.note == "from the phone") }@@ -441,7 +441,7 @@ struct BackupGroupProjectionTests { store.addEntry(key: "chapter-1", capturedAt: 10, site: first) try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.titlePatterns.count == 1) #expect(payload.sites.count == 1)@@ -450,10 +450,10 @@ struct BackupGroupProjectionTests { // The archive re-decodes: a payload holding one rule UUID twice is what // the reference validator refuses, and what the store validates it must // be able to export (task 20.4).- let encoded = try BackupV15Codec.encode(+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))- _ = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ _ = try BackupV16Codec.decode(encoded) } /// The dedup must not cost a hostname its active title rule.@@ -476,14 +476,14 @@ struct BackupGroupProjectionTests { store.addEntry(key: "chapter-1", capturedAt: 10, site: site) try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.titlePatterns.count == 1) #expect(payload.titlePatterns.first?.isActive == true)- let encoded = try BackupV15Codec.encode(+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))- _ = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ _ = try BackupV16Codec.decode(encoded) } /// The URL-rule half, which fails *silently* rather than refusing: nothing@@ -502,7 +502,7 @@ struct BackupGroupProjectionTests { store.addEntry(key: "chapter-1", capturedAt: 10, site: site) try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.urlRules.count == 1) #expect(payload.urlRules.first?.isCurrent == true)@@ -536,7 +536,7 @@ struct BackupGroupProjectionTests { #expect(facts.first(where: \.isActive)?.version == 3) #expect(try store.diagnose().quarantineMap().isEmpty) - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.titlePatterns.count == 1) #expect(payload.titlePatterns.first?.isActive == true)@@ -558,7 +558,7 @@ struct BackupGroupProjectionTests { store.addEntry(key: "chapter-1", capturedAt: 10, site: site) try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } #expect(payload.titlePatterns.count == 1) #expect(payload.titlePatterns.first?.isActive == true)@@ -594,7 +594,7 @@ struct BackupGroupProjectionTests { } try store.commit() - let payload = try store.read { try LibraryRepository.projectV15Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV16Payload(context: $0) } let pattern = try #require(payload.titlePatterns.first) #expect(pattern.id == ruleID)@@ -608,7 +608,7 @@ struct BackupGroupProjectionTests { try body() Issue.record("expected a torn-groups refusal, but the export proceeded") return TornGroupsPayload(count: 0, blockingWorkSet: nil)- } catch let error as BackupV15ExportError {+ } catch let error as BackupV16ExportError { guard case .tornGroups(let payload) = error else { Issue.record("expected .tornGroups, got \(error)") return TornGroupsPayload(count: 0, blockingWorkSet: nil)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swiftindex 62db448c..0fbb67fa 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swift@@ -38,7 +38,7 @@ struct BackupGroupRoundTripTests { let entryID = UUID() try await repository.seedSplitEntryGroup(id: entryID) - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() let record = try #require(payload.entries.first) let before = try await repository.entryRows(id: entryID) #expect(before.count == 2)@@ -63,7 +63,7 @@ struct BackupGroupRoundTripTests { let sourceRepository = try await source.open() let entryID = UUID() try await sourceRepository.seedSplitEntryGroup(id: entryID)- let payload = try await sourceRepository.backupV15Snapshot()+ let payload = try await sourceRepository.backupV16Snapshot() let target = try RoundTripEnvironment() let targetRepository = try await target.open()@@ -87,7 +87,7 @@ struct BackupGroupRoundTripTests { let workID = UUID() try await repository.seedSplitWorkGroup(id: workID) - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() let record = try #require(payload.works.first) let before = try await repository.workRows(id: workID) #expect(before.count == 2)@@ -117,7 +117,7 @@ struct BackupGroupRoundTripTests { let sourceRepository = try await source.open() let workID = UUID() try await sourceRepository.seedSplitWorkGroup(id: workID)- let payload = try await sourceRepository.backupV15Snapshot()+ let payload = try await sourceRepository.backupV16Snapshot() let target = try RoundTripEnvironment() let targetRepository = try await target.open()@@ -149,7 +149,7 @@ struct BackupGroupRoundTripTests { let sourceRepository = try await source.open() _ = try await sourceRepository.confirmImport(plan: RoundTripEnvironment.plan(payload)) - let exported = try await sourceRepository.backupV15Snapshot()+ let exported = try await sourceRepository.backupV16Snapshot() let target = try RoundTripEnvironment() let targetRepository = try await target.open()@@ -157,7 +157,7 @@ struct BackupGroupRoundTripTests { // Req 5.3's citation half, as decoded values rather than as bytes. let original = try #require(payload.entries.first?.citations)- let citations = try await targetRepository.citations(entryID: BackupV15Fixtures.entryID)+ let citations = try await targetRepository.citations(entryID: BackupV16Fixtures.entryID) #expect(citations == original) // Named, so the comparison above cannot pass on two empty values. #expect(citations?.chapterSequence?.id == Self.citedURLRuleID)@@ -172,7 +172,7 @@ struct BackupGroupRoundTripTests { /// used to refuse are not merely decodable, they **commit**, and the rows /// land holding the versions the archive named. ///- /// `BackupV15ArchiveTests` stops at a decode, which only proves the reference+ /// `BackupV16ArchiveTests` stops at a decode, which only proves the reference /// checks let the file through. Here the same fixture goes through /// `confirmImport` into an empty library: two title patterns share version 1 /// with one of them marked, and the marked URL rule sits *below* a retired@@ -180,7 +180,7 @@ struct BackupGroupRoundTripTests { /// renumbering pass would admit it and move the versions. @Test("An archive with duplicate and non-greatest rule versions imports with its versions") func duplicateAndNonGreatestVersionsImportIntoAnEmptyLibrary() async throws {- let payload = BackupV15Fixtures.duplicateVersionsPayload()+ let payload = BackupV16Fixtures.duplicateVersionsPayload() let host = try #require(payload.sites.first?.hostname) let target = try RoundTripEnvironment()@@ -211,7 +211,7 @@ struct BackupGroupRoundTripTests { private static let citedURLRuleID = UUID( uuidString: "dddddddd-dddd-dddd-dddd-dddddddddddd")! - private static func expectedPatternRows(_ payload: BackupV15Payload) -> [RuleRowFacts] {+ private static func expectedPatternRows(_ payload: BackupV16Payload) -> [RuleRowFacts] { payload.titlePatterns .map { RuleRowFacts(@@ -221,7 +221,7 @@ struct BackupGroupRoundTripTests { .sorted { $0.id.uuidString < $1.id.uuidString } } - private static func expectedURLRuleRows(_ payload: BackupV15Payload) -> [RuleRowFacts] {+ private static func expectedURLRuleRows(_ payload: BackupV16Payload) -> [RuleRowFacts] { payload.urlRules .map { RuleRowFacts(@@ -234,22 +234,22 @@ struct BackupGroupRoundTripTests { /// `composedPayload` — one taught Site, one cited title rule, one cited URL /// rule, one Entry citing both — plus a retired row of each kind sitting at /// a higher version than the marked one.- private static func versionSpreadPayload() -> BackupV15Payload {- let base = BackupV15Fixtures.composedPayload()+ private static func versionSpreadPayload() -> BackupV16Payload {+ let base = BackupV16Fixtures.composedPayload() let host = "example.com"- let retired = BackupV15Fixtures.created.addingTimeInterval(-60)+ let retired = BackupV16Fixtures.created.addingTimeInterval(-60) - let retiredPattern = BackupV15TitlePattern(+ let retiredPattern = BackupV16TitlePattern( id: UUID(uuidString: "cccccccc-cccc-cccc-cccc-ccccccccccc9")!, siteHostname: host, version: 9, isActive: false, createdAt: retired, definition: StoredPatternDefinition(definition: .wholeTitle))- let retiredRule = BackupV15URLRule(+ let retiredRule = BackupV16URLRule( id: UUID(uuidString: "dddddddd-dddd-dddd-dddd-ddddddddddd9")!, version: 7, isCurrent: false, createdAt: retired, origin: .readerTaught, definition: .sequence(locator: .query(name: ExactScalarString("part"))), siteHostname: host) - return BackupV15Payload(+ return BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns + [retiredPattern], urlRules: base.urlRules + [retiredRule],@@ -288,7 +288,7 @@ private struct RoundTripEnvironment { /// The plan `confirmImport` takes, straight off a payload the export just /// produced — which is what a reader restoring their own backup hands it.- static func plan(_ payload: BackupV15Payload) -> BackupImportPlan {+ static func plan(_ payload: BackupV16Payload) -> BackupImportPlan { BackupImportPlan( metadata: BackupImportMetadata( formatVersion: 8, schemaVersion: 9, appBuild: "test-1.0",
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swiftindex 653bfb74..06b4027e 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -692,12 +692,12 @@ private func createReadyEmptyV3Store(at configuration: LibraryConfiguration) thr ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV16MigrationPlan.self,+ migrationPlan: AsterismV17MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container) try context.save()- try Data("16\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic)+ try Data("17\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic) } private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) throws {@@ -706,7 +706,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -715,7 +715,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV16MigrationPlan.self,+ migrationPlan: AsterismV17MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -738,7 +738,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) // seeded already linked. entry.site = site try context.save()- try Data("16\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic)+ try Data("17\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic) } /// A certified library holding exactly one Site in the given state, for the@@ -758,7 +758,7 @@ private func createReadySiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -767,7 +767,7 @@ private func createReadySiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV16MigrationPlan.self,+ migrationPlan: AsterismV17MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -783,7 +783,7 @@ private func createReadySiteStore( context.insert(pattern) } try context.save()- try Data("16\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic)+ try Data("17\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic) } /// A certified library holding **two** Site rows for one hostname, each taught@@ -802,7 +802,7 @@ private func createReadyDuplicateSiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -811,7 +811,7 @@ private func createReadyDuplicateSiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV16MigrationPlan.self,+ migrationPlan: AsterismV17MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -826,7 +826,7 @@ private func createReadyDuplicateSiteStore( context.insert(pattern) } try context.save()- try Data("16\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic)+ try Data("17\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic) } /// An archive describing one Site and nothing else — no entries, no works, so@@ -840,12 +840,12 @@ private func makeSiteDesignationPlan( patternVersion: Int = 1 ) throws -> BackupImportPlan { let epoch = Date(timeIntervalSince1970: 1_800_000_000)- let site = BackupV15Site(+ let site = BackupV16Site( hostname: hostname, displayName: displayName ?? hostname, mode: mode)- let patterns: [BackupV15TitlePattern] = activePattern+ let patterns: [BackupV16TitlePattern] = activePattern ? [- BackupV15TitlePattern(+ BackupV16TitlePattern( // Fixed, not minted: two applications of one archive must match // the same rule row rather than insert a second one. id: patternID,@@ -871,11 +871,11 @@ private func makeSiteDesignationPlan( private func makeBulkImportPlan(entryCount: Int) throws -> BackupImportPlan { let hostname = "bulk.example" let epoch = Date(timeIntervalSince1970: 1_800_000_000)- let site = BackupV15Site(+ let site = BackupV16Site( hostname: hostname, displayName: hostname, mode: .untaught)- let entries = (0..<entryCount).map { index -> BackupV15Entry in+ let entries = (0..<entryCount).map { index -> BackupV16Entry in let rawURL = "https://\(hostname)/read?chapter=\(index)"- return BackupV15Entry(+ return BackupV16Entry( id: UUID(), captureTitle: "Chapter \(index)", captureTitleSource: .host, rawURL: rawURL, canonicalURL: nil, hostname: hostname, entryIdentityKey: rawURL,@@ -934,7 +934,7 @@ private func makeMinimalImportPlan( let patternProvenance = try FieldProvenance( kind: .pattern, patternID: patternID) - let entry = BackupV15Entry(+ let entry = BackupV16Entry( id: entryID, captureTitle: "Imported Chapter", captureTitleSource: .networkFetch,@@ -960,7 +960,7 @@ private func makeMinimalImportPlan( workAssignment: .pattern(CitedRule(id: patternID))) ) - let work = BackupV15Work(+ let work = BackupV16Work( id: workID, displayTitle: "Imported Work", lastParsedTitle: "Imported Work",@@ -979,7 +979,7 @@ private func makeMinimalImportPlan( // Req 9.1: the Work's site presence is its membership, and Req 9.5 requires // one on the Entry's hostname.- let membership = BackupV15Membership(+ let membership = BackupV16Membership( // Derived from the Work rather than minted: two archives *of one // library* carry the same membership row, which is what makes a // re-import an update rather than a second row on the same hostname.@@ -993,7 +993,7 @@ private func makeMinimalImportPlan( workURLString: workURL ) - let pattern = BackupV15TitlePattern(+ let pattern = BackupV16TitlePattern( id: patternID, siteHostname: siteHostname, version: 1,@@ -1005,8 +1005,8 @@ private func makeMinimalImportPlan( ignored: [])) ) - let urlRules: [BackupV15URLRule] = includeURLRule ? [- BackupV15URLRule(+ let urlRules: [BackupV16URLRule] = includeURLRule ? [+ BackupV16URLRule( id: urlRuleID, version: 1, isCurrent: true,@@ -1022,7 +1022,7 @@ private func makeMinimalImportPlan( ) ] : [] - let site = BackupV15Site(+ let site = BackupV16Site( hostname: siteHostname, displayName: siteHostname, mode: .taught
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16ArchiveTests.swiftsimilarity index 74%rename from Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swiftrename to Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16ArchiveTests.swiftindex faab030c..8941c00e 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16ArchiveTests.swift@@ -4,15 +4,15 @@ import Testing @testable import AsterismCore -// Archive generation 15/16 (T-2336, `remove-article-mode` Req 5.1): a Site+// Archive generation 16/17 (T-2336, `remove-article-mode` Req 5.1): a Site // record no longer carries a junk-suffix rule, because V16 has no column for it, // and the schema number names the store the archive was taken from (V16). The // Site's `mode` stays the typed `SiteMode`, so the one spelling a previous build // could have written — `articles` — refuses the file as malformed rather than-// arriving as a tolerated default (Req 5.1). A 15/16 archive is refused by+// arriving as a tolerated default (Req 5.1). A 16/17 archive is refused by // version, naming the pair it declares (Req 5.3). //-// The Work record is 15/16's: it carries the reader's cover — the shape's raw+// The Work record is 16/17's: it carries the reader's cover — the shape's raw // spelling and the bytes, base64 through `Codable` (Q5) — and its release days. // The digest is deliberately **not** in the file: it is // derived from the bytes alone (Req 1.10), so import re-derives it, which is@@ -41,17 +41,17 @@ import Testing // MARK: - Codec @Suite("Backup V15 codec")-struct BackupV15CodecTests {+struct BackupV16CodecTests { - @Test("V15 encode/decode round-trips 15/16, the multi-site gate, and the seventeen arrays")+ @Test("V16 encode/decode round-trips 16/17, the multi-site gate, and the seventeen arrays") func roundTrip() throws {- let payload = BackupV15Fixtures.payload()+ let payload = BackupV16Fixtures.payload() - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) - #expect(decoded.backupFormatVersion == 15)- #expect(decoded.databaseSchemaVersion == 16)+ #expect(decoded.backupFormatVersion == 16)+ #expect(decoded.databaseSchemaVersion == 17) #expect(decoded.capabilityGate == "multi-site") #expect(decoded.payload == payload) #expect(decoded.payload.characters == payload.characters)@@ -63,10 +63,10 @@ struct BackupV15CodecTests { // records whose text they describe. #expect( decoded.payload.entries.first?.characterExtractionFingerprint- == BackupV15Fixtures.noteFingerprint)+ == BackupV16Fixtures.noteFingerprint) #expect( decoded.payload.works.first?.genericNotesExtractionFingerprint- == BackupV15Fixtures.genericNotesFingerprint)+ == BackupV16Fixtures.genericNotesFingerprint) } /// Req 8.1. The two statuses travel as the typed enums, exactly as@@ -75,13 +75,13 @@ struct BackupV15CodecTests { /// defaults, so a dropped field cannot pass as a matching default. @Test("A Work's two statuses and verdict survive the round-trip typed") func workStatusFieldsRoundTrip() throws {- let payload = BackupV15Fixtures.composedPayload()+ let payload = BackupV16Fixtures.composedPayload() - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) let record = try #require(- decoded.payload.works.first { $0.id == BackupV15Fixtures.composedWorkID })+ decoded.payload.works.first { $0.id == BackupV16Fixtures.composedWorkID }) #expect(record.workStatus == .finished) #expect(record.readingStatus == .abandoned) #expect(record.verdict == "Dropped it at the timeskip.")@@ -94,18 +94,18 @@ struct BackupV15CodecTests { @Test("A character's facts, aliases, note and keys survive the round-trip") func characterFieldsRoundTrip() throws { let facts = [- BackupV15Fixtures.fact(),- BackupV15Fixtures.fact(+ BackupV16Fixtures.fact(),+ BackupV16Fixtures.fact( statement: "Knows the way through the pass.", quote: "knows the way", source: .genericNotes), ]- let payload = BackupV15Fixtures.payload(+ let payload = BackupV16Fixtures.payload( characters: [- BackupV15Fixtures.character(aliases: ["Klar", "The Guide"], facts: facts)+ BackupV16Fixtures.character(aliases: ["Klar", "The Guide"], facts: facts) ]) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) let character = try #require(decoded.payload.characters.first) #expect(character.name == "Grover")@@ -114,23 +114,23 @@ struct BackupV15CodecTests { #expect(character.note == "The guide.") #expect(character.facts.count == 2) #expect(character.facts.contains { $0.source == .genericNotes })- #expect(character.facts.contains { $0.source == .entry(BackupV15Fixtures.entryID) })+ #expect(character.facts.contains { $0.source == .entry(BackupV16Fixtures.entryID) }) #expect(character.facts.allSatisfy { $0.nameKey == "grover" }) } @Test("Both suppression kinds round-trip with their status and action time") func suppressionKindsRoundTrip() throws { let rows = [- BackupV15Fixtures.suppression(),- BackupV15Fixtures.suppression(- id: BackupV15Fixtures.factSuppressionID, kind: .fact, nameKey: "grover",- source: .entry(BackupV15Fixtures.entryID), evidence: "promised to guide",+ BackupV16Fixtures.suppression(),+ BackupV16Fixtures.suppression(+ id: BackupV16Fixtures.factSuppressionID, kind: .fact, nameKey: "grover",+ source: .entry(BackupV16Fixtures.entryID), evidence: "promised to guide", status: .cleared), ]- let payload = BackupV15Fixtures.payload(suppressions: rows)+ let payload = BackupV16Fixtures.payload(suppressions: rows) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.suppressions == rows) }@@ -143,11 +143,11 @@ struct BackupV15CodecTests { /// tolerated in-flight state (Req 6.7). @Test("A character with no work reference validates") func orphanCharacterValidates() throws {- let payload = BackupV15Fixtures.payload(- characters: [BackupV15Fixtures.character(id: BackupV15Fixtures.orphanID, workID: nil)])+ let payload = BackupV16Fixtures.payload(+ characters: [BackupV16Fixtures.character(id: BackupV16Fixtures.orphanID, workID: nil)]) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.characters.first?.workID == nil) }@@ -159,18 +159,18 @@ struct BackupV15CodecTests { @Test("A fact citing an entry the archive does not carry validates") func danglingFactCitationValidates() throws { let absent = UUID(uuidString: "DEADBEEF-0000-4000-8000-000000000001")!- let payload = BackupV15Fixtures.payload(+ let payload = BackupV16Fixtures.payload( characters: [- BackupV15Fixtures.character(facts: [BackupV15Fixtures.fact(source: .entry(absent))])+ BackupV16Fixtures.character(facts: [BackupV16Fixtures.fact(source: .entry(absent))]) ], suppressions: [- BackupV15Fixtures.suppression(- id: BackupV15Fixtures.factSuppressionID, kind: .fact, nameKey: "grover",+ BackupV16Fixtures.suppression(+ id: BackupV16Fixtures.factSuppressionID, kind: .fact, nameKey: "grover", source: .entry(absent), evidence: "gone") ]) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.characters.first?.facts.first?.source == .entry(absent)) #expect(decoded.payload.suppressions.first?.sourceEntryID == absent)@@ -181,24 +181,24 @@ struct BackupV15CodecTests { @Test("A character naming a work the archive does not carry refuses") func characterCitingAnAbsentWorkRefuses() throws { let absent = UUID(uuidString: "DEADBEEF-0000-4000-8000-000000000002")!- let payload = BackupV15Fixtures.payload(- characters: [BackupV15Fixtures.character(workID: absent)])+ let payload = BackupV16Fixtures.payload(+ characters: [BackupV16Fixtures.character(workID: absent)]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @Test("A suppression naming a work the archive does not carry refuses") func suppressionCitingAnAbsentWorkRefuses() throws { let absent = UUID(uuidString: "DEADBEEF-0000-4000-8000-000000000003")!- let payload = BackupV15Fixtures.payload(- suppressions: [BackupV15Fixtures.suppression(workID: absent)])+ let payload = BackupV16Fixtures.payload(+ suppressions: [BackupV16Fixtures.suppression(workID: absent)]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @@ -206,23 +206,23 @@ struct BackupV15CodecTests { @Test("Two records for one character identity refuse") func duplicateCharacterIDRefuses() throws {- let payload = BackupV15Fixtures.payload(- characters: [BackupV15Fixtures.character(), BackupV15Fixtures.character()])+ let payload = BackupV16Fixtures.payload(+ characters: [BackupV16Fixtures.character(), BackupV16Fixtures.character()]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @Test("Two records for one suppression identity refuse") func duplicateSuppressionIDRefuses() throws {- let payload = BackupV15Fixtures.payload(- suppressions: [BackupV15Fixtures.suppression(), BackupV15Fixtures.suppression()])+ let payload = BackupV16Fixtures.payload(+ suppressions: [BackupV16Fixtures.suppression(), BackupV16Fixtures.suppression()]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @@ -234,43 +234,43 @@ struct BackupV15CodecTests { @Test("A place's facts, aliases, note and keys survive the round-trip") func placeFieldsRoundTrip() throws { let facts = [- BackupV15Fixtures.fact(+ BackupV16Fixtures.fact( statement: "Sits above the pass.", quote: "above the pass", nameKey: "high keep"),- BackupV15Fixtures.fact(+ BackupV16Fixtures.fact( statement: "Was abandoned after the siege.", quote: "abandoned after the siege", nameKey: "high keep", source: .genericNotes), ]- let payload = BackupV15Fixtures.payload(- places: [BackupV15Fixtures.place(aliases: ["The Keep"], facts: facts)])+ let payload = BackupV16Fixtures.payload(+ places: [BackupV16Fixtures.place(aliases: ["The Keep"], facts: facts)]) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) let place = try #require(decoded.payload.places.first)- #expect(place.workID == BackupV15Fixtures.workID)+ #expect(place.workID == BackupV16Fixtures.workID) #expect(place.name == "The High Keep") #expect(place.nameKey == "high keep") #expect(place.aliases == ["The Keep"]) #expect(place.note == "The fortress above the pass.") #expect(place.facts.count == 2) #expect(place.facts.contains { $0.source == .genericNotes })- #expect(place.facts.contains { $0.source == .entry(BackupV15Fixtures.entryID) })+ #expect(place.facts.contains { $0.source == .entry(BackupV16Fixtures.entryID) }) } @Test("Both place-suppression kinds round-trip with their status and action time") func placeSuppressionKindsRoundTrip() throws { let rows = [- BackupV15Fixtures.placeSuppression(),- BackupV15Fixtures.placeSuppression(- id: BackupV15Fixtures.placeFactSuppressionID, kind: .fact,- nameKey: "high keep", source: .entry(BackupV15Fixtures.entryID),+ BackupV16Fixtures.placeSuppression(),+ BackupV16Fixtures.placeSuppression(+ id: BackupV16Fixtures.placeFactSuppressionID, kind: .fact,+ nameKey: "high keep", source: .entry(BackupV16Fixtures.entryID), evidence: "above the pass", status: .cleared), ]- let payload = BackupV15Fixtures.payload(placeSuppressions: rows)+ let payload = BackupV16Fixtures.payload(placeSuppressions: rows) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.placeSuppressions == rows) }@@ -282,12 +282,12 @@ struct BackupV15CodecTests { @Test("A place and a place suppression naming a work the archive does not carry validate") func orphanPlaceValidates() throws { let absent = UUID(uuidString: "DEADBEEF-0000-4000-8000-00000000000a")!- let payload = BackupV15Fixtures.payload(- places: [BackupV15Fixtures.place(id: BackupV15Fixtures.orphanPlaceID, workID: absent)],- placeSuppressions: [BackupV15Fixtures.placeSuppression(workID: absent)])+ let payload = BackupV16Fixtures.payload(+ places: [BackupV16Fixtures.place(id: BackupV16Fixtures.orphanPlaceID, workID: absent)],+ placeSuppressions: [BackupV16Fixtures.placeSuppression(workID: absent)]) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.places.first?.workID == absent) #expect(decoded.payload.placeSuppressions.first?.workID == absent)@@ -297,22 +297,22 @@ struct BackupV15CodecTests { /// records for one identity contradicts itself whichever table it is. @Test("Two records for one place or one place-suppression identity refuse") func duplicatePlaceIDRefuses() throws {- let duplicatePlaces = BackupV15Fixtures.payload(- places: [BackupV15Fixtures.place(), BackupV15Fixtures.place()])+ let duplicatePlaces = BackupV16Fixtures.payload(+ places: [BackupV16Fixtures.place(), BackupV16Fixtures.place()]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: duplicatePlaces, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: duplicatePlaces, metadata: BackupV16Fixtures.metadata())) } - let duplicateSuppressions = BackupV15Fixtures.payload(+ let duplicateSuppressions = BackupV16Fixtures.payload( placeSuppressions: [- BackupV15Fixtures.placeSuppression(), BackupV15Fixtures.placeSuppression(),+ BackupV16Fixtures.placeSuppression(), BackupV16Fixtures.placeSuppression(), ]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: duplicateSuppressions, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: duplicateSuppressions, metadata: BackupV16Fixtures.metadata())) } } @@ -326,7 +326,7 @@ struct BackupV15CodecTests { /// The tie asserts **plainly** again. It was deliberately broken for the /// length of `remove-article-mode`'s schema commit, as it was for /// `update-schedule`'s and `work-thumbnails`' (Q73, Q17): the store moved to- /// V16 one commit before the archive moved to 15/16, held open by a+ /// V16 one commit before the archive moved to 16/17, held open by a /// self-clearing `withKnownIssue`. Swift Testing fails a known-issue block /// whose issue does not occur, so this commit had to take the wrapper off or /// go red — which is exactly what it was for. `make test-core` expects zero@@ -334,23 +334,23 @@ struct BackupV15CodecTests { @Test("The archive's schema version is the live schema's, and the format is one below") func envelopeVersionsFollowTheLiveSchema() throws { #expect(- BackupV15Document.schemaVersion == AsterismSchemaV16.versionIdentifier.major,+ BackupV16Document.schemaVersion == AsterismSchemaV17.versionIdentifier.major, """- the archive declares schema \(BackupV15Document.schemaVersion) but the store \- is at V\(AsterismSchemaV16.versionIdentifier.major). A schema bump moves four \+ the archive declares schema \(BackupV16Document.schemaVersion) but the store \+ is at V\(AsterismSchemaV17.versionIdentifier.major). A schema bump moves four \ things (CLAUDE.md, `docs/agent-notes/schema-migration.md`), and the archive \ generation is the one that fails silently when it is forgotten. """) // Both numbers move together when the archive generation does: 15 // trails 16 exactly as 14 trailed 15. #expect(- BackupV15Document.formatVersion == BackupV15Document.schemaVersion - 1,+ BackupV16Document.formatVersion == BackupV16Document.schemaVersion - 1, "the format number has trailed the schema number by one since 4/4 diverged") } // MARK: The Site's mode (`remove-article-mode` Req 5.1) - /// `BackupV15Site.mode` is the typed `SiteMode` rather than its raw string,+ /// `BackupV16Site.mode` is the typed `SiteMode` rather than its raw string, /// so a spelling this build has no case for fails the decode and the archive /// is refused as malformed. Reading a store row is tolerant — an unknown /// `modeRaw` reads as the default and is quarantined — and reading a backup@@ -360,14 +360,14 @@ struct BackupV15CodecTests { /// The literal carries a neutral unknown spelling. The retired `articles` is /// Req 7.2's exception, spelled only in `UnknownSiteModeTests`; the door /// asserted here is the same one for every value the type cannot name.- @Test("A 15/16 Site carrying a mode this build cannot name fails to decode")+ @Test("A 16/17 Site carrying a mode this build cannot name fails to decode") func siteWithAnUnknownModeRefuses() throws {- let document = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.unknownSiteModePayloadJSON,+ let document = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.unknownSiteModePayloadJSON, entryCount: 1, workCount: 1) do {- _ = try BackupV15Codec.decode(document)+ _ = try BackupV16Codec.decode(document) Issue.record("expected a decode refusal, but the document decoded") } catch let error as BackupCodecError { guard case .decodingFailed = error else {@@ -378,10 +378,10 @@ struct BackupV15CodecTests { // The same literal with a mode this build *can* name decodes, so the // refusal is about the value rather than about the paste.- let known = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.citationVersionFreePayloadJSON,+ let known = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)- let site = try #require(try BackupV15Codec.decode(known).payload.sites.first)+ let site = try #require(try BackupV16Codec.decode(known).payload.sites.first) #expect(site.mode == .taught) } @@ -393,20 +393,20 @@ struct BackupV15CodecTests { /// wholly legal on arrival (Q50). @Test("An Entry whose present Work has no membership on its hostname refuses") func entryWithoutAMembershipOnItsHostnameRefuses() throws {- let base = BackupV15Fixtures.composedPayload()+ let base = BackupV16Fixtures.composedPayload() // The premise: with the membership present the payload is legal.- _ = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: base, metadata: BackupV15Fixtures.metadata()))+ _ = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: base, metadata: BackupV16Fixtures.metadata())) - let uncovered = BackupV15Payload(+ let uncovered = BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: []) let error = #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: uncovered, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: uncovered, metadata: BackupV16Fixtures.metadata())) } guard case .unresolvedReference(let type, _, let reference) = error else { Issue.record("expected an unresolved reference, got \(String(describing: error))")@@ -421,18 +421,18 @@ struct BackupV15CodecTests { /// the reconciler resolves (Req 2.6, 8.2), and one an archive may not carry. @Test("Two memberships for one Work and hostname refuse") func duplicateMembershipForOneHostnameRefuses() throws {- let base = BackupV15Fixtures.composedPayload()- let twin = BackupV15Fixtures.membership(+ let base = BackupV16Fixtures.composedPayload()+ let twin = BackupV16Fixtures.membership( id: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee2")!,- workID: BackupV15Fixtures.composedWorkID, hostname: "example.com")- let payload = BackupV15Payload(+ workID: BackupV16Fixtures.composedWorkID, hostname: "example.com")+ let payload = BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: base.memberships + [twin]) let error = #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } guard case .invalidStateTuple(let type, _, let reason) = error else { Issue.record("expected an invalid state tuple, got \(String(describing: error))")@@ -449,24 +449,24 @@ struct BackupV15CodecTests { func unattachedMembershipAndPairValidate() throws { let absent = UUID(uuidString: "DEADBEEF-0000-4000-8000-000000000010")! let other = UUID(uuidString: "DEADBEEF-0000-4000-8000-000000000011")!- let base = BackupV15Fixtures.composedPayload()- let orphan = BackupV15Fixtures.membership(+ let base = BackupV16Fixtures.composedPayload()+ let orphan = BackupV16Fixtures.membership( id: UUID(uuidString: "0adbea00-0000-4000-8000-000000000001")!, workID: absent, hostname: "example.com") let ids = WorkDistinctPair.sortedIDs(absent, other)- let payload = BackupV15Payload(+ let payload = BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: base.memberships + [orphan], distinctPairs: [- BackupV15DistinctPair(+ BackupV16DistinctPair( id: UUID(uuidString: "0adbea00-0000-4000-8000-000000000002")!, lowerWorkID: ids.lower, higherWorkID: ids.higher,- recordedAt: BackupV15Fixtures.created)+ recordedAt: BackupV16Fixtures.created) ]) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.memberships.contains { $0.workID == absent }) #expect(decoded.payload.distinctPairs.count == 1)@@ -477,20 +477,20 @@ struct BackupV15CodecTests { /// value (Req 1.2). @Test("A membership whose identity tuple contradicts itself refuses") func illegalMembershipTupleRefuses() throws {- let base = BackupV15Fixtures.composedPayload()- let illegal = BackupV15Membership(- id: BackupV15Fixtures.composedMembershipID,- workID: BackupV15Fixtures.composedWorkID, hostname: "example.com",- createdAt: BackupV15Fixtures.created, urlIdentity: nil, urlIdentityState: .rule,+ let base = BackupV16Fixtures.composedPayload()+ let illegal = BackupV16Membership(+ id: BackupV16Fixtures.composedMembershipID,+ workID: BackupV16Fixtures.composedWorkID, hostname: "example.com",+ createdAt: BackupV16Fixtures.created, urlIdentity: nil, urlIdentityState: .rule, urlIdentityRuleID: nil, workURLString: nil)- let payload = BackupV15Payload(+ let payload = BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: [illegal]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @@ -500,29 +500,29 @@ struct BackupV15CodecTests { /// no writer produces — the Entry's identity arm refuses the same shape. @Test("A membership citing a rule taught for another site refuses") func membershipCitingAnotherSitesRuleRefuses() throws {- let base = BackupV15Fixtures.composedPayload()+ let base = BackupV16Fixtures.composedPayload() let otherHost = "other.example" let otherRuleID = UUID(uuidString: "dddddddd-dddd-dddd-dddd-ddddddddddd2")!- let otherSite = BackupV15Site(+ let otherSite = BackupV16Site( hostname: otherHost, displayName: "Other", mode: .untaught)- let otherRule = BackupV15URLRule(- id: otherRuleID, version: 1, isCurrent: false, createdAt: BackupV15Fixtures.created,+ let otherRule = BackupV16URLRule(+ id: otherRuleID, version: 1, isCurrent: false, createdAt: BackupV16Fixtures.created, origin: .importedV2, definition: .work(locator: .query(name: ExactScalarString("series"))), siteHostname: otherHost) // The membership is on example.com and cites other.example's rule.- let crossSite = BackupV15Fixtures.membership(- id: BackupV15Fixtures.composedMembershipID,- workID: BackupV15Fixtures.composedWorkID, hostname: "example.com",+ let crossSite = BackupV16Fixtures.membership(+ id: BackupV16Fixtures.composedMembershipID,+ workID: BackupV16Fixtures.composedWorkID, hostname: "example.com", urlIdentity: "serial-9", urlIdentityState: .rule, urlIdentityRuleID: otherRuleID)- let payload = BackupV15Payload(+ let payload = BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites + [otherSite], titlePatterns: base.titlePatterns, urlRules: base.urlRules + [otherRule], workTypes: base.workTypes, memberships: [crossSite]) let error = #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } guard case .invalidStateTuple(let type, _, let reason) = error else { Issue.record("expected an invalid state tuple, got \(String(describing: error))")@@ -538,19 +538,19 @@ struct BackupV15CodecTests { /// arrives, which is a tolerated state rather than a corrupt file. @Test("A membership citing a rule the archive does not carry is accepted") func membershipCitingAnAbsentRuleValidates() throws {- let base = BackupV15Fixtures.composedPayload()+ let base = BackupV16Fixtures.composedPayload() let absentRule = UUID(uuidString: "dddddddd-dddd-dddd-dddd-ddddddddddd3")!- let dangling = BackupV15Fixtures.membership(- id: BackupV15Fixtures.composedMembershipID,- workID: BackupV15Fixtures.composedWorkID, hostname: "example.com",+ let dangling = BackupV16Fixtures.membership(+ id: BackupV16Fixtures.composedMembershipID,+ workID: BackupV16Fixtures.composedWorkID, hostname: "example.com", urlIdentity: "serial-9", urlIdentityState: .rule, urlIdentityRuleID: absentRule)- let payload = BackupV15Payload(+ let payload = BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: [dangling]) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.memberships.first?.urlIdentityRuleID == absentRule) }@@ -561,41 +561,41 @@ struct BackupV15CodecTests { /// works' membership pairs, and the link between them. @Test("Series, memberships and links round-trip through the codec") func seriesAndLinksRoundTrip() throws {- let payload = BackupV15Fixtures.seriesPayload()+ let payload = BackupV16Fixtures.seriesPayload() - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.series == payload.series) #expect(decoded.payload.links == payload.links) let first = try #require(- decoded.payload.works.first { $0.id == BackupV15Fixtures.composedWorkID })- #expect(first.seriesID == BackupV15Fixtures.seriesID)+ decoded.payload.works.first { $0.id == BackupV16Fixtures.composedWorkID })+ #expect(first.seriesID == BackupV16Fixtures.seriesID) #expect(first.seriesPosition == 1) let second = try #require(- decoded.payload.works.first { $0.id == BackupV15Fixtures.secondWorkID })+ decoded.payload.works.first { $0.id == BackupV16Fixtures.secondWorkID }) #expect(second.seriesPosition == 2.5) } @Test("Two records for one series identity refuse") func duplicateSeriesIDRefuses() throws {- let payload = BackupV15Fixtures.seriesPayload(- series: [BackupV15Fixtures.seriesRecord(), BackupV15Fixtures.seriesRecord()])+ let payload = BackupV16Fixtures.seriesPayload(+ series: [BackupV16Fixtures.seriesRecord(), BackupV16Fixtures.seriesRecord()]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @Test("Two records for one link identity refuse") func duplicateLinkIDRefuses() throws {- let payload = BackupV15Fixtures.seriesPayload(- links: [BackupV15Fixtures.linkRecord(), BackupV15Fixtures.linkRecord()])+ let payload = BackupV16Fixtures.seriesPayload(+ links: [BackupV16Fixtures.linkRecord(), BackupV16Fixtures.linkRecord()]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @@ -604,15 +604,15 @@ struct BackupV15CodecTests { /// before a file exists; this answers for an archive written elsewhere. @Test("A link naming one work twice refuses") func selfLinkRefuses() throws {- let payload = BackupV15Fixtures.seriesPayload(+ let payload = BackupV16Fixtures.seriesPayload( links: [- BackupV15Fixtures.linkRecord(- a: BackupV15Fixtures.composedWorkID, b: BackupV15Fixtures.composedWorkID)+ BackupV16Fixtures.linkRecord(+ a: BackupV16Fixtures.composedWorkID, b: BackupV16Fixtures.composedWorkID) ]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @@ -622,31 +622,31 @@ struct BackupV15CodecTests { @Test("Two links over one pair refuse, whichever order their ids are in") func twoLinksForOnePairRefuse() throws { let second = UUID(uuidString: "11115E51-0000-4000-8000-000000000002")!- let payload = BackupV15Fixtures.seriesPayload(+ let payload = BackupV16Fixtures.seriesPayload( links: [- BackupV15Fixtures.linkRecord(),+ BackupV16Fixtures.linkRecord(), // The reversed spelling of the same pair: the payload sorts at // the door, so this is the same key rather than a second one.- BackupV15Fixtures.linkRecord(- id: second, a: BackupV15Fixtures.secondWorkID,- b: BackupV15Fixtures.composedWorkID, type: "sequel"),+ BackupV16Fixtures.linkRecord(+ id: second, a: BackupV16Fixtures.secondWorkID,+ b: BackupV16Fixtures.composedWorkID, type: "sequel"), ]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @Test("A series with an empty trimmed name refuses") func emptySeriesNameRefuses() throws { for name in ["", " ", "\n\t "] {- let payload = BackupV15Fixtures.seriesPayload(- series: [BackupV15Fixtures.seriesRecord(name: name)])+ let payload = BackupV16Fixtures.seriesPayload(+ series: [BackupV16Fixtures.seriesRecord(name: name)]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())) } } }@@ -658,16 +658,16 @@ struct BackupV15CodecTests { @Test("A half-set membership pair refuses, either half") func halfSetMembershipRefuses() throws { let halves: [(UUID?, Double?)] = [- (BackupV15Fixtures.seriesID, nil),+ (BackupV16Fixtures.seriesID, nil), (nil, 2), ] for (id, position) in halves {- let payload = BackupV15Fixtures.payloadWithMembership(+ let payload = BackupV16Fixtures.payloadWithMembership( seriesID: id, position: position) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())) } } }@@ -677,12 +677,12 @@ struct BackupV15CodecTests { @Test("A position that is not finite or carries a second fraction digit refuses") func illegalPositionRefuses() throws { for position in [2.55, 1.0 / 3.0, Double.infinity, Double.nan] {- let payload = BackupV15Fixtures.payloadWithMembership(- seriesID: BackupV15Fixtures.seriesID, position: position)+ let payload = BackupV16Fixtures.payloadWithMembership(+ seriesID: BackupV16Fixtures.seriesID, position: position) #expect(throws: (any Error).self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())) } } }@@ -696,19 +696,19 @@ struct BackupV15CodecTests { func unresolvedReferencesValidate() throws { let absentSeries = UUID(uuidString: "5E81E5A0-0000-4000-8000-000000000009")! let absentWork = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee99")!- let payload = BackupV15Fixtures.seriesPayload(+ let payload = BackupV16Fixtures.seriesPayload( links: [- BackupV15Fixtures.linkRecord(- a: BackupV15Fixtures.composedWorkID, b: absentWork, type: "spin-off")+ BackupV16Fixtures.linkRecord(+ a: BackupV16Fixtures.composedWorkID, b: absentWork, type: "spin-off") ], firstMembership: (absentSeries, 3)) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect( decoded.payload.works.contains {- $0.id == BackupV15Fixtures.composedWorkID && $0.seriesID == absentSeries+ $0.id == BackupV16Fixtures.composedWorkID && $0.seriesID == absentSeries }) #expect( decoded.payload.links.contains {@@ -723,11 +723,11 @@ struct BackupV15CodecTests { @Test("A link's ids are sorted at the door") func linkIDsAreSortedAtTheDoor() throws { let ids = WorkDistinctPair.sortedIDs(- BackupV15Fixtures.composedWorkID, BackupV15Fixtures.secondWorkID)- let reversed = BackupV15Fixtures.linkRecord(a: ids.higher, b: ids.lower)+ BackupV16Fixtures.composedWorkID, BackupV16Fixtures.secondWorkID)+ let reversed = BackupV16Fixtures.linkRecord(a: ids.higher, b: ids.lower) #expect(reversed.lowerWorkID == ids.higher) - let payload = BackupImportPayload(BackupV15Fixtures.seriesPayload(links: [reversed]))+ let payload = BackupImportPayload(BackupV16Fixtures.seriesPayload(links: [reversed])) #expect(payload.links.map(\.lowerWorkID) == [ids.lower]) #expect(payload.links.map(\.higherWorkID) == [ids.higher]) }@@ -739,77 +739,77 @@ struct BackupV15CodecTests { /// (Q50) and the list order a credit is presented in. @Test("Creators, roles and credits round-trip with their per-field timestamps") func creatorRecordsRoundTrip() throws {- let payload = BackupV15Fixtures.creditsPayload()+ let payload = BackupV16Fixtures.creditsPayload() - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload.creators == payload.creators) #expect(decoded.payload.creatorRoles == payload.creatorRoles) #expect(decoded.payload.credits == payload.credits) let alias = try #require(- decoded.payload.creators.first { $0.id == BackupV15Fixtures.aliasID })+ decoded.payload.creators.first { $0.id == BackupV16Fixtures.aliasID }) #expect(alias.stateRaw == CreatorState.merged.rawValue)- #expect(alias.canonicalID == BackupV15Fixtures.moriID)+ #expect(alias.canonicalID == BackupV16Fixtures.moriID) let mori = try #require(- decoded.payload.creators.first { $0.id == BackupV15Fixtures.moriID })+ decoded.payload.creators.first { $0.id == BackupV16Fixtures.moriID }) #expect(mori.notes == "Also draws.")- #expect(mori.nameModifiedAt == BackupV15Fixtures.created)- #expect(mori.notesModifiedAt == BackupV15Fixtures.created)+ #expect(mori.nameModifiedAt == BackupV16Fixtures.created)+ #expect(mori.notesModifiedAt == BackupV16Fixtures.created) // A seeded role travels pristine, which is what lets the archive's own // record of a default yield to — or beat — a local seed on arrival (Q28). let author = try #require(- decoded.payload.creatorRoles.first { $0.id == BackupV15Fixtures.authorRoleID })+ decoded.payload.creatorRoles.first { $0.id == BackupV16Fixtures.authorRoleID }) #expect(author.position == 0)- #expect(author.nameModifiedAt == BackupV15Fixtures.pristine)- #expect(author.positionModifiedAt == BackupV15Fixtures.pristine)+ #expect(author.nameModifiedAt == BackupV16Fixtures.pristine)+ #expect(author.positionModifiedAt == BackupV16Fixtures.pristine) let letterer = try #require(- decoded.payload.creatorRoles.first { $0.id == BackupV15Fixtures.lettererRoleID })+ decoded.payload.creatorRoles.first { $0.id == BackupV16Fixtures.lettererRoleID }) #expect(letterer.position == 3) let editor = try #require(- decoded.payload.creatorRoles.first { $0.id == BackupV15Fixtures.editorRoleID })+ decoded.payload.creatorRoles.first { $0.id == BackupV16Fixtures.editorRoleID }) #expect(editor.stateRaw == CreatorRoleState.removed.rawValue) // Q27: a credit carries every role identifier it holds **in any state**, // the removed one included, or a restore after a remove-then-restore // would lose the pairing Req 2.2 promises to bring back. let credit = try #require(- decoded.payload.credits.first { $0.id == BackupV15Fixtures.moriCreditID })- #expect(credit.roleIDs.contains(BackupV15Fixtures.editorRoleID.uuidString))+ decoded.payload.credits.first { $0.id == BackupV16Fixtures.moriCreditID })+ #expect(credit.roleIDs.contains(BackupV16Fixtures.editorRoleID.uuidString)) } @Test( "Two records for one creator, role or credit identity refuse", arguments: [0, 1, 2]) func duplicateDirectoryIDsRefuse(table: Int) throws {- let payload: BackupV15Payload+ let payload: BackupV16Payload switch table { case 0:- payload = BackupV15Fixtures.creditsPayload(- creators: BackupV15Fixtures.creatorRecords- + [BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane")])+ payload = BackupV16Fixtures.creditsPayload(+ creators: BackupV16Fixtures.creatorRecords+ + [BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane")]) case 1:- payload = BackupV15Fixtures.creditsPayload(- creatorRoles: BackupV15Fixtures.creatorRoleRecords- + [BackupV15Fixtures.creatorRoleRecord(- id: BackupV15Fixtures.lettererRoleID, name: "letterer", position: 9)])+ payload = BackupV16Fixtures.creditsPayload(+ creatorRoles: BackupV16Fixtures.creatorRoleRecords+ + [BackupV16Fixtures.creatorRoleRecord(+ id: BackupV16Fixtures.lettererRoleID, name: "letterer", position: 9)]) default:- payload = BackupV15Fixtures.creditsPayload(- credits: BackupV15Fixtures.creditRecords- + [BackupV15Fixtures.creditRecord(- id: BackupV15Fixtures.moriCreditID,- workID: BackupV15Fixtures.secondWorkID,- creatorID: BackupV15Fixtures.studioID)])+ payload = BackupV16Fixtures.creditsPayload(+ credits: BackupV16Fixtures.creditRecords+ + [BackupV16Fixtures.creditRecord(+ id: BackupV16Fixtures.moriCreditID,+ workID: BackupV16Fixtures.secondWorkID,+ creatorID: BackupV16Fixtures.studioID)]) } #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @@ -820,25 +820,25 @@ struct BackupV15CodecTests { /// name. @Test("Two active creators, or two visible roles, with one normalized name refuse") func normalizedNameCollisionsRefuse() throws {- let creators = BackupV15Fixtures.creditsPayload(- creators: BackupV15Fixtures.creatorRecords- + [BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.absentCreatorID, name: "MORI AYANE")])+ let creators = BackupV16Fixtures.creditsPayload(+ creators: BackupV16Fixtures.creatorRecords+ + [BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.absentCreatorID, name: "MORI AYANE")]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: creators, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: creators, metadata: BackupV16Fixtures.metadata())) } // Active against removed: the pair Req 2.2's restore could not choose // between.- let roles = BackupV15Fixtures.creditsPayload(- creatorRoles: BackupV15Fixtures.creatorRoleRecords- + [BackupV15Fixtures.creatorRoleRecord(- id: BackupV15Fixtures.absentRoleID, name: "Editor", position: 5)])+ let roles = BackupV16Fixtures.creditsPayload(+ creatorRoles: BackupV16Fixtures.creatorRoleRecords+ + [BackupV16Fixtures.creatorRoleRecord(+ id: BackupV16Fixtures.absentRoleID, name: "Editor", position: 5)]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: roles, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: roles, metadata: BackupV16Fixtures.metadata())) } } @@ -848,46 +848,46 @@ struct BackupV15CodecTests { /// whose end is another alias (Q33). @Test("A merged record naming an absent or merged survivor refuses") func brokenAliasChainsRefuse() throws {- let absentSurvivor = BackupV15Fixtures.creditsPayload(+ let absentSurvivor = BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane"),- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.aliasID, name: "mori ayane", state: .merged,- canonicalID: BackupV15Fixtures.absentCreatorID),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane"),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.aliasID, name: "mori ayane", state: .merged,+ canonicalID: BackupV16Fixtures.absentCreatorID), ]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: absentSurvivor, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: absentSurvivor, metadata: BackupV16Fixtures.metadata())) } - let chain = BackupV15Fixtures.creditsPayload(+ let chain = BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane"),- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.studioID, name: "mori ayane 2", state: .merged,- canonicalID: BackupV15Fixtures.moriID),- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.aliasID, name: "mori ayane", state: .merged,- canonicalID: BackupV15Fixtures.studioID),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane"),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.studioID, name: "mori ayane 2", state: .merged,+ canonicalID: BackupV16Fixtures.moriID),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.aliasID, name: "mori ayane", state: .merged,+ canonicalID: BackupV16Fixtures.studioID), ]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: chain, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: chain, metadata: BackupV16Fixtures.metadata())) } - let roleChain = BackupV15Fixtures.creditsPayload(- creatorRoles: BackupV15Fixtures.creatorRoleRecords- + [BackupV15Fixtures.creatorRoleRecord(- id: BackupV15Fixtures.absentRoleID, name: "letters", position: 6,- state: .merged, canonicalID: BackupV15Fixtures.absentCreatorID)])+ let roleChain = BackupV16Fixtures.creditsPayload(+ creatorRoles: BackupV16Fixtures.creatorRoleRecords+ + [BackupV16Fixtures.creatorRoleRecord(+ id: BackupV16Fixtures.absentRoleID, name: "letters", position: 6,+ state: .merged, canonicalID: BackupV16Fixtures.absentCreatorID)]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: roleChain, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: roleChain, metadata: BackupV16Fixtures.metadata())) } } @@ -897,59 +897,59 @@ struct BackupV15CodecTests { /// and no writer produces (Q65). @Test("Two credits over one pair, and a repeated role identifier, refuse") func malformedCreditsRefuse() throws {- let pair = BackupV15Fixtures.creditsPayload(- credits: BackupV15Fixtures.creditRecords- + [BackupV15Fixtures.creditRecord(- id: BackupV15Fixtures.absentRoleID,- workID: BackupV15Fixtures.composedWorkID,- creatorID: BackupV15Fixtures.moriID,- roleIDs: [BackupV15Fixtures.artistRoleID])])+ let pair = BackupV16Fixtures.creditsPayload(+ credits: BackupV16Fixtures.creditRecords+ + [BackupV16Fixtures.creditRecord(+ id: BackupV16Fixtures.absentRoleID,+ workID: BackupV16Fixtures.composedWorkID,+ creatorID: BackupV16Fixtures.moriID,+ roleIDs: [BackupV16Fixtures.artistRoleID])]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: pair, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: pair, metadata: BackupV16Fixtures.metadata())) } - let repeated = BackupV15Fixtures.creditsPayload(+ let repeated = BackupV16Fixtures.creditsPayload( credits: [- BackupV15Credit(- id: BackupV15Fixtures.moriCreditID,- workID: BackupV15Fixtures.composedWorkID,- creatorID: BackupV15Fixtures.moriID,+ BackupV16Credit(+ id: BackupV16Fixtures.moriCreditID,+ workID: BackupV16Fixtures.composedWorkID,+ creatorID: BackupV16Fixtures.moriID, roleIDs: [- BackupV15Fixtures.authorRoleID.uuidString,- BackupV15Fixtures.authorRoleID.uuidString,+ BackupV16Fixtures.authorRoleID.uuidString,+ BackupV16Fixtures.authorRoleID.uuidString, ],- createdAt: BackupV15Fixtures.created,- modifiedAt: BackupV15Fixtures.created)+ createdAt: BackupV16Fixtures.created,+ modifiedAt: BackupV16Fixtures.created) ]) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: repeated, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: repeated, metadata: BackupV16Fixtures.metadata())) } } @Test("A creator or role with an empty trimmed name refuses") func emptyDirectoryNamesRefuse() throws { for name in ["", " ", "\n\t "] {- let creators = BackupV15Fixtures.creditsPayload(- creators: [BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: name)],+ let creators = BackupV16Fixtures.creditsPayload(+ creators: [BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: name)], credits: []) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: creators, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: creators, metadata: BackupV16Fixtures.metadata())) } - let roles = BackupV15Fixtures.creditsPayload(- creatorRoles: [BackupV15Fixtures.creatorRoleRecord(- id: BackupV15Fixtures.lettererRoleID, name: name, position: 3)],+ let roles = BackupV16Fixtures.creditsPayload(+ creatorRoles: [BackupV16Fixtures.creatorRoleRecord(+ id: BackupV16Fixtures.lettererRoleID, name: name, position: 3)], credits: []) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(- payload: roles, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(+ payload: roles, metadata: BackupV16Fixtures.metadata())) } } }@@ -961,21 +961,21 @@ struct BackupV15CodecTests { @Test("A credit naming an absent work, creator and role is accepted") func unresolvedCreditsValidate() throws { let absentWork = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee98")!- let payload = BackupV15Fixtures.creditsPayload(+ let payload = BackupV16Fixtures.creditsPayload( credits: [- BackupV15Fixtures.creditRecord(- id: BackupV15Fixtures.orphanCreditID, workID: absentWork,- creatorID: BackupV15Fixtures.absentCreatorID,- roleIDs: [BackupV15Fixtures.absentRoleID])+ BackupV16Fixtures.creditRecord(+ id: BackupV16Fixtures.orphanCreditID, workID: absentWork,+ creatorID: BackupV16Fixtures.absentCreatorID,+ roleIDs: [BackupV16Fixtures.absentRoleID]) ]) - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) let credit = try #require(decoded.payload.credits.first) #expect(credit.workID == absentWork)- #expect(credit.creatorID == BackupV15Fixtures.absentCreatorID)- #expect(credit.roleIDs == [BackupV15Fixtures.absentRoleID.uuidString])+ #expect(credit.creatorID == BackupV16Fixtures.absentCreatorID)+ #expect(credit.roleIDs == [BackupV16Fixtures.absentRoleID.uuidString]) } // MARK: The citation arms@@ -986,11 +986,11 @@ struct BackupV15CodecTests { /// refused, and it still refuses. @Test("A composed identity with no name contributor refuses") func composedIdentityWithoutANameContributorRefuses() throws {- let payload = BackupV15Fixtures.composedPayload(dropNameContributor: true)+ let payload = BackupV16Fixtures.composedPayload(dropNameContributor: true) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } @@ -998,9 +998,9 @@ struct BackupV15CodecTests { /// `.rawURL` is a record that cannot say which key it holds. @Test("A URL-rule basis carrying a raw-URL citation arm refuses") func urlRuleBasisWithARawURLArmRefuses() throws {- let base = BackupV15Fixtures.composedPayload()+ let base = BackupV16Fixtures.composedPayload() let entry = try #require(base.entries.first)- let stripped = BackupV15Entry(+ let stripped = BackupV16Entry( id: entry.id, captureTitle: entry.captureTitle, captureTitleSource: entry.captureTitleSource, rawURL: entry.rawURL, canonicalURL: entry.canonicalURL, hostname: entry.hostname,@@ -1012,27 +1012,27 @@ struct BackupV15CodecTests { lastSharedAt: entry.lastSharedAt, modifiedAt: entry.modifiedAt, workID: entry.workID, intentionallyUnattached: entry.intentionallyUnattached, citations: EntryCitations(identity: .rawURL))- let payload = BackupV15Payload(+ let payload = BackupV16Payload( entries: [stripped], works: base.works, sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: base.memberships) #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) } } - @Test("A mismatched version pair around 15/16 is refused by the codec itself")+ @Test("A mismatched version pair around 16/17 is refused by the codec itself") func mismatchedPairsRefuse() throws {- let encoded = try BackupV15Codec.encode(- payload: BackupV15Fixtures.payload(), metadata: BackupV15Fixtures.metadata())+ let encoded = try BackupV16Codec.encode(+ payload: BackupV16Fixtures.payload(), metadata: BackupV16Fixtures.metadata()) var object = try #require( try JSONSerialization.jsonObject(with: encoded) as? [String: Any]) object["databaseSchemaVersion"] = 9 #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(try JSONSerialization.data(withJSONObject: object))+ try BackupV16Codec.decode(try JSONSerialization.data(withJSONObject: object)) } } @@ -1042,24 +1042,24 @@ struct BackupV15CodecTests { @Test("A 14/15 envelope is refused by the codec") func retiredEnvelopeRefuses() throws { #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(BackupV15Fixtures.retiredGenerationDocument())+ try BackupV16Codec.decode(BackupV16Fixtures.retiredGenerationDocument()) } } /// A citation is the rule's UUID since 8/9, so `version` is a key the codec /// does not write back — and the checksum is taken over the bytes as they- /// arrived. A 15/16 file carrying one therefore fails the re-encode+ /// arrived. A 16/17 file carrying one therefore fails the re-encode /// comparison, which is the same door every other unrepresentable key meets. /// /// The paired assertion is what makes this about the key rather than about /// the paste: the identical literal with `"version":3` removed decodes.- @Test("A 15/16 archive whose citation carries a version fails the checksum")+ @Test("A 16/17 archive whose citation carries a version fails the checksum") func citationVersionFailsTheChecksum() throws {- let document = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.citationVersionPayloadJSON, entryCount: 1, workCount: 1)+ let document = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.citationVersionPayloadJSON, entryCount: 1, workCount: 1) do {- _ = try BackupV15Codec.decode(document)+ _ = try BackupV16Codec.decode(document) Issue.record("expected a checksum refusal, but the document decoded") } catch let error as BackupCodecError { guard case .checksumMismatch = error else {@@ -1068,16 +1068,16 @@ struct BackupV15CodecTests { } } - let versionFree = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)- let decoded = try BackupV15Codec.decode(versionFree)+ let versionFree = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+ let decoded = try BackupV16Codec.decode(versionFree) #expect( decoded.payload.entries.first?.citations.chapterSequence == CitedRule(id: UUID(uuidString: "DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD")!)) } /// Req 8.1 and Q34 from the wire side: the three status fields are declared- /// without `decodeIfPresent` and without a default, so a 15/16 document whose+ /// without `decodeIfPresent` and without a default, so a 16/17 document whose /// Work record omits them is malformed rather than restorable. A default /// would put a reader's abandoned work back as one they are still reading. ///@@ -1085,13 +1085,13 @@ struct BackupV15CodecTests { /// gives up on the missing key before the payload is ever re-encoded — and /// the paired assertion pins it to the three keys rather than to the paste: /// the identical literal carrying them decodes.- @Test("A 15/16 Work record omitting the three status fields fails to decode")+ @Test("A 16/17 Work record omitting the three status fields fails to decode") func workOmittingTheStatusFieldsRefuses() throws {- let document = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.statusFieldsOmittedPayloadJSON, entryCount: 1, workCount: 1)+ let document = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.statusFieldsOmittedPayloadJSON, entryCount: 1, workCount: 1) do {- _ = try BackupV15Codec.decode(document)+ _ = try BackupV16Codec.decode(document) Issue.record("expected a decode refusal, but the document decoded") } catch let error as BackupCodecError { guard case .decodingFailed = error else {@@ -1100,9 +1100,9 @@ struct BackupV15CodecTests { } } - let complete = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)- let record = try #require(try BackupV15Codec.decode(complete).payload.works.first)+ let complete = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+ let record = try #require(try BackupV16Codec.decode(complete).payload.works.first) #expect(record.workStatus == .ongoing) #expect(record.readingStatus == .reading) #expect(record.verdict.isEmpty)@@ -1111,17 +1111,17 @@ struct BackupV15CodecTests { /// Req 5.1 and Q51 from the wire side. The two place arrays are declared /// like every other array — no `decodeIfPresent`, no default — so a payload /// shaped the way a **pre-place** build wrote one is malformed here even- /// when someone has relabelled its envelope 15/16. That is the same door the+ /// when someone has relabelled its envelope 16/17. That is the same door the /// version refusal is, reached from the other side: an 11/12 file holds no /// place, and a default would restore a library asserting the reader had /// accepted none.- @Test("A 15/16 payload without the two place arrays fails to decode")+ @Test("A 16/17 payload without the two place arrays fails to decode") func payloadOmittingThePlaceArraysRefuses() throws {- let document = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.placeArraysOmittedPayloadJSON, entryCount: 1, workCount: 1)+ let document = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.placeArraysOmittedPayloadJSON, entryCount: 1, workCount: 1) do {- _ = try BackupV15Codec.decode(document)+ _ = try BackupV16Codec.decode(document) Issue.record("expected a decode refusal, but the document decoded") } catch let error as BackupCodecError { guard case .decodingFailed = error else {@@ -1132,9 +1132,9 @@ struct BackupV15CodecTests { // And the identical literal carrying the two empty arrays decodes, so // the refusal is about them rather than about the paste.- let complete = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)- let decoded = try BackupV15Codec.decode(complete)+ let complete = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+ let decoded = try BackupV16Codec.decode(complete) #expect(decoded.payload.places.isEmpty) #expect(decoded.payload.placeSuppressions.isEmpty) }@@ -1150,9 +1150,9 @@ struct BackupV15CodecTests { /// codec refuses this one before any record is seen. @Test("A cover whose base64 does not decode refuses the whole archive") func undecodableCoverBase64RefusesTheArchive() throws {- let encoded = try BackupV15Codec.encode(- payload: BackupV15Fixtures.coveredPayload(),- metadata: BackupV15Fixtures.metadata())+ let encoded = try BackupV16Codec.encode(+ payload: BackupV16Fixtures.coveredPayload(),+ metadata: BackupV16Fixtures.metadata()) let text = try #require(String(data: encoded, encoding: .utf8)) // The cover's own field, not `thumbnailShape`: the closing quote and // the colon are part of the match.@@ -1162,11 +1162,11 @@ struct BackupV15CodecTests { in: field, with: "\"thumbnail\":\"not base64 @@@@\"") #expect(throws: BackupCodecError.self) {- try BackupV15Codec.decode(Data(corrupted.utf8))+ try BackupV16Codec.decode(Data(corrupted.utf8)) } // The same document with its cover intact decodes, so the refusal is // about the base64 rather than about the edit.- #expect(try BackupV15Codec.decode(encoded).payload.works.first?.thumbnail != nil)+ #expect(try BackupV16Codec.decode(encoded).payload.works.first?.thumbnail != nil) } /// Req 3.2: the version invariants are retired, so an archive whose Site@@ -1174,10 +1174,10 @@ struct BackupV15CodecTests { /// retired one is a file the reference checks accept. @Test("An archive with duplicate and non-greatest rule versions decodes") func duplicateAndNonGreatestVersionsDecode() throws {- let payload = BackupV15Fixtures.duplicateVersionsPayload()+ let payload = BackupV16Fixtures.duplicateVersionsPayload() - let decoded = try BackupV15Codec.decode(- try BackupV15Codec.encode(payload: payload, metadata: BackupV15Fixtures.metadata()))+ let decoded = try BackupV16Codec.decode(+ try BackupV16Codec.encode(payload: payload, metadata: BackupV16Fixtures.metadata())) #expect(decoded.payload == payload) #expect(decoded.payload.titlePatterns.map(\.version) == [1, 1])@@ -1188,7 +1188,7 @@ struct BackupV15CodecTests { // MARK: - Export @Suite("Backup V15 export", .serialized)-struct BackupV15ExportTests {+struct BackupV16ExportTests { private static let host = "characters.example" private static let workID = UUID(uuidString: "60000000-0000-4000-8000-000000000001")! private static let entryID = UUID(uuidString: "60000000-0000-4000-8000-000000000002")!@@ -1204,21 +1204,21 @@ struct BackupV15ExportTests { private static let note = "Grover promised to guide them home." private static let genericNotes = "The guide is not what he seems." - @Test("Exporter produces a v15 filename and a valid, decodable 15/16 document")+ @Test("Exporter produces a v16 filename and a valid, decodable 16/17 document") func exporterProducesValidDocument() async throws { let tempDir = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: tempDir) } - let payload = BackupV15Fixtures.payload()- let exporter = BackupV15Exporter(+ let payload = BackupV16Fixtures.payload()+ let exporter = BackupV16Exporter( repository: MockV15SnapshotProvider(payload: payload), stagingDirectory: tempDir)- let result = try await exporter.export(metadata: BackupV15Fixtures.metadata())+ let result = try await exporter.export(metadata: BackupV16Fixtures.metadata()) - #expect(result.fileURL.lastPathComponent.contains("v15"))- let decoded = try BackupV15Codec.decode(try Data(contentsOf: result.fileURL))- #expect(decoded.backupFormatVersion == 15)- #expect(decoded.databaseSchemaVersion == 16)+ #expect(result.fileURL.lastPathComponent.contains("v16"))+ let decoded = try BackupV16Codec.decode(try Data(contentsOf: result.fileURL))+ #expect(decoded.backupFormatVersion == 16)+ #expect(decoded.databaseSchemaVersion == 17) #expect(decoded.payload == payload) exporter.cleanup(result) }@@ -1230,7 +1230,7 @@ struct BackupV15ExportTests { /// /// The second half is asserted over the encoded JSON rather than over the /// record, because that is where it could go wrong: a `thumbnailDigest`- /// property added to `BackupV15Work` would put a second copy of a derived+ /// property added to `BackupV16Work` would put a second copy of a derived /// fact in the file and invite the two to disagree, and no assertion on /// decoded values would notice. @Test("A work's cover projects onto the archive record, without its digest")@@ -1238,20 +1238,20 @@ struct BackupV15ExportTests { let store = try LibraryStore() store.setThumbnail( shapeRaw: ThumbnailShape.portrait.rawValue,- bytes: BackupV15Fixtures.coverBytes, digest: BackupV15Fixtures.coverDigest)+ bytes: BackupV16Fixtures.coverBytes, digest: BackupV16Fixtures.coverDigest) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let record = try #require(payload.works.first { $0.id == Self.workID }) #expect(record.thumbnailShape == ThumbnailShape.portrait.rawValue)- #expect(record.thumbnail == BackupV15Fixtures.coverBytes)+ #expect(record.thumbnail == BackupV16Fixtures.coverBytes) - let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata()) let text = try #require(String(data: encoded, encoding: .utf8)) #expect(!text.contains("thumbnailDigest"))- #expect(!text.contains(BackupV15Fixtures.coverDigest))+ #expect(!text.contains(BackupV16Fixtures.coverDigest)) } /// Decision 3: a cover the reader zoomed out on is stored shorter than its@@ -1264,15 +1264,15 @@ struct BackupV15ExportTests { let store = try LibraryStore() store.setThumbnail( shapeRaw: ThumbnailShape.portrait.rawValue,- bytes: BackupV15Fixtures.gappedCoverBytes,- digest: BackupV15Fixtures.gappedCoverDigest)+ bytes: BackupV16Fixtures.gappedCoverBytes,+ digest: BackupV16Fixtures.gappedCoverDigest) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let record = try #require(payload.works.first { $0.id == Self.workID }) #expect(record.thumbnailShape == ThumbnailShape.portrait.rawValue)- #expect(record.thumbnail == BackupV15Fixtures.gappedCoverBytes)+ #expect(record.thumbnail == BackupV16Fixtures.gappedCoverBytes) } /// Req 8.3 as Q52 amends it, and the one cover state that must **not**@@ -1287,7 +1287,7 @@ struct BackupV15ExportTests { shapeRaw: ThumbnailShape.square.rawValue, bytes: nil, digest: "never-arrived") try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let record = try #require(payload.works.first { $0.id == Self.workID }) #expect(record.thumbnailShape == nil)@@ -1308,19 +1308,19 @@ struct BackupV15ExportTests { let store = try LibraryStore() store.setThumbnail( shapeRaw: ThumbnailShape.portrait.rawValue, bytes: nil,- digest: BackupV15Fixtures.coverDigest)+ digest: BackupV16Fixtures.coverDigest) store.insertSiblingRow(- shapeRaw: ThumbnailShape.portrait.rawValue, bytes: BackupV15Fixtures.coverBytes,- digest: BackupV15Fixtures.coverDigest)+ shapeRaw: ThumbnailShape.portrait.rawValue, bytes: BackupV16Fixtures.coverBytes,+ digest: BackupV16Fixtures.coverDigest) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) // One record for the group, whichever row the bytes came off. #expect(payload.works.count == 1) let record = try #require(payload.works.first { $0.id == Self.workID }) #expect(record.thumbnailShape == ThumbnailShape.portrait.rawValue)- #expect(record.thumbnail == BackupV15Fixtures.coverBytes)+ #expect(record.thumbnail == BackupV16Fixtures.coverBytes) } /// The same shape with the carrier holding **stale** bytes: the cover the@@ -1335,16 +1335,16 @@ struct BackupV15ExportTests { let stale = Data("the cover this work used to have".utf8) store.setThumbnail( shapeRaw: ThumbnailShape.portrait.rawValue, bytes: stale,- digest: BackupV15Fixtures.coverDigest)+ digest: BackupV16Fixtures.coverDigest) store.insertSiblingRow(- shapeRaw: ThumbnailShape.portrait.rawValue, bytes: BackupV15Fixtures.coverBytes,- digest: BackupV15Fixtures.coverDigest)+ shapeRaw: ThumbnailShape.portrait.rawValue, bytes: BackupV16Fixtures.coverBytes,+ digest: BackupV16Fixtures.coverDigest) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let record = try #require(payload.works.first { $0.id == Self.workID })- #expect(record.thumbnail == BackupV15Fixtures.coverBytes)+ #expect(record.thumbnail == BackupV16Fixtures.coverBytes) #expect(record.thumbnail != stale) } @@ -1364,15 +1364,15 @@ struct BackupV15ExportTests { digest: Hexadecimal.sha256(bytes)) try store.context.save() - let error = #expect(throws: BackupV15ExportError.self) {- _ = try LibraryRepository.projectV15Payload(context: store.context)+ let error = #expect(throws: BackupV16ExportError.self) {+ _ = try LibraryRepository.projectV16Payload(context: store.context) } guard case .unrepresentableValue(let record, let field, _) = error else { Issue.record("expected .unrepresentableValue, got \(String(describing: error))") return } #expect(record.contains("A Work"))- #expect(field == BackupV15ExportError.thumbnailField)+ #expect(field == BackupV16ExportError.thumbnailField) #expect(error?.description.contains("A Work") == true) #expect(error?.description.contains("Remove the cover") == true) #expect(error?.description.contains("resolve it first") == true)@@ -1391,19 +1391,19 @@ struct BackupV15ExportTests { func unknownCoverShapeRefusesByTitle() throws { let store = try LibraryStore() store.setThumbnail(- shapeRaw: "hexagon", bytes: BackupV15Fixtures.coverBytes,- digest: BackupV15Fixtures.coverDigest)+ shapeRaw: "hexagon", bytes: BackupV16Fixtures.coverBytes,+ digest: BackupV16Fixtures.coverDigest) try store.context.save() - let error = #expect(throws: BackupV15ExportError.self) {- _ = try LibraryRepository.projectV15Payload(context: store.context)+ let error = #expect(throws: BackupV16ExportError.self) {+ _ = try LibraryRepository.projectV16Payload(context: store.context) } guard case .unrepresentableValue(let record, let field, let value) = error else { Issue.record("expected .unrepresentableValue, got \(String(describing: error))") return } #expect(record.contains("A Work"))- #expect(field == BackupV15ExportError.thumbnailField)+ #expect(field == BackupV16ExportError.thumbnailField) #expect(value == "hexagon") } @@ -1421,8 +1421,8 @@ struct BackupV15ExportTests { store.setReleaseDaysRaw(["monday", "funday"]) try store.context.save() - let error = #expect(throws: BackupV15ExportError.self) {- _ = try LibraryRepository.projectV15Payload(context: store.context)+ let error = #expect(throws: BackupV16ExportError.self) {+ _ = try LibraryRepository.projectV16Payload(context: store.context) } guard case .unrepresentableValue(let record, let field, let value) = error else { Issue.record("expected .unrepresentableValue, got \(String(describing: error))")@@ -1441,7 +1441,7 @@ struct BackupV15ExportTests { store.setReleaseDaysRaw(["thursday", "monday"]) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let record = try #require(payload.works.first { $0.id == Self.workID }) #expect(record.releaseDays == [.monday, .thursday])@@ -1465,7 +1465,7 @@ struct BackupV15ExportTests { store.coverGenericNotes() try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let character = try #require(payload.characters.first) #expect(character.id == Self.characterID)@@ -1511,7 +1511,7 @@ struct BackupV15ExportTests { store.context.insert(twin) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) // One record for the pair, and it is the survivor's — carrying the // address the discarded row held.@@ -1530,15 +1530,15 @@ struct BackupV15ExportTests { store.insertCharacter(id: Self.orphanID, name: "Stranger", attachToWork: false) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let orphan = try #require(payload.characters.first { $0.id == Self.orphanID }) #expect(orphan.workID == nil) // And the file it produces is legal: the validator's exemption and the // exporter's enumeration have to agree, or the export refuses its own bytes.- let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).payload == payload)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).payload == payload) } /// Req 6.5. One character UUID over two rows that disagree about something@@ -1551,8 +1551,8 @@ struct BackupV15ExportTests { store.insertCharacter(id: Self.characterID, name: "Grover", note: "A traitor.") try store.context.save() - #expect(throws: BackupV15ExportError.self) {- try LibraryRepository.projectV15Payload(context: store.context)+ #expect(throws: BackupV16ExportError.self) {+ try LibraryRepository.projectV16Payload(context: store.context) } } @@ -1571,12 +1571,12 @@ struct BackupV15ExportTests { ]) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) #expect(payload.characters.first?.facts.first?.source == .entry(absent))- let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).payload == payload)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).payload == payload) } // MARK: The places (Req 5.1, 5.3, 5.5)@@ -1598,7 +1598,7 @@ struct BackupV15ExportTests { store.insertPlaceSuppression(nameKey: "low road") try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let place = try #require(payload.places.first) #expect(place.id == Self.placeID)@@ -1627,7 +1627,7 @@ struct BackupV15ExportTests { store.insertPlaceSuppression(nameKey: "elsewhere", workID: Self.absentWorkID) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let orphan = try #require(payload.places.first { $0.id == Self.orphanPlaceID }) #expect(orphan.workID == Self.absentWorkID)@@ -1635,9 +1635,9 @@ struct BackupV15ExportTests { // And the file it produces is legal: the validator's exemption and the // exporter's enumeration have to agree, or the export refuses its own // bytes.- let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).payload == payload)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).payload == payload) } /// Req 5.3: a torn place group is the same thing a torn character group is —@@ -1650,8 +1650,8 @@ struct BackupV15ExportTests { store.insertPlace(id: Self.placeID, name: "The High Keep", note: "Still garrisoned.") try store.context.save() - #expect(throws: BackupV15ExportError.self) {- try LibraryRepository.projectV15Payload(context: store.context)+ #expect(throws: BackupV16ExportError.self) {+ try LibraryRepository.projectV16Payload(context: store.context) } } @@ -1678,7 +1678,7 @@ struct BackupV15ExportTests { store.insertLink(id: selfLink, a: Self.workID, b: Self.workID, type: "sequel") try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) #expect(payload.links.map(\.id) == [newer]) #expect(payload.links.map(\.linkType) == ["sequel"])@@ -1697,7 +1697,7 @@ struct BackupV15ExportTests { store.placeWork(seriesID: seriesID, position: 2.5) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) #expect(payload.series.map(\.id) == [seriesID]) #expect(payload.series.first?.name == "Ashfall Cycle")@@ -1724,8 +1724,8 @@ struct BackupV15ExportTests { store.placeWork(seriesID: id, position: position) try store.context.save() - let error = #expect(throws: BackupV15ExportError.self) {- try LibraryRepository.projectV15Payload(context: store.context)+ let error = #expect(throws: BackupV16ExportError.self) {+ try LibraryRepository.projectV16Payload(context: store.context) } guard case .unrepresentableValue(let record, _, _) = error else { Issue.record("expected an unrepresentable-value refusal, got \(String(describing: error))")@@ -1762,7 +1762,7 @@ struct BackupV15ExportTests { store.insertCreatorRole(id: Self.roleID, name: "letterer", position: 3) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) #expect(payload.creators.count == 3) let record = try #require(payload.creators.first { $0.id == mori })@@ -1780,9 +1780,9 @@ struct BackupV15ExportTests { // And the file it produces is legal: the projection and the reference // checks have to agree, or the export refuses its own bytes.- let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).payload == payload)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).payload == payload) } /// Q68: a merged record whose survivor is not in the library reads as@@ -1799,14 +1799,14 @@ struct BackupV15ExportTests { stateModifiedAt: Self.early) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let record = try #require(payload.creators.first { $0.id == alias }) #expect(record.stateRaw == CreatorState.merged.rawValue) #expect(record.canonicalID == nil)- let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).payload == payload)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).payload == payload) } /// Req 9.2: one credit per work-and-creator pair, bucketed on the@@ -1837,7 +1837,7 @@ struct BackupV15ExportTests { modifiedAt: Self.early.addingTimeInterval(120)) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) #expect(payload.credits.count == 1) let record = try #require(payload.credits.first)@@ -1885,7 +1885,7 @@ struct BackupV15ExportTests { modifiedAt: Self.early.addingTimeInterval(120)) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) #expect(payload.creators.count == 2) #expect(@@ -1909,9 +1909,9 @@ struct BackupV15ExportTests { #expect(credit.roleIDs == [author.uuidString, artist.uuidString].sorted()) // The check that used to refuse this library's own archive.- let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).payload == payload)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).payload == payload) } /// Req 10.2 at the export door: nothing is pruned for naming a work,@@ -1929,15 +1929,15 @@ struct BackupV15ExportTests { createdAt: Self.early, modifiedAt: Self.early) try store.context.save() - let payload = try LibraryRepository.projectV15Payload(context: store.context)+ let payload = try LibraryRepository.projectV16Payload(context: store.context) let record = try #require(payload.credits.first) #expect(record.workID == absentWork) #expect(record.creatorID == absentCreator) #expect(record.roleIDs == [absentRole.uuidString])- let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).payload == payload)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).payload == payload) } // MARK: - Fixture@@ -1954,7 +1954,7 @@ struct BackupV15ExportTests { private var carrier: Work! init() throws {- let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) container = try ModelContainer( for: schema, configurations: [@@ -1962,23 +1962,23 @@ struct BackupV15ExportTests { schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none) ]) context = ModelContext(container)- let site = Site(hostname: BackupV15ExportTests.host, displayName: "Characters")+ let site = Site(hostname: BackupV16ExportTests.host, displayName: "Characters") site.mode = .untaught context.insert(site) let work = Work.create(- in: context, id: BackupV15ExportTests.workID, title: "A Work",- hostname: BackupV15ExportTests.host, site: site,- timestamp: BackupV15ExportTests.early)- work.genericNotes = BackupV15ExportTests.genericNotes+ in: context, id: BackupV16ExportTests.workID, title: "A Work",+ hostname: BackupV16ExportTests.host, site: site,+ timestamp: BackupV16ExportTests.early)+ work.genericNotes = BackupV16ExportTests.genericNotes carrier = work - let rawURL = "https://\(BackupV15ExportTests.host)/read/1"+ let rawURL = "https://\(BackupV16ExportTests.host)/read/1" let entry = Entry(- id: BackupV15ExportTests.entryID, captureTitle: "Chapter 1",+ id: BackupV16ExportTests.entryID, captureTitle: "Chapter 1", captureTitleSource: .host, rawURLString: rawURL,- hostname: BackupV15ExportTests.host, entryIdentityKey: rawURL,- timestamp: BackupV15ExportTests.early, note: BackupV15ExportTests.note)+ hostname: BackupV16ExportTests.host, entryIdentityKey: rawURL,+ timestamp: BackupV16ExportTests.early, note: BackupV16ExportTests.note) entry.conservativeIdentityKey = rawURL entry.editCitations { $0.workAssignment = .manual } context.insert(entry)@@ -1995,14 +1995,14 @@ struct BackupV15ExportTests { let character = CharacterRecord( id: id, name: name, nameKey: RecordNameKey.normalize(name), aliases: aliases, note: note, facts: facts,- timestamp: BackupV15ExportTests.early)+ timestamp: BackupV16ExportTests.early) context.insert(character) if attachToWork { character.work = work } } func insertSuppression(nameKey: String) { let row = CharacterSuppression(- kind: .candidate, nameKey: nameKey, actionAt: BackupV15ExportTests.early)+ kind: .candidate, nameKey: nameKey, actionAt: BackupV16ExportTests.early) context.insert(row) row.work = work }@@ -2012,22 +2012,22 @@ struct BackupV15ExportTests { /// seed the non-resolving owner of Req 5.5. func insertPlace( id: UUID, name: String, aliases: [String] = [], note: String = "",- facts: [RecordFact] = [], workID: UUID = BackupV15ExportTests.workID+ facts: [RecordFact] = [], workID: UUID = BackupV16ExportTests.workID ) { context.insert( Place( id: id, name: name, nameKey: RecordNameKey.normalize(name), aliases: aliases, note: note, facts: facts,- timestamp: BackupV15ExportTests.early, workID: workID))+ timestamp: BackupV16ExportTests.early, workID: workID)) } func insertPlaceSuppression(- nameKey: String, workID: UUID = BackupV15ExportTests.workID+ nameKey: String, workID: UUID = BackupV16ExportTests.workID ) { context.insert( PlaceSuppression( workID: workID, kind: .candidate, nameKey: nameKey,- actionAt: BackupV15ExportTests.early))+ actionAt: BackupV16ExportTests.early)) } /// The three cover columns, written straight onto the work row.@@ -2053,9 +2053,9 @@ struct BackupV15ExportTests { /// original row the carrier. func insertSiblingRow(shapeRaw: String?, bytes: Data?, digest: String?) { let sibling = Work.create(- in: context, id: BackupV15ExportTests.workID, title: carrier.displayTitle,- hostname: BackupV15ExportTests.host, site: carrier.primaryMembership?.site,- timestamp: BackupV15ExportTests.early.addingTimeInterval(60))+ in: context, id: BackupV16ExportTests.workID, title: carrier.displayTitle,+ hostname: BackupV16ExportTests.host, site: carrier.primaryMembership?.site,+ timestamp: BackupV16ExportTests.early.addingTimeInterval(60)) sibling.lastParsedTitle = carrier.lastParsedTitle sibling.titleProvenanceRaw = carrier.titleProvenanceRaw sibling.genericNotes = carrier.genericNotes@@ -2073,20 +2073,20 @@ struct BackupV15ExportTests { func coverEntry() { try? context.fetch(FetchDescriptor<Entry>()).first? .characterExtractionFingerprint = CharacterCoverageFingerprint.of(- BackupV15ExportTests.note)+ BackupV16ExportTests.note) } func coverGenericNotes() { work?.genericNotesExtractionFingerprint = CharacterCoverageFingerprint.of(- BackupV15ExportTests.genericNotes)+ BackupV16ExportTests.genericNotes) } // `series-and-related-works` Req 13. func insertSeries( id: UUID, name: String, notes: String = "",- createdAt: Date = BackupV15ExportTests.early,- modifiedAt: Date = BackupV15ExportTests.early+ createdAt: Date = BackupV16ExportTests.early,+ modifiedAt: Date = BackupV16ExportTests.early ) { context.insert( Series(@@ -2098,13 +2098,13 @@ struct BackupV15ExportTests { /// self-link no writer produces and the projection drops. func insertLink( id: UUID, a: UUID, b: UUID, type: String,- modifiedAt: Date = BackupV15ExportTests.early+ modifiedAt: Date = BackupV16ExportTests.early ) { let sorted = WorkDistinctPair.sortedIDs(a, b) context.insert( WorkLink( id: id, lowerWorkID: sorted.lower, higherWorkID: sorted.higher,- linkType: type, createdAt: BackupV15ExportTests.early,+ linkType: type, createdAt: BackupV16ExportTests.early, modifiedAt: modifiedAt)) } @@ -2135,7 +2135,7 @@ struct BackupV15ExportTests { let row = Creator( id: id, name: name, notes: notes, stateRaw: state.rawValue, canonicalID: canonicalID)- row.createdAt = BackupV15ExportTests.early+ row.createdAt = BackupV16ExportTests.early row.nameModifiedAt = nameModifiedAt row.notesModifiedAt = notesModifiedAt row.stateModifiedAt = stateModifiedAt@@ -2146,14 +2146,14 @@ struct BackupV15ExportTests { func insertCreatorRole( id: UUID, name: String, position: Int, state: CreatorRoleState = .active, canonicalID: UUID? = nil,- nameModifiedAt: Date = BackupV15ExportTests.early,- positionModifiedAt: Date = BackupV15ExportTests.early,- stateModifiedAt: Date = BackupV15ExportTests.early+ nameModifiedAt: Date = BackupV16ExportTests.early,+ positionModifiedAt: Date = BackupV16ExportTests.early,+ stateModifiedAt: Date = BackupV16ExportTests.early ) { let row = CreatorRole( id: id, name: name, position: position, stateRaw: state.rawValue, canonicalID: canonicalID)- row.createdAt = BackupV15ExportTests.early+ row.createdAt = BackupV16ExportTests.early row.nameModifiedAt = nameModifiedAt row.positionModifiedAt = positionModifiedAt row.stateModifiedAt = stateModifiedAt@@ -2176,20 +2176,20 @@ struct BackupV15ExportTests { // MARK: - Import -@Suite("Backup 15/16 import", .serialized)-struct BackupV15ImportTests {+@Suite("Backup 16/17 import", .serialized)+struct BackupV16ImportTests { // MARK: One accepted pair (Decision 2) - @Test("The importer accepts 15/16")+ @Test("The importer accepts 16/17") func acceptedGeneration() throws {- let data = try BackupV15Codec.encode(- payload: BackupV15Fixtures.payload(), metadata: BackupV15Fixtures.metadata())+ let data = try BackupV16Codec.encode(+ payload: BackupV16Fixtures.payload(), metadata: BackupV16Fixtures.metadata()) let plan = try BackupImporter.plan(from: data)- #expect(plan.metadata.formatVersion == 15)- #expect(plan.metadata.schemaVersion == 16)- #expect(plan.payload == BackupImportPayload(BackupV15Fixtures.payload()))+ #expect(plan.metadata.formatVersion == 16)+ #expect(plan.metadata.schemaVersion == 17)+ #expect(plan.payload == BackupImportPayload(BackupV16Fixtures.payload())) } /// The retired generations refuse **by version**, and the refusal names the@@ -2207,11 +2207,11 @@ struct BackupV15ImportTests { @Test( "A retired generation refuses by version, naming the pair", arguments: [- (14, 15), (13, 14), (12, 13), (11, 12), (10, 11), (9, 10), (8, 9), (7, 8), (6, 7),+ (15, 16), (14, 15), (13, 14), (12, 13), (11, 12), (10, 11), (9, 10), (8, 9), (7, 8), (6, 7), (4, 4), (5, 6), (3, 3), ]) func retiredGenerationsRefuseByVersion(pair: (format: Int, schema: Int)) throws {- let data = BackupV15Fixtures.retiredGenerationDocument(+ let data = BackupV16Fixtures.retiredGenerationDocument( format: pair.format, schema: pair.schema) // The envelope is intact — this is a version refusal, not a decode one. #expect((try? JSONSerialization.jsonObject(with: data)) != nil)@@ -2226,10 +2226,10 @@ struct BackupV15ImportTests { #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("(\(BackupV15Document.formatVersion)/\(BackupV15Document.schemaVersion))"))+ #expect(reason.contains("(\(BackupV16Document.formatVersion)/\(BackupV16Document.schemaVersion))")) } - @Test("A mismatched pair around 15/16 is unsupported")+ @Test("A mismatched pair around 16/17 is unsupported") func mismatchedPairsReject() throws { for (format, schema) in [(15, 15), (15, 17), (14, 16), (16, 16)] { let data = try JSONSerialization.data(withJSONObject: [@@ -2244,40 +2244,40 @@ struct BackupV15ImportTests { // MARK: What lands (Req 6.1) - @Test("A 15/16 archive commits its characters, suppressions and coverage")+ @Test("A 16/17 archive commits its characters, suppressions and coverage") func archiveCommits() async throws { let fixture = try await M5Fixture() let result = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.payload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.payload())) guard case .committed = result else { Issue.record("expected committed, got \(result)") return } let characters = try await fixture.repository.m5AllCharacters()- let grover = try #require(characters.first { $0.id == BackupV15Fixtures.groverID })+ let grover = try #require(characters.first { $0.id == BackupV16Fixtures.groverID }) #expect(grover.name == "Grover") #expect(grover.nameKey == "grover") #expect(grover.aliases == ["Klar"]) #expect(grover.note == "The guide.") #expect(grover.facts.map(\.quote) == ["promised to guide them home"])- #expect(grover.facts.first?.source == .entry(BackupV15Fixtures.entryID))- #expect(grover.workID == BackupV15Fixtures.workID, "the character joins its work")+ #expect(grover.facts.first?.source == .entry(BackupV16Fixtures.entryID))+ #expect(grover.workID == BackupV16Fixtures.workID, "the character joins its work") let suppressions = try await fixture.repository.m5SuppressionRows()- let row = try #require(suppressions.first { $0.id == BackupV15Fixtures.suppressionID })+ let row = try #require(suppressions.first { $0.id == BackupV16Fixtures.suppressionID }) #expect(row.nameKey == "the crowned one") #expect(row.kind == .candidate) #expect(row.status == .active)- #expect(row.workID == BackupV15Fixtures.workID)+ #expect(row.workID == BackupV16Fixtures.workID) #expect(- try await fixture.repository.m5EntryCoverage(BackupV15Fixtures.entryID)- == BackupV15Fixtures.noteFingerprint)+ try await fixture.repository.m5EntryCoverage(BackupV16Fixtures.entryID)+ == BackupV16Fixtures.noteFingerprint) #expect(- try await fixture.repository.m5WorkCoverage(BackupV15Fixtures.workID)- == BackupV15Fixtures.genericNotesFingerprint)+ try await fixture.repository.m5WorkCoverage(BackupV16Fixtures.workID)+ == BackupV16Fixtures.genericNotesFingerprint) } /// Req 6.7 through the archive: a character with no work is a tolerated@@ -2287,14 +2287,14 @@ struct BackupV15ImportTests { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload( characters: [- BackupV15Fixtures.character(id: BackupV15Fixtures.orphanID, workID: nil)+ BackupV16Fixtures.character(id: BackupV16Fixtures.orphanID, workID: nil) ]))) let characters = try await fixture.repository.m5AllCharacters()- let orphan = try #require(characters.first { $0.id == BackupV15Fixtures.orphanID })+ let orphan = try #require(characters.first { $0.id == BackupV16Fixtures.orphanID }) #expect(orphan.workID == nil) } @@ -2306,13 +2306,13 @@ struct BackupV15ImportTests { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(entryFingerprint: "not-this-note")))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload(entryFingerprint: "not-this-note"))) - #expect(try await fixture.repository.m5EntryCoverage(BackupV15Fixtures.entryID) == nil)+ #expect(try await fixture.repository.m5EntryCoverage(BackupV16Fixtures.entryID) == nil) #expect(- try await fixture.repository.m5WorkCoverage(BackupV15Fixtures.workID)- == BackupV15Fixtures.genericNotesFingerprint)+ try await fixture.repository.m5WorkCoverage(BackupV16Fixtures.workID)+ == BackupV16Fixtures.genericNotesFingerprint) } // MARK: Value guards and idempotence (Req 6.1, 7.7's shape)@@ -2321,22 +2321,22 @@ struct BackupV15ImportTests { /// rows: the memberships and the pairs are asserted beside the characters and /// suppressions, because they are the two the 7/8 format added and the two a /// second import could silently rewrite.- @Test("Importing the same 15/16 archive twice changes nothing the second time")+ @Test("Importing the same 16/17 archive twice changes nothing the second time") func importingTwiceChangesNothing() async throws { let fixture = try await M5Fixture()- let base = BackupV15Fixtures.payload()+ let base = BackupV16Fixtures.payload() let stranger = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee99")!- let ids = WorkDistinctPair.sortedIDs(BackupV15Fixtures.workID, stranger)- let plan = BackupV15Fixtures.plan(- BackupV15Payload(+ let ids = WorkDistinctPair.sortedIDs(BackupV16Fixtures.workID, stranger)+ let plan = BackupV16Fixtures.plan(+ BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: base.memberships, distinctPairs: [- BackupV15DistinctPair(+ BackupV16DistinctPair( id: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee98")!, lowerWorkID: ids.lower, higherWorkID: ids.higher,- recordedAt: BackupV15Fixtures.created)+ recordedAt: BackupV16Fixtures.created) ], characters: base.characters, suppressions: base.suppressions, places: base.places, placeSuppressions: base.placeSuppressions))@@ -2361,20 +2361,20 @@ struct BackupV15ImportTests { func olderArchiveDoesNotRegressACharacter() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.payload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.payload())) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload( characters: [- BackupV15Fixtures.character(+ BackupV16Fixtures.character( name: "Renamed by an older device", note: "older",- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(-1_000))+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(-1_000)) ]))) let grover = try #require( try await fixture.repository.m5AllCharacters()- .first { $0.id == BackupV15Fixtures.groverID })+ .first { $0.id == BackupV16Fixtures.groverID }) #expect(grover.name == "Grover") #expect(grover.note == "The guide.") }@@ -2391,25 +2391,25 @@ struct BackupV15ImportTests { @Test("An archived cover restores byte-identical, with the digest re-derived") func archivedCoverRestoresWithTheDigestReDerived() async throws { let fixture = try await M5Fixture()- let archive = try BackupV15Codec.encode(- payload: BackupV15Fixtures.coveredPayload(),- metadata: BackupV15Fixtures.metadata())+ let archive = try BackupV16Codec.encode(+ payload: BackupV16Fixtures.coveredPayload(),+ metadata: BackupV16Fixtures.metadata()) try await fixture.repository.confirmImport(plan: try BackupImporter.plan(from: archive)) #expect(- try await fixture.repository.thumbnailColumns(of: BackupV15Fixtures.workID)+ try await fixture.repository.thumbnailColumns(of: BackupV16Fixtures.workID) == [ThumbnailColumns(- byteCount: BackupV15Fixtures.coverBytes.count,+ byteCount: BackupV16Fixtures.coverBytes.count, shapeRaw: ThumbnailShape.portrait.rawValue,- digest: BackupV15Fixtures.coverDigest)])+ digest: BackupV16Fixtures.coverDigest)]) // Byte-identical, not merely the same length — and read back through the // production accessor, which is digest-gated, so a mismatch reads as nil // rather than as the wrong picture. #expect( try await fixture.repository.thumbnailBytes(- workID: BackupV15Fixtures.workID, digest: BackupV15Fixtures.coverDigest)- == BackupV15Fixtures.coverBytes)+ workID: BackupV16Fixtures.workID, digest: BackupV16Fixtures.coverDigest)+ == BackupV16Fixtures.coverBytes) } /// Decision 3 through the whole archive: a cover stored shorter than its box@@ -2420,10 +2420,10 @@ struct BackupV15ImportTests { @Test("A gapped cover round-trips and is not dropped on import") func gappedCoverRoundTrips() async throws { let fixture = try await M5Fixture()- let archive = try BackupV15Codec.encode(- payload: BackupV15Fixtures.coveredPayload(- bytes: BackupV15Fixtures.gappedCoverBytes),- metadata: BackupV15Fixtures.metadata())+ let archive = try BackupV16Codec.encode(+ payload: BackupV16Fixtures.coveredPayload(+ bytes: BackupV16Fixtures.gappedCoverBytes),+ metadata: BackupV16Fixtures.metadata()) let result = try await fixture.repository.confirmImport( plan: try BackupImporter.plan(from: archive))@@ -2435,9 +2435,9 @@ struct BackupV15ImportTests { #expect(report.droppedThumbnails.isEmpty) #expect( try await fixture.repository.thumbnailBytes(- workID: BackupV15Fixtures.workID,- digest: BackupV15Fixtures.gappedCoverDigest)- == BackupV15Fixtures.gappedCoverBytes)+ workID: BackupV16Fixtures.workID,+ digest: BackupV16Fixtures.gappedCoverDigest)+ == BackupV16Fixtures.gappedCoverBytes) } /// Req 8.4 on the **insert** path: a record whose bytes decode as `Data` and@@ -2453,9 +2453,9 @@ struct BackupV15ImportTests { let fixture = try await M5Fixture() let result = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.coveredPayload(- bytes: BackupV15Fixtures.undecodableCoverBytes)))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.coveredPayload(+ bytes: BackupV16Fixtures.undecodableCoverBytes))) guard case .committed(let counts, let report) = result else { Issue.record("expected committed, got \(result)")@@ -2466,7 +2466,7 @@ struct BackupV15ImportTests { #expect(counts.works >= 1) #expect(report.droppedThumbnails == ["Actual Title"]) #expect(- try await fixture.repository.thumbnailColumns(of: BackupV15Fixtures.workID)+ try await fixture.repository.thumbnailColumns(of: BackupV16Fixtures.workID) == [ThumbnailColumns.empty]) } @@ -2480,16 +2480,16 @@ struct BackupV15ImportTests { func undecodableCoverClearsALocalCover() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.coveredPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.coveredPayload())) #expect(- try await fixture.repository.thumbnailColumns(of: BackupV15Fixtures.workID)+ try await fixture.repository.thumbnailColumns(of: BackupV16Fixtures.workID) != [ThumbnailColumns.empty]) let result = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.coveredPayload(- bytes: BackupV15Fixtures.undecodableCoverBytes,- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(1_000))))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.coveredPayload(+ bytes: BackupV16Fixtures.undecodableCoverBytes,+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(1_000)))) guard case .committed(_, let report) = result else { Issue.record("expected committed, got \(result)")@@ -2497,7 +2497,7 @@ struct BackupV15ImportTests { } #expect(report.droppedThumbnails == ["Actual Title"]) #expect(- try await fixture.repository.thumbnailColumns(of: BackupV15Fixtures.workID)+ try await fixture.repository.thumbnailColumns(of: BackupV16Fixtures.workID) == [ThumbnailColumns.empty]) } @@ -2509,16 +2509,16 @@ struct BackupV15ImportTests { func olderArchiveDoesNotReplaceANewerLocalCover() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.coveredPayload(- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(1_000))))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.coveredPayload(+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(1_000)))) let result = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.coveredPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.coveredPayload( shapeRaw: ThumbnailShape.square.rawValue,- bytes: BackupV15Fixtures.undecodableCoverBytes,- modifiedAt: BackupV15Fixtures.created)))+ bytes: BackupV16Fixtures.undecodableCoverBytes,+ modifiedAt: BackupV16Fixtures.created))) guard case .committed(_, let report) = result else { Issue.record("expected committed, got \(result)")@@ -2526,11 +2526,11 @@ struct BackupV15ImportTests { } #expect(report.droppedThumbnails.isEmpty) #expect(- try await fixture.repository.thumbnailColumns(of: BackupV15Fixtures.workID)+ try await fixture.repository.thumbnailColumns(of: BackupV16Fixtures.workID) == [ThumbnailColumns(- byteCount: BackupV15Fixtures.coverBytes.count,+ byteCount: BackupV16Fixtures.coverBytes.count, shapeRaw: ThumbnailShape.portrait.rawValue,- digest: BackupV15Fixtures.coverDigest)])+ digest: BackupV16Fixtures.coverDigest)]) } /// Req 1.11's argument, applied to import: importing the same archive twice@@ -2546,21 +2546,21 @@ struct BackupV15ImportTests { @Test("Importing the same archive twice leaves the cover untouched") func importingTwiceLeavesTheCoverUntouched() async throws { let fixture = try await M5Fixture()- let plan = BackupV15Fixtures.plan(BackupV15Fixtures.coveredPayload())+ let plan = BackupV16Fixtures.plan(BackupV16Fixtures.coveredPayload()) try await fixture.repository.confirmImport(plan: plan) let columnsAfterFirst = try await fixture.repository- .thumbnailColumns(of: BackupV15Fixtures.workID)+ .thumbnailColumns(of: BackupV16Fixtures.workID) try await fixture.repository.confirmImport(plan: plan) #expect(- try await fixture.repository.thumbnailColumns(of: BackupV15Fixtures.workID)+ try await fixture.repository.thumbnailColumns(of: BackupV16Fixtures.workID) == columnsAfterFirst) #expect( try await fixture.repository.thumbnailBytes(- workID: BackupV15Fixtures.workID, digest: BackupV15Fixtures.coverDigest)- == BackupV15Fixtures.coverBytes)+ workID: BackupV16Fixtures.workID, digest: BackupV16Fixtures.coverDigest)+ == BackupV16Fixtures.coverBytes) } /// The half the repository API cannot show: whether the second application@@ -2573,7 +2573,7 @@ struct BackupV15ImportTests { /// 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let container = try ModelContainer( for: schema, configurations: [@@ -2584,14 +2584,14 @@ struct BackupV15ImportTests { context.autosaveEnabled = false let work = Work.create( in: context, title: "Covered", hostname: "a.example",- timestamp: BackupV15Fixtures.created)+ timestamp: BackupV16Fixtures.created) let cover = ArchiveThumbnail.value( shapeRaw: ThumbnailShape.portrait.rawValue,- bytes: BackupV15Fixtures.coverBytes,- digest: BackupV15Fixtures.coverDigest)+ bytes: BackupV16Fixtures.coverBytes,+ digest: BackupV16Fixtures.coverDigest) LibraryRepository.applyThumbnail(cover, to: work) try context.save()- #expect(work.thumbnailDigest == BackupV15Fixtures.coverDigest)+ #expect(work.thumbnailDigest == BackupV16Fixtures.coverDigest) LibraryRepository.applyThumbnail(cover, to: work) #expect(!context.hasChanges, "a second import of the same cover must write nothing")@@ -2603,7 +2603,7 @@ struct BackupV15ImportTests { try context.save() LibraryRepository.applyThumbnail(cover, to: work) #expect(context.hasChanges, "a restore must heal a row whose blob is not its digest")- #expect(work.thumbnailData == BackupV15Fixtures.coverBytes)+ #expect(work.thumbnailData == BackupV16Fixtures.coverBytes) try context.save() // The clearing arm, both ways round.@@ -2622,7 +2622,7 @@ struct BackupV15ImportTests { let fixture = try await M5Fixture() let result = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.coveredPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.coveredPayload())) guard case .committed(_, let report) = result else { Issue.record("expected committed, got \(result)")@@ -2635,20 +2635,20 @@ struct BackupV15ImportTests { func newerArchiveUpdatesACharacter() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.payload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.payload())) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload( characters: [- BackupV15Fixtures.character(+ BackupV16Fixtures.character( name: "Grover Underwood", note: "Still the guide.",- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(1_000))+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(1_000)) ]))) let grover = try #require( try await fixture.repository.m5AllCharacters()- .first { $0.id == BackupV15Fixtures.groverID })+ .first { $0.id == BackupV16Fixtures.groverID }) #expect(grover.name == "Grover Underwood") #expect(grover.note == "Still the guide.") // The retained key never moves with a rename (Q19/Q46) — including a@@ -2662,21 +2662,21 @@ struct BackupV15ImportTests { func olderSuppressionDoesNotUndoAClear() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload( suppressions: [- BackupV15Fixtures.suppression(+ BackupV16Fixtures.suppression( status: .cleared,- actionAt: BackupV15Fixtures.created.addingTimeInterval(1_000))+ actionAt: BackupV16Fixtures.created.addingTimeInterval(1_000)) ]))) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(suppressions: [BackupV15Fixtures.suppression()])))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload(suppressions: [BackupV16Fixtures.suppression()]))) let row = try #require( try await fixture.repository.m5SuppressionRows()- .first { $0.id == BackupV15Fixtures.suppressionID })+ .first { $0.id == BackupV16Fixtures.suppressionID }) #expect(row.status == .cleared) } @@ -2688,53 +2688,53 @@ struct BackupV15ImportTests { /// /// It was parameterised over the generations that had nowhere to write a /// character. Those read paths are gone (Decision 2), so the state is now- /// reached the only way it still can be — a 15/16 archive whose arrays are+ /// reached the only way it still can be — a 16/17 archive whose arrays are /// empty. @Test("Importing an archive with no characters creates none") func archivesWithoutCharactersCreateNone() async throws { let fixture = try await M5Fixture() let plan = try BackupImporter.plan(- from: try BackupV15Codec.encode(- payload: BackupV15Fixtures.composedPayload(),- metadata: BackupV15Fixtures.metadata()))+ from: try BackupV16Codec.encode(+ payload: BackupV16Fixtures.composedPayload(),+ metadata: BackupV16Fixtures.metadata())) try await fixture.repository.confirmImport(plan: plan) #expect(try await fixture.repository.m5AllCharacters().isEmpty) #expect(try await fixture.repository.m5SuppressionRows().isEmpty) #expect(try await fixture.repository.m5AllPlaces().isEmpty) #expect(try await fixture.repository.m5PlaceSuppressionRows().isEmpty)- #expect(try await fixture.repository.m5EntryCoverage(BackupV15Fixtures.entryID) == nil)+ #expect(try await fixture.repository.m5EntryCoverage(BackupV16Fixtures.entryID) == nil) } // MARK: The places (Req 5.1, 5.3, 5.5) - /// Req 5.1: a 15/16 archive lands its places and their suppressions into a+ /// Req 5.1: a 16/17 archive lands its places and their suppressions into a /// library that holds only the seeds, on the same terms the characters /// arrive on — the generic merge is one body called once per kind, and this /// is the place call's evidence that it ran.- @Test("A 15/16 archive commits its places and place suppressions")+ @Test("A 16/17 archive commits its places and place suppressions") func archiveCommitsPlaces() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.payload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.payload())) let places = try await fixture.repository.m5AllPlaces()- let keep = try #require(places.first { $0.id == BackupV15Fixtures.keepID })+ let keep = try #require(places.first { $0.id == BackupV16Fixtures.keepID }) #expect(keep.name == "The High Keep") #expect(keep.nameKey == "high keep") #expect(keep.aliases == ["The Keep"]) #expect(keep.note == "The fortress above the pass.") #expect(keep.facts.map(\.quote) == ["above the pass"])- #expect(keep.workID == BackupV15Fixtures.workID, "the place joins its work")+ #expect(keep.workID == BackupV16Fixtures.workID, "the place joins its work") let rows = try await fixture.repository.m5PlaceSuppressionRows()- let row = try #require(rows.first { $0.id == BackupV15Fixtures.placeSuppressionID })+ let row = try #require(rows.first { $0.id == BackupV16Fixtures.placeSuppressionID }) #expect(row.nameKey == "low road") #expect(row.kind == .candidate) #expect(row.status == .active)- #expect(row.workID == BackupV15Fixtures.workID)+ #expect(row.workID == BackupV16Fixtures.workID) } /// Req 5.5 and Q60: an owner the archive names and this library cannot@@ -2747,24 +2747,24 @@ struct BackupV15ImportTests { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload( places: [- BackupV15Fixtures.place(- id: BackupV15Fixtures.orphanPlaceID, workID: absent)+ BackupV16Fixtures.place(+ id: BackupV16Fixtures.orphanPlaceID, workID: absent) ],- placeSuppressions: [BackupV15Fixtures.placeSuppression(workID: absent)])))+ placeSuppressions: [BackupV16Fixtures.placeSuppression(workID: absent)]))) let orphan = try #require( try await fixture.repository.m5AllPlaces()- .first { $0.id == BackupV15Fixtures.orphanPlaceID })+ .first { $0.id == BackupV16Fixtures.orphanPlaceID }) #expect(orphan.workID == absent) #expect( try await fixture.repository.m5PlaceSuppressionRows()- .first { $0.id == BackupV15Fixtures.placeSuppressionID }?.workID == absent)+ .first { $0.id == BackupV16Fixtures.placeSuppressionID }?.workID == absent) - let payload = try await fixture.repository.backupV15Snapshot()- #expect(payload.places.first { $0.id == BackupV15Fixtures.orphanPlaceID }?.workID == absent)+ let payload = try await fixture.repository.backupV16Snapshot()+ #expect(payload.places.first { $0.id == BackupV16Fixtures.orphanPlaceID }?.workID == absent) #expect(payload.placeSuppressions.contains { $0.workID == absent }) } @@ -2781,7 +2781,7 @@ struct BackupV15ImportTests { func archivedOrphanDoesNotMoveALocalPlace() async throws { let localWorkID = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee96")! let absent = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee97")!- let older = BackupV15Fixtures.created.addingTimeInterval(-1_000)+ let older = BackupV16Fixtures.created.addingTimeInterval(-1_000) let fixture = try await M5Fixture() try await fixture.repository.seedM5Rows( sites: [M5SeedSite(hostname: "b.example")],@@ -2791,17 +2791,17 @@ struct BackupV15ImportTests { ], places: [ M5SeedPlace(- id: BackupV15Fixtures.keepID, name: "The Keep", nameKey: "high keep",+ id: BackupV16Fixtures.keepID, name: "The Keep", nameKey: "high keep", workID: localWorkID, createdAt: older, modifiedAt: older) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(places: [BackupV15Fixtures.place(workID: absent)])))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload(places: [BackupV16Fixtures.place(workID: absent)]))) let keep = try #require( try await fixture.repository.m5AllPlaces()- .first { $0.id == BackupV15Fixtures.keepID })+ .first { $0.id == BackupV16Fixtures.keepID }) #expect(keep.workID == localWorkID, "an owner that resolves to nothing never moves a place") #expect(keep.name == "The High Keep", "the archive's content still applies") }@@ -2812,22 +2812,22 @@ struct BackupV15ImportTests { @Test("A local orphan place adopts an archived work this library resolves") func localOrphanPlaceAdoptsAResolvingWork() async throws { let unresolvable = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee95")!- let older = BackupV15Fixtures.created.addingTimeInterval(-1_000)+ let older = BackupV16Fixtures.created.addingTimeInterval(-1_000) let fixture = try await M5Fixture() try await fixture.repository.seedM5Rows( places: [ M5SeedPlace(- id: BackupV15Fixtures.keepID, name: "The Keep", nameKey: "high keep",+ id: BackupV16Fixtures.keepID, name: "The Keep", nameKey: "high keep", workID: unresolvable, createdAt: older, modifiedAt: older) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.payload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.payload())) let keep = try #require( try await fixture.repository.m5AllPlaces()- .first { $0.id == BackupV15Fixtures.keepID })- #expect(keep.workID == BackupV15Fixtures.workID)+ .first { $0.id == BackupV16Fixtures.keepID })+ #expect(keep.workID == BackupV16Fixtures.workID) #expect(keep.name == "The High Keep") } @@ -2841,7 +2841,7 @@ struct BackupV15ImportTests { func archivedOrphanDoesNotMoveAPlaceSuppression() async throws { let localWorkID = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee94")! let absent = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee97")!- let older = BackupV15Fixtures.created.addingTimeInterval(-1_000)+ let older = BackupV16Fixtures.created.addingTimeInterval(-1_000) let fixture = try await M5Fixture() try await fixture.repository.seedM5Rows( sites: [M5SeedSite(hostname: "b.example")],@@ -2851,18 +2851,18 @@ struct BackupV15ImportTests { ], placeSuppressions: [ M5SeedPlaceSuppression(- id: BackupV15Fixtures.placeSuppressionID, workID: localWorkID,+ id: BackupV16Fixtures.placeSuppressionID, workID: localWorkID, nameKey: "old key", actionAt: older) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(- placeSuppressions: [BackupV15Fixtures.placeSuppression(workID: absent)])))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload(+ placeSuppressions: [BackupV16Fixtures.placeSuppression(workID: absent)]))) let row = try #require( try await fixture.repository.m5PlaceSuppressionRows()- .first { $0.id == BackupV15Fixtures.placeSuppressionID })+ .first { $0.id == BackupV16Fixtures.placeSuppressionID }) #expect( row.workID == localWorkID, "an owner that resolves to nothing never moves a suppression")@@ -2871,10 +2871,10 @@ struct BackupV15ImportTests { /// The idempotence half, over the two arrays this generation adds: a second /// import of the same file writes nothing.- @Test("Importing the same 15/16 archive twice leaves the places untouched")+ @Test("Importing the same 16/17 archive twice leaves the places untouched") func importingTwiceLeavesPlacesUntouched() async throws { let fixture = try await M5Fixture()- let plan = BackupV15Fixtures.plan(BackupV15Fixtures.payload())+ let plan = BackupV16Fixtures.plan(BackupV16Fixtures.payload()) try await fixture.repository.confirmImport(plan: plan) let placesAfterFirst = try await fixture.repository.m5AllPlaces()@@ -2894,35 +2894,35 @@ struct BackupV15ImportTests { func placeModificationGuard() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.payload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.payload())) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload( places: [- BackupV15Fixtures.place(+ BackupV16Fixtures.place( name: "Renamed by an older device", note: "older",- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(-1_000))+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(-1_000)) ]))) var keep = try #require( try await fixture.repository.m5AllPlaces()- .first { $0.id == BackupV15Fixtures.keepID })+ .first { $0.id == BackupV16Fixtures.keepID }) #expect(keep.name == "The High Keep") #expect(keep.note == "The fortress above the pass.") try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload( places: [- BackupV15Fixtures.place(+ BackupV16Fixtures.place( name: "The Keep Above the Pass", note: "Still standing.",- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(1_000))+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(1_000)) ]))) keep = try #require( try await fixture.repository.m5AllPlaces()- .first { $0.id == BackupV15Fixtures.keepID })+ .first { $0.id == BackupV16Fixtures.keepID }) #expect(keep.name == "The Keep Above the Pass") #expect(keep.note == "Still standing.") // The retained key never moves with a rename, an archived one included.@@ -2936,22 +2936,22 @@ struct BackupV15ImportTests { func olderPlaceSuppressionDoesNotUndoAClear() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload( placeSuppressions: [- BackupV15Fixtures.placeSuppression(+ BackupV16Fixtures.placeSuppression( status: .cleared,- actionAt: BackupV15Fixtures.created.addingTimeInterval(1_000))+ actionAt: BackupV16Fixtures.created.addingTimeInterval(1_000)) ]))) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.payload(- placeSuppressions: [BackupV15Fixtures.placeSuppression()])))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.payload(+ placeSuppressions: [BackupV16Fixtures.placeSuppression()]))) let row = try #require( try await fixture.repository.m5PlaceSuppressionRows()- .first { $0.id == BackupV15Fixtures.placeSuppressionID })+ .first { $0.id == BackupV16Fixtures.placeSuppressionID }) #expect(row.status == .cleared) } @@ -2962,22 +2962,22 @@ struct BackupV15ImportTests { @Test("An import into an empty library reproduces series, memberships and links") func seriesAndLinksImportWhole() async throws { let fixture = try await M5Fixture()- let plan = BackupV15Fixtures.plan(BackupV15Fixtures.seriesPayload())+ let plan = BackupV16Fixtures.plan(BackupV16Fixtures.seriesPayload()) try await fixture.repository.confirmImport(plan: plan) let series = try await fixture.repository.seriesRowValues()- #expect(series.map(\.id) == [BackupV15Fixtures.seriesID])+ #expect(series.map(\.id) == [BackupV16Fixtures.seriesID]) #expect(series.first?.name == "Ashfall Cycle") #expect(series.first?.notes == "Read 2.5 after 2.") #expect(- try await fixture.repository.membershipColumns(of: BackupV15Fixtures.composedWorkID)- == [SeriesColumns(seriesID: BackupV15Fixtures.seriesID, position: 1)])+ try await fixture.repository.membershipColumns(of: BackupV16Fixtures.composedWorkID)+ == [SeriesColumns(seriesID: BackupV16Fixtures.seriesID, position: 1)]) #expect(- try await fixture.repository.membershipColumns(of: BackupV15Fixtures.secondWorkID)- == [SeriesColumns(seriesID: BackupV15Fixtures.seriesID, position: 2.5)])+ try await fixture.repository.membershipColumns(of: BackupV16Fixtures.secondWorkID)+ == [SeriesColumns(seriesID: BackupV16Fixtures.seriesID, position: 2.5)]) let links = try await fixture.repository.workLinkRowValues()- #expect(links.map(\.id) == [BackupV15Fixtures.linkID])+ #expect(links.map(\.id) == [BackupV16Fixtures.linkID]) #expect(links.first?.linkType == "adaptation") // A repeated import writes the same values back and removes nothing.@@ -2996,29 +2996,29 @@ struct BackupV15ImportTests { let local = UUID(uuidString: "5E81E5A0-0000-4000-8000-0000000000ff")! let localLink = UUID(uuidString: "11115E51-0000-4000-8000-0000000000ff")! try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.seriesPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.seriesPayload())) // Two rows only this library holds, and a newer local edit to the // series the archive also carries. try await fixture.repository.seedSeries([SeedSeries(id: local, name: "Quiet Shelf")]) try await fixture.repository.seedWorkLinks([ SeedWorkLink(- id: localLink, a: BackupV15Fixtures.composedWorkID,+ id: localLink, a: BackupV16Fixtures.composedWorkID, b: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee97")!, type: "prequel") ]) try await fixture.repository.updateSeries(- id: BackupV15Fixtures.seriesID, name: "Renamed here", notes: "later")+ id: BackupV16Fixtures.seriesID, name: "Renamed here", notes: "later") try await fixture.repository.retypeLink(- id: BackupV15Fixtures.linkID, type: "retyped here")+ id: BackupV16Fixtures.linkID, type: "retyped here") // The same archive again: its records are now older than both rows. try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.seriesPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.seriesPayload())) let afterOlder = try await fixture.repository.seriesRowValues()- #expect(afterOlder.first { $0.id == BackupV15Fixtures.seriesID }?.name == "Renamed here")+ #expect(afterOlder.first { $0.id == BackupV16Fixtures.seriesID }?.name == "Renamed here") #expect( try await fixture.repository.workLinkRowValues()- .first { $0.id == BackupV15Fixtures.linkID }?.linkType == "retyped here")+ .first { $0.id == BackupV16Fixtures.linkID }?.linkType == "retyped here") // Nothing the archive does not carry was removed. #expect(afterOlder.contains { $0.id == local }) #expect(try await fixture.repository.workLinkIDs().contains(localLink))@@ -3028,19 +3028,19 @@ struct BackupV15ImportTests { // own epoch — not merely later than the archive's own `created`. let later = M5Fixture.epoch.addingTimeInterval(3_600) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.seriesPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.seriesPayload( series: [- BackupV15Fixtures.seriesRecord(name: "Renamed there", modifiedAt: later)+ BackupV16Fixtures.seriesRecord(name: "Renamed there", modifiedAt: later) ],- links: [BackupV15Fixtures.linkRecord(type: "retyped there", modifiedAt: later)])))+ links: [BackupV16Fixtures.linkRecord(type: "retyped there", modifiedAt: later)]))) #expect( try await fixture.repository.seriesRowValues()- .first { $0.id == BackupV15Fixtures.seriesID }?.name == "Renamed there")+ .first { $0.id == BackupV16Fixtures.seriesID }?.name == "Renamed there") #expect( try await fixture.repository.workLinkRowValues()- .first { $0.id == BackupV15Fixtures.linkID }?.linkType == "retyped there")+ .first { $0.id == BackupV16Fixtures.linkID }?.linkType == "retyped there") } /// Req 13.5's tolerated half, at the store rather than on the wire: a work@@ -3053,16 +3053,16 @@ struct BackupV15ImportTests { let absentSeries = UUID(uuidString: "5E81E5A0-0000-4000-8000-000000000009")! let absentWork = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee99")! try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.seriesPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.seriesPayload( links: [- BackupV15Fixtures.linkRecord(- a: BackupV15Fixtures.composedWorkID, b: absentWork, type: "spin-off")+ BackupV16Fixtures.linkRecord(+ a: BackupV16Fixtures.composedWorkID, b: absentWork, type: "spin-off") ], firstMembership: (absentSeries, 3)))) #expect(- try await fixture.repository.membershipColumns(of: BackupV15Fixtures.composedWorkID)+ try await fixture.repository.membershipColumns(of: BackupV16Fixtures.composedWorkID) == [SeriesColumns(seriesID: absentSeries, position: 3)]) let links = try await fixture.repository.workLinkRowValues() #expect(links.count == 1)@@ -3079,47 +3079,47 @@ struct BackupV15ImportTests { @Test("An import into a seeds-only library reproduces creators, roles and credits") func creatorsImportWhole() async throws { let fixture = try await M5Fixture()- let plan = BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload())+ let plan = BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload()) try await fixture.repository.confirmImport(plan: plan) let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())- let mori = try #require(creators[BackupV15Fixtures.moriID])+ let mori = try #require(creators[BackupV16Fixtures.moriID]) #expect(mori.name == "Mori Ayane") #expect(mori.notes == "Also draws.") #expect(mori.state == .active) // The archive's own field timestamps, so the next sync fold and a // repeated import see exactly what the exporting device saw (Q50).- #expect(mori.nameModifiedAt == BackupV15Fixtures.created)- #expect(mori.notesModifiedAt == BackupV15Fixtures.created)- let alias = try #require(creators[BackupV15Fixtures.aliasID])+ #expect(mori.nameModifiedAt == BackupV16Fixtures.created)+ #expect(mori.notesModifiedAt == BackupV16Fixtures.created)+ let alias = try #require(creators[BackupV16Fixtures.aliasID]) #expect(alias.state == .merged)- #expect(alias.canonicalID == BackupV15Fixtures.moriID)+ #expect(alias.canonicalID == BackupV16Fixtures.moriID) // A credit naming the alias reads as its survivor on arrival.- #expect(creators.canonicalID(of: BackupV15Fixtures.aliasID) == BackupV15Fixtures.moriID)+ #expect(creators.canonicalID(of: BackupV16Fixtures.aliasID) == BackupV16Fixtures.moriID) let roles = CreatorRoleDirectory( rows: try await fixture.repository.creatorRoleRowValues()) #expect(roles.identities.count == 5) #expect(roles.options.map(\.name) == ["author", "artist", "translator", "letterer"])- #expect(roles[BackupV15Fixtures.lettererRoleID]?.position == 3)- #expect(roles[BackupV15Fixtures.editorRoleID]?.state == .removed)+ #expect(roles[BackupV16Fixtures.lettererRoleID]?.position == 3)+ #expect(roles[BackupV16Fixtures.editorRoleID]?.state == .removed) // The three defaults are still the seeded identities the library minted // at open: the archive's records of them matched by identifier.- #expect(roles[BackupV15Fixtures.authorRoleID]?.isPristine == true)+ #expect(roles[BackupV16Fixtures.authorRoleID]?.isPristine == true) let credits = try await fixture.repository.creditRows() #expect(credits.count == 3)- let credit = try #require(credits.first { $0.id == BackupV15Fixtures.moriCreditID })+ let credit = try #require(credits.first { $0.id == BackupV16Fixtures.moriCreditID }) #expect( credit.roleIDs == [- BackupV15Fixtures.authorRoleID.uuidString,- BackupV15Fixtures.editorRoleID.uuidString,+ BackupV16Fixtures.authorRoleID.uuidString,+ BackupV16Fixtures.editorRoleID.uuidString, ].sorted()) // Req 9.5's tolerance at the store: the credit whose work the archive // never carried is here, unresolved and nobody's to prune.- #expect(credits.contains { $0.id == BackupV15Fixtures.orphanCreditID })+ #expect(credits.contains { $0.id == BackupV16Fixtures.orphanCreditID }) let creatorsAfterFirst = try await fixture.repository.creatorRowValues() let rolesAfterFirst = try await fixture.repository.creatorRoleRowValues()@@ -3138,22 +3138,22 @@ struct BackupV15ImportTests { @Test("An identifier match takes each field only when the archive's stamp beats the local") func identifierMatchAppliesPerField() async throws { let fixture = try await M5Fixture()- let later = BackupV15Fixtures.created.addingTimeInterval(1_000)+ let later = BackupV16Fixtures.created.addingTimeInterval(1_000) try await fixture.repository.seedCreators([ SeedCreator(- id: BackupV15Fixtures.moriID, name: "Renamed here",- nameModifiedAt: later, createdAt: BackupV15Fixtures.created)+ id: BackupV16Fixtures.moriID, name: "Renamed here",+ nameModifiedAt: later, createdAt: BackupV16Fixtures.created) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())- let mori = try #require(creators[BackupV15Fixtures.moriID])+ let mori = try #require(creators[BackupV16Fixtures.moriID]) #expect(mori.name == "Renamed here") #expect(mori.nameModifiedAt == later) #expect(mori.notes == "Also draws.")- #expect(mori.notesModifiedAt == BackupV15Fixtures.created)+ #expect(mori.notesModifiedAt == BackupV16Fixtures.created) } /// The other half of the rule: an archive field nobody has ever touched@@ -3162,20 +3162,20 @@ struct BackupV15ImportTests { @Test("A pristine archive field never overrides a reader-touched local one") func pristineArchiveFieldNeverStands() async throws { let fixture = try await M5Fixture()- let touched = BackupV15Fixtures.created.addingTimeInterval(1_000)+ let touched = BackupV16Fixtures.created.addingTimeInterval(1_000) // A second row of the seeded identity, carrying the reader's rename. try await fixture.repository.seedCreatorRoles([ SeedCreatorRole(- id: BackupV15Fixtures.authorRoleID, name: "writer", position: 0,+ id: BackupV16Fixtures.authorRoleID, name: "writer", position: 0, nameModifiedAt: touched) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) let roles = CreatorRoleDirectory( rows: try await fixture.repository.creatorRoleRowValues())- #expect(roles[BackupV15Fixtures.authorRoleID]?.name == "writer")+ #expect(roles[BackupV16Fixtures.authorRoleID]?.name == "writer") } /// Req 9.4: `merged` is terminal on the **local** side. An identity that@@ -3191,44 +3191,44 @@ struct BackupV15ImportTests { func mergedStateIsTerminal() async throws { let fixture = try await M5Fixture() let survivor = UUID(uuidString: "c8ea1080-0000-4000-8000-0000000000a1")!- let later = BackupV15Fixtures.created.addingTimeInterval(3_000)+ let later = BackupV16Fixtures.created.addingTimeInterval(3_000) try await fixture.repository.seedCreators([ // Locally merged already: the archive's `active` record cannot // resurrect it, even carrying a later state stamp.- SeedCreator(id: survivor, name: "Kept", nameModifiedAt: BackupV15Fixtures.created),+ SeedCreator(id: survivor, name: "Kept", nameModifiedAt: BackupV16Fixtures.created), SeedCreator(- id: BackupV15Fixtures.moriID, name: "Mori Ayane", state: .merged,+ id: BackupV16Fixtures.moriID, name: "Mori Ayane", state: .merged, canonicalID: survivor,- nameModifiedAt: BackupV15Fixtures.created,- stateModifiedAt: BackupV15Fixtures.created),+ nameModifiedAt: BackupV16Fixtures.created,+ stateModifiedAt: BackupV16Fixtures.created), // Locally active, and the archive says it merged into `mori`, which // resolves here to `survivor`: the archive's later stamp applies. SeedCreator(- id: BackupV15Fixtures.aliasID, name: "mori ayane",- nameModifiedAt: BackupV15Fixtures.created.addingTimeInterval(2_000),- stateModifiedAt: BackupV15Fixtures.created),+ id: BackupV16Fixtures.aliasID, name: "mori ayane",+ nameModifiedAt: BackupV16Fixtures.created.addingTimeInterval(2_000),+ stateModifiedAt: BackupV16Fixtures.created), ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane", notes: "Also draws.", stateModifiedAt: later),- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.studioID, name: "Studio Lantern"),- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.aliasID, name: "mori ayane",- state: .merged, canonicalID: BackupV15Fixtures.moriID,+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.studioID, name: "Studio Lantern"),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.aliasID, name: "mori ayane",+ state: .merged, canonicalID: BackupV16Fixtures.moriID, stateModifiedAt: later), ]))) let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())- let mori = try #require(creators[BackupV15Fixtures.moriID])+ let mori = try #require(creators[BackupV16Fixtures.moriID]) #expect(mori.state == .merged) #expect(mori.canonicalID == survivor)- let alias = try #require(creators[BackupV15Fixtures.aliasID])+ let alias = try #require(creators[BackupV16Fixtures.aliasID]) #expect(alias.state == .merged) // The chain the archive's pointer made — alias into mori into survivor — // is collapsed by the same commit's reconcile.@@ -3242,25 +3242,25 @@ struct BackupV15ImportTests { @Test("An archived merge carrying no survivor leaves a live creator active") func survivorlessArchivedMergeLeavesTheCreatorActive() async throws { let fixture = try await M5Fixture()- let later = BackupV15Fixtures.created.addingTimeInterval(3_000)+ let later = BackupV16Fixtures.created.addingTimeInterval(3_000) try await fixture.repository.seedCreators([ SeedCreator(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",- nameModifiedAt: BackupV15Fixtures.created,- stateModifiedAt: BackupV15Fixtures.created)+ id: BackupV16Fixtures.moriID, name: "Mori Ayane",+ nameModifiedAt: BackupV16Fixtures.created,+ stateModifiedAt: BackupV16Fixtures.created) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane", state: .merged, canonicalID: nil, stateModifiedAt: later) ]))) let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())- #expect(creators[BackupV15Fixtures.moriID]?.state == .active)+ #expect(creators[BackupV16Fixtures.moriID]?.state == .active) #expect(creators.options.contains { $0.name == "Mori Ayane" }) } @@ -3274,20 +3274,20 @@ struct BackupV15ImportTests { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane", state: .merged, canonicalID: nil) ]))) let rows = try await fixture.repository.creatorRowValues()- let row = try #require(rows.first { $0.id == BackupV15Fixtures.moriID })+ let row = try #require(rows.first { $0.id == BackupV16Fixtures.moriID }) #expect(row.stateRaw == CreatorState.merged.rawValue) #expect(row.canonicalID == nil, "the survivorless pointer is kept, not invented") #expect(- CreatorDirectory(rows: rows)[BackupV15Fixtures.moriID]?.state == .merged,+ CreatorDirectory(rows: rows)[BackupV16Fixtures.moriID]?.state == .merged, "and the same commit's reconcile leaves it there — there is no chain to collapse") } @@ -3297,26 +3297,26 @@ struct BackupV15ImportTests { @Test("An archived merge naming an absent survivor leaves a live creator active") func archivedMergeNamingAnAbsentSurvivorIsSkipped() async throws { let fixture = try await M5Fixture()- let later = BackupV15Fixtures.created.addingTimeInterval(3_000)+ let later = BackupV16Fixtures.created.addingTimeInterval(3_000) try await fixture.repository.seedCreators([ SeedCreator(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",- nameModifiedAt: BackupV15Fixtures.created,- stateModifiedAt: BackupV15Fixtures.created)+ id: BackupV16Fixtures.moriID, name: "Mori Ayane",+ nameModifiedAt: BackupV16Fixtures.created,+ stateModifiedAt: BackupV16Fixtures.created) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",- state: .merged, canonicalID: BackupV15Fixtures.absentCreatorID,+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane",+ state: .merged, canonicalID: BackupV16Fixtures.absentCreatorID, stateModifiedAt: later) ]))) let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())- #expect(creators[BackupV15Fixtures.moriID]?.state == .active)+ #expect(creators[BackupV16Fixtures.moriID]?.state == .active) } /// And the positive case: a survivor the archive itself carries, on a@@ -3324,30 +3324,30 @@ struct BackupV15ImportTests { @Test("An archived merge naming a present survivor and stamped later applies") func archivedMergeWithAPresentSurvivorApplies() async throws { let fixture = try await M5Fixture()- let later = BackupV15Fixtures.created.addingTimeInterval(3_000)+ let later = BackupV16Fixtures.created.addingTimeInterval(3_000) try await fixture.repository.seedCreators([ SeedCreator(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",- nameModifiedAt: BackupV15Fixtures.created,- stateModifiedAt: BackupV15Fixtures.created)+ id: BackupV16Fixtures.moriID, name: "Mori Ayane",+ nameModifiedAt: BackupV16Fixtures.created,+ stateModifiedAt: BackupV16Fixtures.created) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",- state: .merged, canonicalID: BackupV15Fixtures.studioID,+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane",+ state: .merged, canonicalID: BackupV16Fixtures.studioID, stateModifiedAt: later),- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.studioID, name: "Studio Lantern"),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.studioID, name: "Studio Lantern"), ]))) let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())- let mori = try #require(creators[BackupV15Fixtures.moriID])+ let mori = try #require(creators[BackupV16Fixtures.moriID]) #expect(mori.state == .merged)- #expect(mori.canonicalID == BackupV15Fixtures.studioID)+ #expect(mori.canonicalID == BackupV16Fixtures.studioID) } /// The stamp rule holds for a merge like any other field: an archive older@@ -3356,26 +3356,26 @@ struct BackupV15ImportTests { @Test("An archived merge older than the local state writes nothing") func archivedMergeOlderThanTheLocalStateIsIgnored() async throws { let fixture = try await M5Fixture()- let touched = BackupV15Fixtures.created.addingTimeInterval(3_000)+ let touched = BackupV16Fixtures.created.addingTimeInterval(3_000) try await fixture.repository.seedCreators([ SeedCreator(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",+ id: BackupV16Fixtures.moriID, name: "Mori Ayane", nameModifiedAt: touched, stateModifiedAt: touched) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.moriID, name: "Mori Ayane",- state: .merged, canonicalID: BackupV15Fixtures.studioID),- BackupV15Fixtures.creatorRecord(- id: BackupV15Fixtures.studioID, name: "Studio Lantern"),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.moriID, name: "Mori Ayane",+ state: .merged, canonicalID: BackupV16Fixtures.studioID),+ BackupV16Fixtures.creatorRecord(+ id: BackupV16Fixtures.studioID, name: "Studio Lantern"), ]))) let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())- #expect(creators[BackupV15Fixtures.moriID]?.state == .active)+ #expect(creators[BackupV16Fixtures.moriID]?.state == .active) } /// Q54: an archive record matching a local one **by name only** is inserted@@ -3389,20 +3389,20 @@ struct BackupV15ImportTests { try await fixture.repository.seedCreators([ SeedCreator( id: local, name: "Mori Ayane",- nameModifiedAt: BackupV15Fixtures.created.addingTimeInterval(-1_000),- createdAt: BackupV15Fixtures.created.addingTimeInterval(-1_000))+ nameModifiedAt: BackupV16Fixtures.created.addingTimeInterval(-1_000),+ createdAt: BackupV16Fixtures.created.addingTimeInterval(-1_000)) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues()) // Both records are still there — nothing an import touches is deleted. #expect(creators[local] != nil)- #expect(creators[BackupV15Fixtures.moriID] != nil)+ #expect(creators[BackupV16Fixtures.moriID] != nil) // The earliest-created non-pristine identity survives, and the other // reads as it (Req 10.3).- #expect(creators.canonicalID(of: BackupV15Fixtures.moriID) == local)+ #expect(creators.canonicalID(of: BackupV16Fixtures.moriID) == local) #expect(creators.options.count(where: { $0.name == "Mori Ayane" }) == 1) } @@ -3418,17 +3418,17 @@ struct BackupV15ImportTests { try await fixture.repository.seedCreatorRoles([ SeedCreatorRole( id: colorist, name: "colorist", position: 3,- nameModifiedAt: BackupV15Fixtures.created,- positionModifiedAt: BackupV15Fixtures.created,- createdAt: BackupV15Fixtures.created)+ nameModifiedAt: BackupV16Fixtures.created,+ positionModifiedAt: BackupV16Fixtures.created,+ createdAt: BackupV16Fixtures.created) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) let roles = CreatorRoleDirectory( rows: try await fixture.repository.creatorRoleRowValues())- let letterer = try #require(roles[BackupV15Fixtures.lettererRoleID])+ let letterer = try #require(roles[BackupV16Fixtures.lettererRoleID]) #expect(letterer.position == 4, "appended after the local maximum, not at the archive's 3") #expect(letterer.positionModifiedAt == M5Fixture.epoch) #expect(roles.options.map(\.name) == ["author", "artist", "translator", "colorist", "letterer"])@@ -3441,41 +3441,41 @@ struct BackupV15ImportTests { @Test("An archived role state later than the local one is taken, in both directions") func archivedRoleStateIsTakenByStamp() async throws { let fixture = try await M5Fixture()- let later = BackupV15Fixtures.created.addingTimeInterval(1_000)+ let later = BackupV16Fixtures.created.addingTimeInterval(1_000) try await fixture.repository.seedCreatorRoles([ SeedCreatorRole(- id: BackupV15Fixtures.lettererRoleID, name: "letterer", position: 3,- nameModifiedAt: BackupV15Fixtures.created,- positionModifiedAt: BackupV15Fixtures.created,- stateModifiedAt: BackupV15Fixtures.created,- createdAt: BackupV15Fixtures.created),+ id: BackupV16Fixtures.lettererRoleID, name: "letterer", position: 3,+ nameModifiedAt: BackupV16Fixtures.created,+ positionModifiedAt: BackupV16Fixtures.created,+ stateModifiedAt: BackupV16Fixtures.created,+ createdAt: BackupV16Fixtures.created), SeedCreatorRole(- id: BackupV15Fixtures.editorRoleID, name: "editor", position: 4,+ id: BackupV16Fixtures.editorRoleID, name: "editor", position: 4, state: .removed,- nameModifiedAt: BackupV15Fixtures.created,- positionModifiedAt: BackupV15Fixtures.created,- stateModifiedAt: BackupV15Fixtures.created,- createdAt: BackupV15Fixtures.created),+ nameModifiedAt: BackupV16Fixtures.created,+ positionModifiedAt: BackupV16Fixtures.created,+ stateModifiedAt: BackupV16Fixtures.created,+ createdAt: BackupV16Fixtures.created), ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(- creatorRoles: BackupV15Fixtures.seededRoleRecords + [- BackupV15Fixtures.creatorRoleRecord(- id: BackupV15Fixtures.lettererRoleID, name: "letterer",+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload(+ creatorRoles: BackupV16Fixtures.seededRoleRecords + [+ BackupV16Fixtures.creatorRoleRecord(+ id: BackupV16Fixtures.lettererRoleID, name: "letterer", position: 3, state: .removed, stateModifiedAt: later),- BackupV15Fixtures.creatorRoleRecord(- id: BackupV15Fixtures.editorRoleID, name: "editor",+ BackupV16Fixtures.creatorRoleRecord(+ id: BackupV16Fixtures.editorRoleID, name: "editor", position: 4, stateModifiedAt: later), ]))) let roles = CreatorRoleDirectory( rows: try await fixture.repository.creatorRoleRowValues())- #expect(roles[BackupV15Fixtures.lettererRoleID]?.state == .removed)- #expect(roles[BackupV15Fixtures.lettererRoleID]?.stateModifiedAt == later)- #expect(roles[BackupV15Fixtures.editorRoleID]?.state == .active)- #expect(roles[BackupV15Fixtures.editorRoleID]?.stateModifiedAt == later)+ #expect(roles[BackupV16Fixtures.lettererRoleID]?.state == .removed)+ #expect(roles[BackupV16Fixtures.lettererRoleID]?.stateModifiedAt == later)+ #expect(roles[BackupV16Fixtures.editorRoleID]?.state == .active)+ #expect(roles[BackupV16Fixtures.editorRoleID]?.stateModifiedAt == later) } /// The other half: an archived state older than the local one writes@@ -3484,25 +3484,25 @@ struct BackupV15ImportTests { @Test("An archived role state older than the local one writes nothing") func archivedRoleStateOlderThanTheLocalOneIsIgnored() async throws { let fixture = try await M5Fixture()- let touched = BackupV15Fixtures.created.addingTimeInterval(2_000)+ let touched = BackupV16Fixtures.created.addingTimeInterval(2_000) try await fixture.repository.seedCreatorRoles([ SeedCreatorRole(- id: BackupV15Fixtures.lettererRoleID, name: "letterer", position: 3,+ id: BackupV16Fixtures.lettererRoleID, name: "letterer", position: 3, state: .removed,- nameModifiedAt: BackupV15Fixtures.created,- positionModifiedAt: BackupV15Fixtures.created,+ nameModifiedAt: BackupV16Fixtures.created,+ positionModifiedAt: BackupV16Fixtures.created, stateModifiedAt: touched,- createdAt: BackupV15Fixtures.created)+ createdAt: BackupV16Fixtures.created) ]) // The archive's `letterer` is active, stamped at `created`. try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) let roles = CreatorRoleDirectory( rows: try await fixture.repository.creatorRoleRowValues())- #expect(roles[BackupV15Fixtures.lettererRoleID]?.state == .removed)- #expect(roles[BackupV15Fixtures.lettererRoleID]?.stateModifiedAt == touched)+ #expect(roles[BackupV16Fixtures.lettererRoleID]?.state == .removed)+ #expect(roles[BackupV16Fixtures.lettererRoleID]?.stateModifiedAt == touched) } /// Req 9.4's append, over **every** archive-only role rather than the@@ -3516,23 +3516,23 @@ struct BackupV15ImportTests { try await fixture.repository.seedCreatorRoles([ SeedCreatorRole( id: colorist, name: "colorist", position: 3, state: .removed,- nameModifiedAt: BackupV15Fixtures.created,- positionModifiedAt: BackupV15Fixtures.created,- stateModifiedAt: BackupV15Fixtures.created,- createdAt: BackupV15Fixtures.created)+ nameModifiedAt: BackupV16Fixtures.created,+ positionModifiedAt: BackupV16Fixtures.created,+ stateModifiedAt: BackupV16Fixtures.created,+ createdAt: BackupV16Fixtures.created) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) let roles = CreatorRoleDirectory( rows: try await fixture.repository.creatorRoleRowValues())- let letterer = try #require(roles[BackupV15Fixtures.lettererRoleID])+ let letterer = try #require(roles[BackupV16Fixtures.lettererRoleID]) #expect(letterer.position == 4, "past the removed role's 3, not onto it") #expect(letterer.positionModifiedAt == M5Fixture.epoch) // The removed one appends too, at the reader's end of the list rather // than at the place the archive recorded.- let editor = try #require(roles[BackupV15Fixtures.editorRoleID])+ let editor = try #require(roles[BackupV16Fixtures.editorRoleID]) #expect(editor.state == .removed) #expect(editor.position == 5) #expect(editor.positionModifiedAt == M5Fixture.epoch)@@ -3548,54 +3548,54 @@ struct BackupV15ImportTests { func creditGuardHoldsBothWays() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) let stored = [- BackupV15Fixtures.authorRoleID.uuidString,- BackupV15Fixtures.editorRoleID.uuidString,+ BackupV16Fixtures.authorRoleID.uuidString,+ BackupV16Fixtures.editorRoleID.uuidString, ].sorted() func reimport(roleIDs: [UUID], modifiedAt: Date) async throws { try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload( credits: [- BackupV15Fixtures.creditRecord(- id: BackupV15Fixtures.moriCreditID,- workID: BackupV15Fixtures.composedWorkID,- creatorID: BackupV15Fixtures.moriID,+ BackupV16Fixtures.creditRecord(+ id: BackupV16Fixtures.moriCreditID,+ workID: BackupV16Fixtures.composedWorkID,+ creatorID: BackupV16Fixtures.moriID, roleIDs: roleIDs, modifiedAt: modifiedAt) ]))) } func roleIDs() async throws -> [String] { try await fixture.repository.creditRows()- .first { $0.id == BackupV15Fixtures.moriCreditID }?.roleIDs ?? []+ .first { $0.id == BackupV16Fixtures.moriCreditID }?.roleIDs ?? [] } // Older: nothing moves. try await reimport(- roleIDs: [BackupV15Fixtures.artistRoleID],- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(-1_000))+ roleIDs: [BackupV16Fixtures.artistRoleID],+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(-1_000)) #expect(try await roleIDs() == stored) // Equal, and a strict subset: the union the row holds stands (Q67). try await reimport(- roleIDs: [BackupV15Fixtures.authorRoleID], modifiedAt: BackupV15Fixtures.created)+ roleIDs: [BackupV16Fixtures.authorRoleID], modifiedAt: BackupV16Fixtures.created) #expect(try await roleIDs() == stored) // Equal, and a superset: the archive widens it. try await reimport( roleIDs: [- BackupV15Fixtures.authorRoleID, BackupV15Fixtures.editorRoleID,- BackupV15Fixtures.translatorRoleID,- ], modifiedAt: BackupV15Fixtures.created)- #expect(try await roleIDs().contains(BackupV15Fixtures.translatorRoleID.uuidString))+ BackupV16Fixtures.authorRoleID, BackupV16Fixtures.editorRoleID,+ BackupV16Fixtures.translatorRoleID,+ ], modifiedAt: BackupV16Fixtures.created)+ #expect(try await roleIDs().contains(BackupV16Fixtures.translatorRoleID.uuidString)) // Strictly later: the archive wins outright, narrowing included. try await reimport(- roleIDs: [BackupV15Fixtures.artistRoleID],- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(1_000))- #expect(try await roleIDs() == [BackupV15Fixtures.artistRoleID.uuidString])+ roleIDs: [BackupV16Fixtures.artistRoleID],+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(1_000))+ #expect(try await roleIDs() == [BackupV16Fixtures.artistRoleID.uuidString]) } /// Req 9.4's last clause: a pair the import leaves held twice converges per@@ -3606,29 +3606,29 @@ struct BackupV15ImportTests { func duplicatePairConvergesInTheImport() async throws { let fixture = try await M5Fixture() try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) // A second row over the same pair, reached through the alias — created // after the archive's, so the archive's row is the head. let through = UUID(uuidString: "c8ed1700-0000-4000-8000-0000000000a1")! try await fixture.repository.seedCredits([ SeedCredit(- id: through, workID: BackupV15Fixtures.composedWorkID,- creatorID: BackupV15Fixtures.aliasID,- roleIDs: [BackupV15Fixtures.translatorRoleID.uuidString])+ id: through, workID: BackupV16Fixtures.composedWorkID,+ creatorID: BackupV16Fixtures.aliasID,+ roleIDs: [BackupV16Fixtures.translatorRoleID.uuidString]) ]) try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.creditsPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.creditsPayload())) let rows = try await fixture.repository.creditRows()- .filter { $0.workID == BackupV15Fixtures.composedWorkID }- #expect(rows.map(\.id) == [BackupV15Fixtures.moriCreditID])+ .filter { $0.workID == BackupV16Fixtures.composedWorkID }+ #expect(rows.map(\.id) == [BackupV16Fixtures.moriCreditID]) #expect( rows.first?.roleIDs == [- BackupV15Fixtures.authorRoleID.uuidString,- BackupV15Fixtures.editorRoleID.uuidString,- BackupV15Fixtures.translatorRoleID.uuidString,+ BackupV16Fixtures.authorRoleID.uuidString,+ BackupV16Fixtures.editorRoleID.uuidString,+ BackupV16Fixtures.translatorRoleID.uuidString, ].sorted()) } @@ -3647,37 +3647,37 @@ struct BackupV15ImportTests { try await fixture.repository.seedCreators([ SeedCreator( id: kept, name: "Mori Ayane",- nameModifiedAt: BackupV15Fixtures.created,- createdAt: BackupV15Fixtures.created),+ nameModifiedAt: BackupV16Fixtures.created,+ createdAt: BackupV16Fixtures.created), SeedCreator( id: renamed, name: "Ayane Mori",- nameModifiedAt: BackupV15Fixtures.created,- createdAt: BackupV15Fixtures.created.addingTimeInterval(1_000)),+ nameModifiedAt: BackupV16Fixtures.created,+ createdAt: BackupV16Fixtures.created.addingTimeInterval(1_000)), ]) try await fixture.repository.seedCredits([ SeedCredit(- id: keptCredit, workID: BackupV15Fixtures.composedWorkID, creatorID: kept,- roleIDs: [BackupV15Fixtures.authorRoleID.uuidString],- createdAt: BackupV15Fixtures.created,- modifiedAt: BackupV15Fixtures.created),+ id: keptCredit, workID: BackupV16Fixtures.composedWorkID, creatorID: kept,+ roleIDs: [BackupV16Fixtures.authorRoleID.uuidString],+ createdAt: BackupV16Fixtures.created,+ modifiedAt: BackupV16Fixtures.created), SeedCredit(- id: otherCredit, workID: BackupV15Fixtures.composedWorkID,+ id: otherCredit, workID: BackupV16Fixtures.composedWorkID, creatorID: renamed,- roleIDs: [BackupV15Fixtures.artistRoleID.uuidString],- createdAt: BackupV15Fixtures.created.addingTimeInterval(1_000),- modifiedAt: BackupV15Fixtures.created.addingTimeInterval(1_000)),+ roleIDs: [BackupV16Fixtures.artistRoleID.uuidString],+ createdAt: BackupV16Fixtures.created.addingTimeInterval(1_000),+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(1_000)), ]) // Creators only: no roles, and no credits at all. try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.creditsPayload(+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.creditsPayload( creators: [- BackupV15Fixtures.creatorRecord(+ BackupV16Fixtures.creatorRecord( id: renamed, name: "Mori Ayane",- nameModifiedAt: BackupV15Fixtures.created+ nameModifiedAt: BackupV16Fixtures.created .addingTimeInterval(2_000),- createdAt: BackupV15Fixtures.created.addingTimeInterval(1_000))+ createdAt: BackupV16Fixtures.created.addingTimeInterval(1_000)) ], creatorRoles: [], credits: []))) @@ -3685,13 +3685,13 @@ struct BackupV15ImportTests { #expect(creators.canonicalID(of: renamed) == kept) let rows = try await fixture.repository.creditRows()- .filter { $0.workID == BackupV15Fixtures.composedWorkID }+ .filter { $0.workID == BackupV16Fixtures.composedWorkID } #expect(rows.map(\.id) == [keptCredit]) #expect( rows.first?.roleIDs == [- BackupV15Fixtures.authorRoleID.uuidString,- BackupV15Fixtures.artistRoleID.uuidString,+ BackupV16Fixtures.authorRoleID.uuidString,+ BackupV16Fixtures.artistRoleID.uuidString, ].sorted()) } @@ -3705,60 +3705,60 @@ struct BackupV15ImportTests { /// seam it is a claim about: the store's blob, the projection's group scan, /// the codec's base64 and the importer's re-derived digest. The suites /// either side of it pin one seam each over a payload built in memory.- @Test("A 15/16 archive exported from one library imports whole into another")+ @Test("A 16/17 archive exported from one library imports whole into another") func exportedArchivesRoundTrip() async throws { let source = try await M5Fixture() try await source.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.coveredPayload()))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.coveredPayload())) - let payload = try await source.repository.backupV15Snapshot()+ let payload = try await source.repository.backupV16Snapshot() let plan = try BackupImporter.plan(- from: try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata()))+ from: try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())) let target = try await M5Fixture() try await target.repository.confirmImport(plan: plan) let characters = try await target.repository.m5AllCharacters()- let grover = try #require(characters.first { $0.id == BackupV15Fixtures.groverID })+ let grover = try #require(characters.first { $0.id == BackupV16Fixtures.groverID }) #expect(grover.name == "Grover") #expect(grover.facts.map(\.quote) == ["promised to guide them home"])- #expect(grover.workID == BackupV15Fixtures.workID)+ #expect(grover.workID == BackupV16Fixtures.workID) #expect( try await target.repository.m5SuppressionRows()- .contains { $0.id == BackupV15Fixtures.suppressionID })+ .contains { $0.id == BackupV16Fixtures.suppressionID }) #expect(- try await target.repository.m5EntryCoverage(BackupV15Fixtures.entryID)- == BackupV15Fixtures.noteFingerprint)+ try await target.repository.m5EntryCoverage(BackupV16Fixtures.entryID)+ == BackupV16Fixtures.noteFingerprint) // Req 5.1: the second kind makes the same trip, through the same // exporter, codec and gate. let keep = try #require( try await target.repository.m5AllPlaces()- .first { $0.id == BackupV15Fixtures.keepID })+ .first { $0.id == BackupV16Fixtures.keepID }) #expect(keep.name == "The High Keep") #expect(keep.facts.map(\.quote) == ["above the pass"])- #expect(keep.workID == BackupV15Fixtures.workID)+ #expect(keep.workID == BackupV16Fixtures.workID) #expect( try await target.repository.m5PlaceSuppressionRows()- .contains { $0.id == BackupV15Fixtures.placeSuppressionID })+ .contains { $0.id == BackupV16Fixtures.placeSuppressionID }) // Req 8.1: the cover made the same trip, byte for byte, with the digest // re-derived at the far end from bytes the file never carried one for. #expect(- try await target.repository.thumbnailColumns(of: BackupV15Fixtures.workID)+ try await target.repository.thumbnailColumns(of: BackupV16Fixtures.workID) == [ThumbnailColumns(- byteCount: BackupV15Fixtures.coverBytes.count,+ byteCount: BackupV16Fixtures.coverBytes.count, shapeRaw: ThumbnailShape.portrait.rawValue,- digest: BackupV15Fixtures.coverDigest)])+ digest: BackupV16Fixtures.coverDigest)]) #expect( try await target.repository.thumbnailBytes(- workID: BackupV15Fixtures.workID, digest: BackupV15Fixtures.coverDigest)- == BackupV15Fixtures.coverBytes)+ workID: BackupV16Fixtures.workID, digest: BackupV16Fixtures.coverDigest)+ == BackupV16Fixtures.coverBytes) } /// `catch-up-mode` Q6: the fourth reading status is vocabulary, not- /// structure, so it travels under the **unchanged** 15/16 pair — the wire+ /// structure, so it travels under the **unchanged** 16/17 pair — the wire /// field is already the typed enum and no generation moves for it. /// /// Asserted across the same three seams the cover crosses, because a value@@ -3766,59 +3766,59 @@ struct BackupV15ImportTests { /// default and read as a reader who never fell behind: out of the store /// through the real projection, through the codec, and into a different /// library.- @Test("A work on catchingUp exports and imports unchanged under 15/16")+ @Test("A work on catchingUp exports and imports unchanged under 16/17") func catchingUpRoundTrips() async throws { let source = try await M5Fixture() try await source.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.composedPayload(readingStatus: .catchingUp)))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.composedPayload(readingStatus: .catchingUp))) - let payload = try await source.repository.backupV15Snapshot()+ let payload = try await source.repository.backupV16Snapshot() #expect(- payload.works.first { $0.id == BackupV15Fixtures.composedWorkID }?.readingStatus+ payload.works.first { $0.id == BackupV16Fixtures.composedWorkID }?.readingStatus == .catchingUp) - let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).backupFormatVersion == 15)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).backupFormatVersion == 16) let target = try await M5Fixture() try await target.repository.confirmImport(plan: try BackupImporter.plan(from: encoded)) #expect(- try await target.repository.work(id: BackupV15Fixtures.composedWorkID).readingStatus+ try await target.repository.work(id: BackupV16Fixtures.composedWorkID).readingStatus == .catchingUp) } /// `to-read` Req 6.1, and the same reasoning as the case above: the fifth /// reading status is vocabulary rather than structure, so it travels under- /// the **unchanged** 15/16 pair and no generation moves for it.+ /// the **unchanged** 16/17 pair and no generation moves for it. /// /// The composed fixture's work carries an entry, which is the point of /// running it through this seam: a to-read work with chapters noted against /// it is a state the reader can author (Req 1.4) and a restore has to bring /// back as it was, rather than reading the entries as evidence that the /// work was started.- @Test("A work on toRead exports and imports unchanged under 15/16")+ @Test("A work on toRead exports and imports unchanged under 16/17") func toReadRoundTrips() async throws { let source = try await M5Fixture() try await source.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.composedPayload(readingStatus: .toRead)))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.composedPayload(readingStatus: .toRead))) - let payload = try await source.repository.backupV15Snapshot()+ let payload = try await source.repository.backupV16Snapshot() #expect(- payload.works.first { $0.id == BackupV15Fixtures.composedWorkID }?.readingStatus+ payload.works.first { $0.id == BackupV16Fixtures.composedWorkID }?.readingStatus == .toRead) - let encoded = try BackupV15Codec.encode(- payload: payload, metadata: BackupV15Fixtures.metadata())- #expect(try BackupV15Codec.decode(encoded).backupFormatVersion == 15)+ let encoded = try BackupV16Codec.encode(+ payload: payload, metadata: BackupV16Fixtures.metadata())+ #expect(try BackupV16Codec.decode(encoded).backupFormatVersion == 16) let target = try await M5Fixture() try await target.repository.confirmImport(plan: try BackupImporter.plan(from: encoded)) - let restored = try await target.repository.work(id: BackupV15Fixtures.composedWorkID)+ let restored = try await target.repository.work(id: BackupV16Fixtures.composedWorkID) #expect(restored.readingStatus == .toRead) #expect(restored.entries.count == 1) }@@ -3833,7 +3833,7 @@ struct BackupV15ImportTests { /// nothing. /// /// Driven over `BackupGoldenLibrary.payload`, which carries one record of- /// every kind the 15/16 payload holds — Sites and rules, Works, Entries,+ /// every kind the 16/17 payload holds — Sites and rules, Works, Entries, /// memberships, series, links, creators, creator roles and credits, plus /// characters, places and their suppressions — so the guard is exercised /// on every table the upsert writes, not just the ones a narrower fixture@@ -3848,17 +3848,17 @@ struct BackupV15ImportTests { let fixture = try await M5Fixture(saveStrategy: strategy) let payload = BackupGoldenLibrary.payload - try await fixture.repository.confirmImport(plan: BackupV15Fixtures.plan(payload))- let firstImport = try await fixture.repository.backupV15Snapshot()+ try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(payload))+ let firstImport = try await fixture.repository.backupV16Snapshot() strategy.arm()- try await fixture.repository.confirmImport(plan: BackupV15Fixtures.plan(payload))+ try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(payload)) #expect(strategy.saves > 0, "the second import must have reached its saves") #expect( strategy.dirtySaves.allSatisfy { !$0 }, "a second import of an unchanged archive must dirty no save, got \(strategy.dirtySaves)")- #expect(try await fixture.repository.backupV15Snapshot() == firstImport)+ #expect(try await fixture.repository.backupV16Snapshot() == firstImport) } /// The citation arm of the guard above, in one context so the store itself@@ -3875,7 +3875,7 @@ struct BackupV15ImportTests { /// 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let container = try ModelContainer( for: schema, configurations: [@@ -3884,7 +3884,7 @@ struct BackupV15ImportTests { ]) let context = ModelContext(container) context.autosaveEnabled = false- let record = try #require(BackupV15Fixtures.minimalTaughtPayload().entries.first)+ let record = try #require(BackupV16Fixtures.minimalTaughtPayload().entries.first) #expect(record.citations != EntryCitations(), "the arm needs a non-default value to compare") let entry = ArchiveRecordBuilders.makeEntry(record) context.insert(entry)@@ -3907,7 +3907,7 @@ struct BackupV15ImportTests { // guard written over the tolerant read (`citationValues`, which reads // undecodable bytes as the default) would see no difference and skip // the heal. This is the arm that pins the decode-and-compare.- let defaulted = BackupV15Entry(+ let defaulted = BackupV16Entry( id: record.id, captureTitle: record.captureTitle, captureTitleSource: record.captureTitleSource, rawURL: record.rawURL, canonicalURL: record.canonicalURL, hostname: record.hostname,@@ -3966,7 +3966,7 @@ struct BackupV15ImportTests { /// 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let container = try ModelContainer( for: schema, configurations: [@@ -3975,7 +3975,7 @@ struct BackupV15ImportTests { ]) let context = ModelContext(container) context.autosaveEnabled = false- let record = BackupV15Fixtures.character()+ let record = BackupV16Fixtures.character() #expect(!record.facts.isEmpty, "the arm needs a non-empty value to compare") let character = ArchiveRecordBuilders.makeCharacter(record) context.insert(character)@@ -4001,8 +4001,8 @@ struct BackupV15ImportTests { // MARK: - Test Doubles -private final class MockV15SnapshotProvider: BackupV15SnapshotProviding, @unchecked Sendable {- let payload: BackupV15Payload- init(payload: BackupV15Payload) { self.payload = payload }- func backupV15Snapshot() async throws -> BackupV15Payload { payload }+private final class MockV15SnapshotProvider: BackupV16SnapshotProviding, @unchecked Sendable {+ let payload: BackupV16Payload+ init(payload: BackupV16Payload) { self.payload = payload }+ func backupV16Snapshot() async throws -> BackupV16Payload { payload } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15Fixtures.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16Fixtures.swiftsimilarity index 92%rename from Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15Fixtures.swiftrename to Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16Fixtures.swiftindex 36dbf69a..5854662c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15Fixtures.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16Fixtures.swift@@ -20,7 +20,7 @@ import Foundation /// and a Work's series membership (T-2308). 11/12 added the creator table, the /// role list and the credits (T-2316). 13/14 added the cover (T-2330). 14/15 /// added the release days (`update-schedule`).-enum BackupV15Fixtures {+enum BackupV16Fixtures { static let created = Date(timeIntervalSince1970: 1_000_000) // MARK: - The cover (`work-thumbnails` Req 8.1)@@ -80,12 +80,12 @@ enum BackupV15Fixtures { shapeRaw: String? = ThumbnailShape.portrait.rawValue, bytes: Data? = coverBytes, modifiedAt: Date = created- ) -> BackupV15Payload {+ ) -> BackupV16Payload { let base = payload()- return BackupV15Payload(+ return BackupV16Payload( entries: base.entries, works: base.works.map { record in- BackupV15Work(+ BackupV16Work( id: record.id, displayTitle: record.displayTitle, lastParsedTitle: record.lastParsedTitle, genericNotes: record.genericNotes, genreTags: record.genreTags,@@ -152,8 +152,8 @@ enum BackupV15Fixtures { canonicalID: UUID? = nil, createdAt: Date = created, modifiedAt: Date = created- ) -> BackupV15WorkType {- BackupV15WorkType(+ ) -> BackupV16WorkType {+ BackupV16WorkType( id: id, name: name, stateRaw: state.rawValue, canonicalID: canonicalID, createdAt: createdAt, modifiedAt: modifiedAt) }@@ -171,8 +171,8 @@ enum BackupV15Fixtures { urlIdentityState: WorkURLIdentityState = .none, urlIdentityRuleID: UUID? = nil, workURLString: String? = nil- ) -> BackupV15Membership {- BackupV15Membership(+ ) -> BackupV16Membership {+ BackupV16Membership( id: id, workID: workID, hostname: hostname, createdAt: createdAt, urlIdentity: urlIdentity, urlIdentityState: urlIdentityState, urlIdentityRuleID: urlIdentityRuleID, workURLString: workURLString)@@ -193,13 +193,13 @@ enum BackupV15Fixtures { brokenAlias: Bool = false, workTypeID: UUID? = novelTypeID, typeName: String? = "novel",- workTypes: [BackupV15WorkType] = [workTypeRecord(id: novelTypeID, name: "novel")]- ) -> BackupV15Payload {+ workTypes: [BackupV16WorkType] = [workTypeRecord(id: novelTypeID, name: "novel")]+ ) -> BackupV16Payload { let host = minimalHost let patternID = UUID(uuidString: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")! let rawURL = "https://example.com/read/7" - let pattern = BackupV15TitlePattern(+ let pattern = BackupV16TitlePattern( id: patternID, siteHostname: host, version: 1, isActive: activePattern, createdAt: created, definition: StoredPatternDefinition(@@ -207,10 +207,10 @@ enum BackupV15Fixtures { work: try! SegmentRangeSpec(origin: .start, offset: 0, length: 1), ignored: []))) - let site = BackupV15Site(+ let site = BackupV16Site( hostname: host, displayName: "Example", mode: .taught) - let work = BackupV15Work(+ let work = BackupV16Work( id: minimalWorkID, displayTitle: "Constellation", lastParsedTitle: "Constellation", genericNotes: "", genreTags: [], titleProvenance: .parsed, workStatus: .ongoing, readingStatus: .reading, verdict: "",@@ -218,7 +218,7 @@ enum BackupV15Fixtures { workTypeID: workTypeID, typeName: typeName, createdAt: created, modifiedAt: created) - let entry = BackupV15Entry(+ let entry = BackupV16Entry( id: minimalEntryID, captureTitle: "Chapter 7", captureTitleSource: .host, rawURL: rawURL, canonicalURL: nil, hostname: host, entryIdentityKey: rawURL,@@ -229,7 +229,7 @@ enum BackupV15Fixtures { modifiedAt: created, workID: minimalWorkID, intentionallyUnattached: false, citations: EntryCitations(workAssignment: .manual)) - return BackupV15Payload(+ return BackupV16Payload( entries: [entry], works: [work], sites: [site], titlePatterns: [pattern], urlRules: [], workTypes: workTypes, memberships: [@@ -251,8 +251,8 @@ enum BackupV15Fixtures { readingStatus: ReadingStatus = .abandoned, workTypeID: UUID? = novelTypeID, typeName: String? = "novel",- workTypes: [BackupV15WorkType] = [workTypeRecord(id: novelTypeID, name: "novel")]- ) -> BackupV15Payload {+ workTypes: [BackupV16WorkType] = [workTypeRecord(id: novelTypeID, name: "novel")]+ ) -> BackupV16Payload { let host = "example.com" let patternID = UUID(uuidString: "cccccccc-cccc-cccc-cccc-cccccccccccc")! let ruleID = UUID(uuidString: "dddddddd-dddd-dddd-dddd-dddddddddddd")!@@ -260,25 +260,25 @@ enum BackupV15Fixtures { let workName = "Actual Title" // The whole-title rule names the Work by trimming the boilerplate prefix.- let pattern = BackupV15TitlePattern(+ let pattern = BackupV16TitlePattern( id: patternID, siteHostname: host, version: 1, isActive: true, createdAt: created, definition: StoredPatternDefinition( definition: .wholeTitle, trimPrefix: "TtH • Story • ")) // A sequence-only query rule extracts "94" from the raw URL.- let rule = BackupV15URLRule(+ let rule = BackupV16URLRule( id: ruleID, version: 1, isCurrent: true, createdAt: created, origin: .readerTaught, definition: .sequence(locator: .query(name: ExactScalarString("chapter"))), siteHostname: host) - let site = BackupV15Site(+ let site = BackupV16Site( hostname: host, displayName: "Example", mode: .taught) // Req 8.1: the composed fixture's Work carries all three off their // defaults, so a round trip that dropped one would show as a difference // rather than as a default that happened to match.- let work = BackupV15Work(+ let work = BackupV16Work( id: composedWorkID, displayTitle: workName, lastParsedTitle: workName, genericNotes: "", genreTags: [], titleProvenance: .parsed, workStatus: .finished, readingStatus: readingStatus,@@ -293,7 +293,7 @@ enum BackupV15Fixtures { hostname: ExactScalarString(host), workName: ExactScalarString(workName), chapterSequence: ExactScalarString("94"))) - let entry = BackupV15Entry(+ let entry = BackupV16Entry( id: entryID, captureTitle: "TtH • Story • Actual Title", captureTitleSource: .host, rawURL: rawURL, canonicalURL: nil, hostname: host, entryIdentityKey: v3Key, conservativeIdentityKey: rawURL,@@ -308,7 +308,7 @@ enum BackupV15Fixtures { chapterSequence: CitedRule(id: ruleID), workAssignment: .pattern(CitedRule(id: patternID)))) - return BackupV15Payload(+ return BackupV16Payload( entries: [entry], works: [work], sites: [site], titlePatterns: [pattern], urlRules: [rule], workTypes: workTypes, memberships: [@@ -329,8 +329,8 @@ enum BackupV15Fixtures { notes: String = "Read 2.5 after 2.", createdAt: Date = created, modifiedAt: Date = created- ) -> BackupV15Series {- BackupV15Series(+ ) -> BackupV16Series {+ BackupV16Series( id: id, name: name, notes: notes, createdAt: createdAt, modifiedAt: modifiedAt) } @@ -343,8 +343,8 @@ enum BackupV15Fixtures { type: String = "adaptation", createdAt: Date = created, modifiedAt: Date = created- ) -> BackupV15Link {- BackupV15Link(+ ) -> BackupV16Link {+ BackupV16Link( id: id, lowerWorkID: a, higherWorkID: b, linkType: type, createdAt: createdAt, modifiedAt: modifiedAt) }@@ -353,21 +353,21 @@ enum BackupV15Fixtures { /// both, and a link between them: the smallest payload that exercises every /// V12 shape at once. static func seriesPayload(- series: [BackupV15Series] = [seriesRecord()],- links: [BackupV15Link] = [linkRecord()],+ series: [BackupV16Series] = [seriesRecord()],+ links: [BackupV16Link] = [linkRecord()], firstMembership: (series: UUID, position: Double)? = (seriesID, 1), secondMembership: (series: UUID, position: Double)? = (seriesID, 2.5)- ) -> BackupV15Payload {+ ) -> BackupV16Payload { let base = composedPayload() let host = "example.com"- let second = BackupV15Work(+ let second = BackupV16Work( id: secondWorkID, displayTitle: "The Side Story", lastParsedTitle: nil, genericNotes: "", genreTags: [], titleProvenance: .manual, workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], workTypeID: nil, typeName: nil, createdAt: created, modifiedAt: created, seriesID: secondMembership?.series, seriesPosition: secondMembership?.position)- return BackupV15Payload(+ return BackupV16Payload( entries: base.entries, works: base.works.map { placed($0, membership: firstMembership) } + [second], sites: base.sites,@@ -383,12 +383,12 @@ enum BackupV15Fixtures { links: links) } - /// The composed Work with a membership pair. `BackupV15Work`'s fields are+ /// The composed Work with a membership pair. `BackupV16Work`'s fields are /// `let`, so a copy is a full restatement. static func placed(- _ record: BackupV15Work, membership: (series: UUID, position: Double)?- ) -> BackupV15Work {- BackupV15Work(+ _ record: BackupV16Work, membership: (series: UUID, position: Double)?+ ) -> BackupV16Work {+ BackupV16Work( id: record.id, displayTitle: record.displayTitle, lastParsedTitle: record.lastParsedTitle, genericNotes: record.genericNotes, genreTags: record.genreTags, titleProvenance: record.titleProvenance,@@ -403,13 +403,13 @@ enum BackupV15Fixtures { /// half-set and out-of-range shapes no writer produces and both archive /// doors refuse (Req 13.5). static func payloadWithMembership(- seriesID: UUID?, position: Double?, series: [BackupV15Series] = [seriesRecord()]- ) -> BackupV15Payload {+ seriesID: UUID?, position: Double?, series: [BackupV16Series] = [seriesRecord()]+ ) -> BackupV16Payload { let base = composedPayload()- return BackupV15Payload(+ return BackupV16Payload( entries: base.entries, works: base.works.map {- BackupV15Work(+ BackupV16Work( id: $0.id, displayTitle: $0.displayTitle, lastParsedTitle: $0.lastParsedTitle, genericNotes: $0.genericNotes, genreTags: $0.genreTags, titleProvenance: $0.titleProvenance,@@ -461,8 +461,8 @@ enum BackupV15Fixtures { notesModifiedAt: Date = created, stateModifiedAt: Date = created, createdAt: Date = created- ) -> BackupV15Creator {- BackupV15Creator(+ ) -> BackupV16Creator {+ BackupV16Creator( id: id, name: name, nameModifiedAt: nameModifiedAt, notes: notes, notesModifiedAt: notesModifiedAt, stateRaw: state.rawValue, stateModifiedAt: stateModifiedAt, canonicalID: canonicalID,@@ -480,8 +480,8 @@ enum BackupV15Fixtures { positionModifiedAt: Date = created, stateModifiedAt: Date = created, createdAt: Date = created- ) -> BackupV15CreatorRole {- BackupV15CreatorRole(+ ) -> BackupV16CreatorRole {+ BackupV16CreatorRole( id: id, name: name, nameModifiedAt: nameModifiedAt, position: position, positionModifiedAt: positionModifiedAt, stateRaw: state.rawValue, stateModifiedAt: stateModifiedAt, canonicalID: canonicalID,@@ -492,7 +492,7 @@ enum BackupV15Fixtures { /// One of the three defaults exactly as a library that has only ever seeded /// holds it: the frozen identity, the shipped spelling and place, and the /// pristine sentinel on every timestamp.- static func seededRoleRecord(_ seed: CreatorRoleSeeding.Seed) -> BackupV15CreatorRole {+ static func seededRoleRecord(_ seed: CreatorRoleSeeding.Seed) -> BackupV16CreatorRole { creatorRoleRecord( id: seed.id, name: seed.name, position: seed.position, nameModifiedAt: pristine, positionModifiedAt: pristine,@@ -500,7 +500,7 @@ enum BackupV15Fixtures { } /// The three seeds, in list order.- static var seededRoleRecords: [BackupV15CreatorRole] {+ static var seededRoleRecords: [BackupV16CreatorRole] { CreatorRoleSeeding.seeds.map(seededRoleRecord) } @@ -511,8 +511,8 @@ enum BackupV15Fixtures { roleIDs: [UUID] = [], createdAt: Date = created, modifiedAt: Date = created- ) -> BackupV15Credit {- BackupV15Credit(+ ) -> BackupV16Credit {+ BackupV16Credit( id: id, workID: workID, creatorID: creatorID, roleIDs: roleIDs.map(\.uuidString).sorted(), createdAt: createdAt, modifiedAt: modifiedAt)@@ -520,7 +520,7 @@ enum BackupV15Fixtures { /// The two creators, the alias between them, and the archive's role list: /// the three seeds plus a reader-added `letterer` and a removed `editor`.- static var creatorRecords: [BackupV15Creator] {+ static var creatorRecords: [BackupV16Creator] { [ creatorRecord(id: moriID, name: "Mori Ayane", notes: "Also draws."), creatorRecord(id: studioID, name: "Studio Lantern"),@@ -529,7 +529,7 @@ enum BackupV15Fixtures { ] } - static var creatorRoleRecords: [BackupV15CreatorRole] {+ static var creatorRoleRecords: [BackupV16CreatorRole] { seededRoleRecords + [ creatorRoleRecord(id: lettererRoleID, name: "letterer", position: 3), creatorRoleRecord(@@ -541,7 +541,7 @@ enum BackupV15Fixtures { /// including the removed one, one naming the **alias** creator, and one whose /// work the archive does not carry — the tolerated unresolved shape of /// Req 9.5.- static var creditRecords: [BackupV15Credit] {+ static var creditRecords: [BackupV16Credit] { [ creditRecord( id: moriCreditID, workID: composedWorkID, creatorID: moriID,@@ -559,12 +559,12 @@ enum BackupV15Fixtures { /// `seriesPayload` plus the whole V12 surface: the creator table, the role /// list and the credits over both works. static func creditsPayload(- creators: [BackupV15Creator]? = nil,- creatorRoles: [BackupV15CreatorRole]? = nil,- credits: [BackupV15Credit]? = nil- ) -> BackupV15Payload {+ creators: [BackupV16Creator]? = nil,+ creatorRoles: [BackupV16CreatorRole]? = nil,+ credits: [BackupV16Credit]? = nil+ ) -> BackupV16Payload { let base = seriesPayload()- return BackupV15Payload(+ return BackupV16Payload( entries: base.entries, works: base.works, sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: base.memberships,@@ -584,12 +584,12 @@ enum BackupV15Fixtures { /// unanchored — which selection would happily resolve on a single-component /// path, so the import gate's `validate` call is the only thing standing /// between such an archive and the store (Req 1.3, Q5/Q7).- static func unanchoredRulePayload(leftAnchored: Bool) -> BackupV15Payload {+ static func unanchoredRulePayload(leftAnchored: Bool) -> BackupV16Payload { let host = "unanchored.example" let patternID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff1")! let ruleID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff2")! - let pattern = BackupV15TitlePattern(+ let pattern = BackupV16TitlePattern( id: patternID, siteHostname: host, version: 1, isActive: true, createdAt: created, definition: StoredPatternDefinition( definition: .segment(@@ -597,16 +597,16 @@ enum BackupV15Fixtures { ignored: []))) let left: PathAnchor = leftAnchored ? .literal(ExactScalarString("series")) : .unanchored- let rule = BackupV15URLRule(+ let rule = BackupV16URLRule( id: ruleID, version: 1, isCurrent: true, createdAt: created, origin: .readerTaught, definition: .work(locator: .pathBracketed(left: left, right: .unanchored)), siteHostname: host) - let site = BackupV15Site(+ let site = BackupV16Site( hostname: host, displayName: "Unanchored", mode: .taught) - return BackupV15Payload(+ return BackupV16Payload( entries: [], works: [], sites: [site], titlePatterns: [pattern], urlRules: [rule], workTypes: []) }@@ -621,16 +621,16 @@ enum BackupV15Fixtures { /// Fixed UUIDs and a fixed date, so the encoded bytes are stable and can be /// asserted on directly — which a fixture generated by a teaching commit /// cannot be (it mints random UUIDs and wall-clock timestamps).- static func combinedRulePayload(presence: URLSequencePresence) -> BackupV15Payload {+ static func combinedRulePayload(presence: URLSequencePresence) -> BackupV16Payload { let patternID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff3")! let ruleID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff4")! - let pattern = BackupV15TitlePattern(+ let pattern = BackupV16TitlePattern( id: patternID, siteHostname: combinedRuleHost, version: 1, isActive: true, createdAt: created, definition: StoredPatternDefinition(definition: .wholeTitle)) - let rule = BackupV15URLRule(+ let rule = BackupV16URLRule( id: ruleID, version: 1, isCurrent: true, createdAt: created, origin: .readerTaught, definition: .combined(@@ -643,10 +643,10 @@ enum BackupV15Fixtures { sequencePresence: presence)), siteHostname: combinedRuleHost) - let site = BackupV15Site(+ let site = BackupV16Site( hostname: combinedRuleHost, displayName: "Combined", mode: .taught) - return BackupV15Payload(+ return BackupV16Payload( entries: [], works: [], sites: [site], titlePatterns: [pattern], urlRules: [rule], workTypes: []) }@@ -680,7 +680,7 @@ enum BackupV15Fixtures { /// over that literal text rather than over a re-encoding of it. /// /// The checksum is what makes such a fixture a test rather than a- /// restatement: `BackupV15Codec.decode` re-encodes the payload it decoded and+ /// restatement: `BackupV16Codec.decode` re-encodes the payload it decoded and /// compares a SHA-256, so a literal carrying a key the codec does not write /// back — an omitted spelling the build no longer produces, or a citation /// `version` it now ignores — fails with `checksumMismatch` (Decision 1).@@ -696,8 +696,8 @@ enum BackupV15Fixtures { ) -> Data { let checksum = SHA256.hash(data: Data(payload.utf8)) .map { String(format: "%02x", $0) }.joined()- let format = BackupV15Document.formatVersion- let schema = BackupV15Document.schemaVersion+ let format = BackupV16Document.formatVersion+ let schema = BackupV16Document.schemaVersion // Built in steps rather than as one concatenation: with the two numbers // interpolated the single expression no longer type-checks in // reasonable time.@@ -756,9 +756,10 @@ enum BackupV15Fixtures { + #""workTypes":[{"createdAt":"1970-01-12T13:46:40.000Z","# + #""id":"00000000-0000-0000-0000-0000000000A1","modifiedAt":"1970-01-12T13:46:40.000Z","# + #""name":"novel","stateRaw":"active"}],"works":[{"#- + #""createdAt":"1970-01-12T13:46:40.000Z","#+ + #""countsUpOnReleaseDays":true,"createdAt":"1970-01-12T13:46:40.000Z","# + #""displayTitle":"Actual Title","genericNotes":"","genreTags":[],"# + #""id":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","lastParsedTitle":"Actual Title","#+ + #""latestIsEstimate":false,"# + #""modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"reading","# + #""releaseDays":[],"titleProvenance":"parsed","typeName":"novel","verdict":"","# + #""workStatus":"ongoing","#@@ -834,7 +835,7 @@ enum BackupV15Fixtures { // MARK: - A Site carrying a mode this build cannot name (`remove-article-mode` Req 5.1) /// The same literal with the one Site's `mode` replaced by a spelling this- /// build has no case for. `BackupV15Site.mode` is the typed `SiteMode`, so+ /// build has no case for. `BackupV16Site.mode` is the typed `SiteMode`, so /// the value fails the decode and the archive is refused as malformed. /// /// The spelling is a **neutral** one rather than the retired `articles`,@@ -855,21 +856,21 @@ enum BackupV15Fixtures { /// Both shapes were refusals until T-2281 retired the invariant: a Site's /// rule versions had to be unique and the marked row had to hold the /// greatest. The column is advisory now, so this archive imports.- static func duplicateVersionsPayload() -> BackupV15Payload {+ static func duplicateVersionsPayload() -> BackupV16Payload { let host = "versions.example" let retiredPatternID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff5")! let activePatternID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff6")! let retiredRuleID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff7")! let currentRuleID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff8")! - func pattern(_ id: UUID, active: Bool, createdAt: Date) -> BackupV15TitlePattern {- BackupV15TitlePattern(+ func pattern(_ id: UUID, active: Bool, createdAt: Date) -> BackupV16TitlePattern {+ BackupV16TitlePattern( id: id, siteHostname: host, version: 1, isActive: active, createdAt: createdAt, definition: StoredPatternDefinition(definition: .wholeTitle)) } - func rule(_ id: UUID, version: Int, current: Bool, createdAt: Date) -> BackupV15URLRule {- BackupV15URLRule(+ func rule(_ id: UUID, version: Int, current: Bool, createdAt: Date) -> BackupV16URLRule {+ BackupV16URLRule( id: id, version: version, isCurrent: current, createdAt: createdAt, origin: .readerTaught, definition: .sequence(@@ -877,10 +878,10 @@ enum BackupV15Fixtures { siteHostname: host) } - return BackupV15Payload(+ return BackupV16Payload( entries: [], works: [], sites: [- BackupV15Site(+ BackupV16Site( hostname: host, displayName: "Versions", mode: .taught) ], titlePatterns: [@@ -898,21 +899,21 @@ enum BackupV15Fixtures { // MARK: - Two current URL rules (illegal) - static func twoCurrentRulePayload() -> BackupV15Payload {+ static func twoCurrentRulePayload() -> BackupV16Payload { let host = "dup.example" let patternID = UUID() let ruleA = UUID() let ruleB = UUID() - let pattern = BackupV15TitlePattern(+ let pattern = BackupV16TitlePattern( id: patternID, siteHostname: host, version: 1, isActive: true, createdAt: created, definition: StoredPatternDefinition( definition: .segment( work: try! SegmentRangeSpec(origin: .start, offset: 0, length: 1), ignored: []))) - func rule(_ id: UUID, _ version: Int) -> BackupV15URLRule {- BackupV15URLRule(+ func rule(_ id: UUID, _ version: Int) -> BackupV16URLRule {+ BackupV16URLRule( id: id, version: version, isCurrent: true, createdAt: created, origin: .readerTaught, definition: .sequence(@@ -920,10 +921,10 @@ enum BackupV15Fixtures { siteHostname: host) } - let site = BackupV15Site(+ let site = BackupV16Site( hostname: host, displayName: "Dup", mode: .taught) - return BackupV15Payload(+ return BackupV16Payload( entries: [], works: [], sites: [site], titlePatterns: [pattern], urlRules: [rule(ruleA, 1), rule(ruleB, 2)], workTypes: [])@@ -950,8 +951,8 @@ enum BackupV15Fixtures { facts: [RecordFact] = [fact()], createdAt: Date = created, modifiedAt: Date = created- ) -> BackupV15Character {- BackupV15Character(+ ) -> BackupV16Character {+ BackupV16Character( id: id, workID: workID, name: name, nameKey: nameKey, aliases: aliases, note: note, facts: facts, createdAt: createdAt, modifiedAt: modifiedAt) }@@ -965,8 +966,8 @@ enum BackupV15Fixtures { evidence: String? = nil, status: CharacterSuppressionStatus = .active, actionAt: Date = created- ) -> BackupV15Suppression {- BackupV15Suppression(+ ) -> BackupV16Suppression {+ BackupV16Suppression( id: id, workID: workID, kindRaw: kind.rawValue, nameKey: nameKey, sourceKindRaw: source?.kindRaw, sourceEntryID: source?.entryID, evidence: evidence, statusRaw: status.rawValue, actionAt: actionAt)@@ -987,8 +988,8 @@ enum BackupV15Fixtures { facts: [RecordFact] = [placeFact()], createdAt: Date = created, modifiedAt: Date = created- ) -> BackupV15Place {- BackupV15Place(+ ) -> BackupV16Place {+ BackupV16Place( id: id, workID: workID, name: name, nameKey: nameKey, aliases: aliases, note: note, facts: facts, createdAt: createdAt, modifiedAt: modifiedAt) }@@ -1011,8 +1012,8 @@ enum BackupV15Fixtures { evidence: String? = nil, status: CharacterSuppressionStatus = .active, actionAt: Date = created- ) -> BackupV15PlaceSuppression {- BackupV15PlaceSuppression(+ ) -> BackupV16PlaceSuppression {+ BackupV16PlaceSuppression( id: id, workID: workID, kindRaw: kind.rawValue, nameKey: nameKey, sourceKindRaw: source?.kindRaw, sourceEntryID: source?.entryID, evidence: evidence, statusRaw: status.rawValue, actionAt: actionAt)@@ -1029,15 +1030,15 @@ enum BackupV15Fixtures { /// it and the defaults are taken from them — a caller passing something else /// is describing a stale pair on purpose. static func payload(- characters: [BackupV15Character] = [character()],- suppressions: [BackupV15Suppression] = [suppression()],- places: [BackupV15Place] = [place()],- placeSuppressions: [BackupV15PlaceSuppression] = [placeSuppression()],+ characters: [BackupV16Character] = [character()],+ suppressions: [BackupV16Suppression] = [suppression()],+ places: [BackupV16Place] = [place()],+ placeSuppressions: [BackupV16PlaceSuppression] = [placeSuppression()], entryFingerprint: String? = noteFingerprint, workFingerprint: String? = genericNotesFingerprint- ) -> BackupV15Payload {+ ) -> BackupV16Payload { let base = composedPayload()- return BackupV15Payload(+ return BackupV16Payload( entries: base.entries.map { noted($0, fingerprint: entryFingerprint) }, works: base.works.map { annotated($0, fingerprint: workFingerprint) }, sites: base.sites,@@ -1053,16 +1054,16 @@ enum BackupV15Fixtures { } static func metadata(appBuild: String = "test-12", exportedAt: Date = created)- -> BackupV15Metadata+ -> BackupV16Metadata {- BackupV15Metadata(appBuild: appBuild, exportedAt: exportedAt)+ BackupV16Metadata(appBuild: appBuild, exportedAt: exportedAt) } - static func plan(_ payload: BackupV15Payload) -> BackupImportPlan {+ static func plan(_ payload: BackupV16Payload) -> BackupImportPlan { BackupImportPlan( metadata: BackupImportMetadata(- formatVersion: BackupV15Document.formatVersion,- schemaVersion: BackupV15Document.schemaVersion,+ formatVersion: BackupV16Document.formatVersion,+ schemaVersion: BackupV16Document.schemaVersion, appBuild: "test-12", exportedAt: created, capabilityGate: "multi-site", entryCount: payload.entries.count, workCount: payload.works.count),@@ -1085,7 +1086,7 @@ enum BackupV15Fixtures { /// for a mode this build does not know and a column V16 does not have, so /// the only thing this build could do with one is drop what it carries /// silently.- static func retiredGenerationDocument(format: Int = 14, schema: Int = 15) -> Data {+ static func retiredGenerationDocument(format: Int = 15, schema: Int = 16) -> Data { let payload = #"{"entries":[],"sites":[],"titlePatterns":[],"urlRules":[],"works":[]}"# let checksum = SHA256.hash(data: Data(payload.utf8)) .map { String(format: "%02x", $0) }.joined()@@ -1098,11 +1099,11 @@ enum BackupV15Fixtures { // MARK: - Copies of the frozen records - /// The composed Entry with a note and its covered revision. `BackupV15Entry`'s+ /// The composed Entry with a note and its covered revision. `BackupV16Entry`'s /// fields are `let`, so a copy is a full restatement — stated once here /// rather than in each suite.- private static func noted(_ record: BackupV15Entry, fingerprint: String?) -> BackupV15Entry {- BackupV15Entry(+ private static func noted(_ record: BackupV16Entry, fingerprint: String?) -> BackupV16Entry {+ BackupV16Entry( id: record.id, captureTitle: record.captureTitle, captureTitleSource: record.captureTitleSource, rawURL: record.rawURL, canonicalURL: record.canonicalURL, hostname: record.hostname,@@ -1120,8 +1121,8 @@ enum BackupV15Fixtures { } /// The composed Work with generic notes and its covered revision.- private static func annotated(_ record: BackupV15Work, fingerprint: String?) -> BackupV15Work {- BackupV15Work(+ private static func annotated(_ record: BackupV16Work, fingerprint: String?) -> BackupV16Work {+ BackupV16Work( id: record.id, displayTitle: record.displayTitle, lastParsedTitle: record.lastParsedTitle, genericNotes: genericNotes, genreTags: record.genreTags, titleProvenance: record.titleProvenance,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ImportMatrixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16ImportMatrixTests.swiftsimilarity index 79%rename from Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ImportMatrixTests.swiftrename to Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16ImportMatrixTests.swiftindex 971e9244..48238eb9 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ImportMatrixTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV16ImportMatrixTests.swift@@ -5,7 +5,7 @@ import Testing /// Task 9 of `update-schedule`: the release days at the archive's two doors. ///-/// `BackupV15ArchiveTests` covers the generation as a whole; this suite is the+/// `BackupV16ArchiveTests` covers the generation as a whole; this suite is the /// matrix for the one field 14/15 added. Req 8.1 asks for three things and they /// pull in opposite directions, which is why they are pinned together: an empty /// set is written **explicitly** and restores as empty, a non-empty one restores@@ -13,8 +13,8 @@ import Testing /// name — is malformed rather than restorable. A default on decode would make /// the first and the third indistinguishable (Q22), and a tolerant read would /// make the fourth silently lose a day the reader typed (Q36).-@Suite("Backup 15/16 import: release days", .serialized)-struct BackupV15ImportMatrixTests {+@Suite("Backup 16/17 import: release days", .serialized)+struct BackupV16ImportMatrixTests { // MARK: - What restores (Req 8.1) @@ -23,13 +23,13 @@ struct BackupV15ImportMatrixTests { let fixture = try await M5Fixture() let result = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(BackupV15Fixtures.composedPayload(releaseDays: [])))+ plan: BackupV16Fixtures.plan(BackupV16Fixtures.composedPayload(releaseDays: []))) guard case .committed = result else { Issue.record("expected committed, got \(result)") return } - let work = try await fixture.repository.work(id: BackupV15Fixtures.composedWorkID)+ let work = try await fixture.repository.work(id: BackupV16Fixtures.composedWorkID) #expect(work.releaseDays == []) #expect(work.releaseDaysRaw == []) }@@ -39,14 +39,14 @@ struct BackupV15ImportMatrixTests { let fixture = try await M5Fixture() let result = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.composedPayload(releaseDays: [.thursday, .monday])))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.composedPayload(releaseDays: [.thursday, .monday]))) guard case .committed = result else { Issue.record("expected committed, got \(result)") return } - let work = try await fixture.repository.work(id: BackupV15Fixtures.composedWorkID)+ let work = try await fixture.repository.work(id: BackupV16Fixtures.composedWorkID) #expect(work.releaseDays == [.monday, .thursday]) // Req 7.5: one spelling in the store, whatever order the file held. #expect(work.releaseDaysRaw == ["monday", "thursday"])@@ -61,18 +61,18 @@ struct BackupV15ImportMatrixTests { func importReplacesTheLocalSchedule() async throws { let fixture = try await M5Fixture() _ = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.composedPayload(releaseDays: [.friday])))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.composedPayload(releaseDays: [.friday]))) #expect(- try await fixture.repository.work(id: BackupV15Fixtures.composedWorkID).releaseDays+ try await fixture.repository.work(id: BackupV16Fixtures.composedWorkID).releaseDays == [.friday]) // The same record, a second later, with the schedule cleared.- let cleared = BackupV15Fixtures.composedPayload(releaseDays: [])- let newer = BackupV15Payload(+ let cleared = BackupV16Fixtures.composedPayload(releaseDays: [])+ let newer = BackupV16Payload( entries: cleared.entries, works: cleared.works.map { record in- BackupV15Work(+ BackupV16Work( id: record.id, displayTitle: record.displayTitle, lastParsedTitle: record.lastParsedTitle, genericNotes: record.genericNotes, genreTags: record.genreTags,@@ -87,10 +87,10 @@ struct BackupV15ImportMatrixTests { urlRules: cleared.urlRules, workTypes: cleared.workTypes, memberships: cleared.memberships) - _ = try await fixture.repository.confirmImport(plan: BackupV15Fixtures.plan(newer))+ _ = try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(newer)) #expect(- try await fixture.repository.work(id: BackupV15Fixtures.composedWorkID).releaseDays+ try await fixture.repository.work(id: BackupV16Fixtures.composedWorkID).releaseDays == []) } @@ -101,14 +101,14 @@ struct BackupV15ImportMatrixTests { func olderArchiveDoesNotRegressTheSchedule() async throws { let fixture = try await M5Fixture() _ = try await fixture.repository.confirmImport(- plan: BackupV15Fixtures.plan(- BackupV15Fixtures.composedPayload(releaseDays: [.friday])))+ plan: BackupV16Fixtures.plan(+ BackupV16Fixtures.composedPayload(releaseDays: [.friday]))) - let stale = BackupV15Fixtures.composedPayload(releaseDays: [.monday])- let older = BackupV15Payload(+ let stale = BackupV16Fixtures.composedPayload(releaseDays: [.monday])+ let older = BackupV16Payload( entries: stale.entries, works: stale.works.map { record in- BackupV15Work(+ BackupV16Work( id: record.id, displayTitle: record.displayTitle, lastParsedTitle: record.lastParsedTitle, genericNotes: record.genericNotes, genreTags: record.genreTags,@@ -123,10 +123,10 @@ struct BackupV15ImportMatrixTests { urlRules: stale.urlRules, workTypes: stale.workTypes, memberships: stale.memberships) - _ = try await fixture.repository.confirmImport(plan: BackupV15Fixtures.plan(older))+ _ = try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(older)) #expect(- try await fixture.repository.work(id: BackupV15Fixtures.composedWorkID).releaseDays+ try await fixture.repository.work(id: BackupV16Fixtures.composedWorkID).releaseDays == [.friday]) } @@ -137,14 +137,14 @@ struct BackupV15ImportMatrixTests { /// the typed decode gives up on the missing key before the payload is ever /// re-encoded — and the paired assertion pins it to that key rather than to /// the paste: the identical literal carrying it decodes.- @Test("A 15/16 Work record omitting releaseDays fails to decode")+ @Test("A 16/17 Work record omitting releaseDays fails to decode") func recordWithoutTheFieldRefuses() throws {- let document = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.releaseDaysOmittedPayloadJSON,+ let document = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.releaseDaysOmittedPayloadJSON, entryCount: 1, workCount: 1) do {- _ = try BackupV15Codec.decode(document)+ _ = try BackupV16Codec.decode(document) Issue.record("expected a decode refusal, but the document decoded") } catch let error as BackupCodecError { guard case .decodingFailed = error else {@@ -153,10 +153,10 @@ struct BackupV15ImportMatrixTests { } } - let complete = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.citationVersionFreePayloadJSON,+ let complete = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)- let record = try #require(try BackupV15Codec.decode(complete).payload.works.first)+ let record = try #require(try BackupV16Codec.decode(complete).payload.works.first) #expect(record.releaseDays == []) } @@ -164,14 +164,14 @@ struct BackupV15ImportMatrixTests { /// build has no case for fails the decode. There is no tolerant reading of a /// backup — restoring `funday` as nothing would drop a day the reader typed, /// silently, out of the file that is supposed to be the copy.- @Test("A 15/16 Work record carrying an unknown day fails to decode")+ @Test("A 16/17 Work record carrying an unknown day fails to decode") func recordWithAnUnknownDayRefuses() throws {- let document = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.unknownReleaseDayPayloadJSON,+ let document = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.unknownReleaseDayPayloadJSON, entryCount: 1, workCount: 1) do {- _ = try BackupV15Codec.decode(document)+ _ = try BackupV16Codec.decode(document) Issue.record("expected a decode refusal, but the document decoded") } catch let error as BackupCodecError { guard case .decodingFailed = error else {@@ -182,10 +182,10 @@ struct BackupV15ImportMatrixTests { // The same literal with a spelling this build *can* name decodes, so the // refusal is about the value rather than about the key or the paste.- let known = BackupV15Fixtures.literalDocument(- payload: BackupV15Fixtures.populatedReleaseDaysPayloadJSON,+ let known = BackupV16Fixtures.literalDocument(+ payload: BackupV16Fixtures.populatedReleaseDaysPayloadJSON, entryCount: 1, workCount: 1)- let record = try #require(try BackupV15Codec.decode(known).payload.works.first)+ let record = try #require(try BackupV16Codec.decode(known).payload.works.first) #expect(record.releaseDays == [.monday, .thursday]) } @@ -193,12 +193,12 @@ struct BackupV15ImportMatrixTests { /// **by version**, with the message naming both pairs, and nothing is /// written. A 14/15 file is not corrupt — it is one build old, and its Site /// records carry a junk-suffix rule for a mode this build does not know,- /// which is precisely why it cannot be read as a 15/16 one (Q2).+ /// which is precisely why it cannot be read as a 16/17 one (Q2). @Test("A 14/15 archive is refused by pair, naming it and the supported one") func thePreviousGenerationRefusesByPair() async throws { let fixture = try await M5Fixture() let before = try await fixture.repository.sites()- let data = BackupV15Fixtures.retiredGenerationDocument(format: 14, schema: 15)+ let data = BackupV16Fixtures.retiredGenerationDocument(format: 15, schema: 16) let error = #expect(throws: BackupImportError.self) { try BackupImporter.plan(from: data)@@ -207,9 +207,9 @@ struct BackupV15ImportMatrixTests { Issue.record("expected an unsupported-format refusal, got \(String(describing: error))") return }- #expect(reason.contains("format 14"))- #expect(reason.contains("schema 15"))- #expect(reason.contains("(15/16)"))+ #expect(reason.contains("format 15"))+ #expect(reason.contains("schema 16"))+ #expect(reason.contains("(16/17)")) // 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 37772b05..4e7ce089 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() == "16",+ #expect(try root.markerText() == "17", "a crash between store creation and the marker is repaired, not terminal") withExtendedLifetime(root) {} }@@ -269,7 +269,7 @@ struct BootstrapActionTests { // the owner's library (Decision 5) — and the container construction is // what fails. try Data("this is not a sqlite store".utf8).write(to: root.storeURL, options: .atomic)- try root.writeMarker("16\n")+ try root.writeMarker("17\n") let before = try root.digest() await #expect(throws: (any Error).self) {@@ -309,10 +309,10 @@ private enum RefusedState: String, CaseIterable, Sendable { switch self { case .storeRecordedBelowV5: try root.installStoreRecordedAtFourZeroZero()- try root.writeMarker("16\n")+ try root.writeMarker("17\n") case .readinessMarkerWithoutAStore: try root.createStoreDirectory()- try root.writeMarker("16\n")+ try root.writeMarker("17\n") case .historicalMarkerWithoutAStore: try root.createStoreDirectory() try root.writeHistoricalMarker()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swiftindex 200dceb6..a5f67eed 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("16\n")+ try root.writeMarker("17\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("16\n")+ try root.writeMarker("17\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("16\n")+ try root.writeMarker("17\n") try #require(StoreMetadata.recordedVersion(at: root.storeURL) == .indeterminate) #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready,@@ -429,6 +429,7 @@ private struct Cell: Sendable, CustomStringConvertible { case .fourteen: try root.writeMarker("14\n") case .fifteen: try root.writeMarker("15\n") case .sixteen: try root.writeMarker("16\n")+ case .seventeen: try root.writeMarker("17\n") case .unrecognisedText: try root.writeMarker("99\n") case .nonUTF8: try root.writeMarkerBytes(ClassifierRoot.nonUTF8MarkerBytes) }@@ -441,8 +442,8 @@ private struct Cell: Sendable, CustomStringConvertible { func expectedState(recordedVersion: StoreMetadata.RecordedVersion) -> BootstrapState { if case .below(let version) = recordedVersion { return .belowV5(version: version) } let storePresent = family.isStorePresent- if marker == .sixteen, storePresent { return .ready }- if marker == .fifteen, storePresent { return .markerLagging(generation: "15") }+ if marker == .seventeen, storePresent { return .ready }+ if marker == .sixteen, storePresent { return .markerLagging(generation: "16") } if !storePresent { if marker != .absent { return .orphanedEvidence(kind: .readinessMarker) } if historicalMarker { return .orphanedEvidence(kind: .historicalMarker) }@@ -469,7 +470,7 @@ private enum StoreFamily: String, CaseIterable, Sendable { } private enum MarkerAxis: String, CaseIterable, Sendable {- case absent, four, five, six, fourteen, fifteen, sixteen, unrecognisedText, nonUTF8+ case absent, four, five, six, fourteen, fifteen, sixteen, seventeen, unrecognisedText, nonUTF8 } /// What the seeded main file is meant to record. The expectation is derived from
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swiftindex 53b2ef33..57bb3c01 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift@@ -269,7 +269,7 @@ private enum PreCertificationState: String, CaseIterable, Sendable { case .storeWithRetiredMarkerSix: try root.writeMarker("6\n") case .storeWithLaggingMarkerSeven:- try root.writeMarker("15\n")+ try root.writeMarker("16\n") } } }@@ -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 = "16\n"+private let readyMarkerBytes = "17\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.swiftnew file mode 100644index 00000000..7bb0153e--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift@@ -0,0 +1,171 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Catch-up archive 16/17", .serialized)+struct CatchUpArchiveTests {+ private static let base = BackupV16Fixtures.minimalTaughtPayload()+ private static let confirmedAt = Date(timeIntervalSince1970: 1_800_000_012)+ private static let overrideAt = Date(timeIntervalSince1970: 1_800_000_014)++ private static func payload(+ latest: Int? = 52, confirmation: Date? = confirmedAt,+ override: Int? = 30, overrideMoment: Date? = overrideAt,+ modifiedAt: Date = BackupV16Fixtures.created+ ) -> BackupV16Payload {+ let original = base.works[0]+ let work = BackupV16Work(+ id: original.id, displayTitle: original.displayTitle,+ lastParsedTitle: original.lastParsedTitle, genericNotes: original.genericNotes,+ genreTags: original.genreTags, titleProvenance: original.titleProvenance,+ workStatus: original.workStatus, readingStatus: original.readingStatus,+ verdict: original.verdict, releaseDays: original.releaseDays,+ workTypeID: original.workTypeID, typeName: original.typeName,+ createdAt: original.createdAt, modifiedAt: modifiedAt,+ latestReleasedChapter: latest, latestConfirmedAt: confirmation,+ countsUpOnReleaseDays: false, latestIsEstimate: true,+ lastChapterOverride: override, lastChapterOverrideAt: overrideMoment)+ return BackupV16Payload(+ entries: base.entries, works: [work], 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)+ }++ @Test("All six flat fields round-trip and a clear retains its moment")+ func wireFields() throws {+ let original = Self.payload(override: nil)+ let data = try BackupV16Codec.encode(payload: original, metadata: BackupV16Fixtures.metadata())+ let work = try #require(try BackupV16Codec.decode(data).payload.works.first)+ #expect(work.latestReleasedChapter == 52)+ #expect(work.latestConfirmedAt == Self.confirmedAt)+ #expect(work.countsUpOnReleaseDays == false)+ #expect(work.latestIsEstimate)+ #expect(work.lastChapterOverride == nil)+ #expect(work.lastChapterOverrideAt == Self.overrideAt)+ #expect(work.catchUpRecord.override == .cleared(+ atMilliseconds: MillisecondInstant.milliseconds(Self.overrideAt)))+ }++ @Test("A number without its moment is ignored, and out-of-range numbers refuse")+ func incompleteAndInvalidValues() throws {+ #expect(Self.payload(confirmation: nil, overrideMoment: nil).works[0].catchUpRecord == .pristine)+ for number in [-1, 10_000, Int.max] {+ #expect(throws: BackupCodecError.self) {+ let data = try BackupV16Codec.encode(+ payload: Self.payload(latest: number), metadata: BackupV16Fixtures.metadata())+ _ = try BackupV16Codec.decode(data)+ }+ #expect(throws: BackupCodecError.self) {+ let data = try BackupV16Codec.encode(+ payload: Self.payload(override: number), metadata: BackupV16Fixtures.metadata())+ _ = try BackupV16Codec.decode(data)+ }+ }+ }++ @Test("Import folds progress before the older authored-record guard and is idempotent")+ func olderRecordStillCarriesNewerProgress() async throws {+ let saves = ChangeRecordingSaveStrategy()+ let fixture = try await M5Fixture(saveStrategy: saves)+ let local = Self.payload(latest: 30, confirmation: Self.confirmedAt,+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(100))+ _ = try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(local))+ let older = Self.payload(latest: 40, confirmation: Self.confirmedAt.addingTimeInterval(10),+ modifiedAt: BackupV16Fixtures.created)+ let plan = BackupV16Fixtures.plan(older)+ _ = try await fixture.repository.confirmImport(plan: plan)+ let first = try await fixture.repository.work(id: BackupV16Fixtures.minimalWorkID)+ #expect(first.catchUp.latest == 40)+ #expect(first.modifiedAt == BackupV16Fixtures.created.addingTimeInterval(100))+ saves.arm()+ _ = try await fixture.repository.confirmImport(plan: plan)+ let second = try await fixture.repository.work(id: BackupV16Fixtures.minimalWorkID)+ #expect(second.catchUp == first.catchUp)+ #expect(second.modifiedAt == first.modifiedAt)+ #expect(saves.saves > 0)+ #expect(saves.dirtySaves.allSatisfy { !$0 })+ }++ @Test("An older progress record never replaces local progress; an equal-time tie is deterministic")+ func olderAndEqualProgress() async throws {+ let fixture = try await M5Fixture()+ let recent = Self.payload(latest: 60, confirmation: Self.confirmedAt.addingTimeInterval(10))+ _ = try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(recent))+ let earlier = Self.payload(latest: 30, confirmation: Self.confirmedAt,+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(50))+ _ = try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(earlier))+ #expect(try await fixture.repository.work(id: BackupV16Fixtures.minimalWorkID).catchUp.latest == 60)++ let tied = Self.payload(latest: 75, confirmation: Self.confirmedAt.addingTimeInterval(10))+ _ = try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(tied))+ #expect(try await fixture.repository.work(id: BackupV16Fixtures.minimalWorkID).catchUp.latest == 75)+ }++ @Test("A torn authored group still folds the archive's newer progress")+ func tornGroupStillFolds() async throws {+ let fixture = try await M5Fixture()+ _ = try await fixture.repository.confirmImport(+ plan: BackupV16Fixtures.plan(Self.payload(latest: 30)))+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding torn work") { context in+ let other = Work.create(+ in: context, id: BackupV16Fixtures.minimalWorkID,+ title: "Different authored title", hostname: BackupV16Fixtures.minimalHost,+ timestamp: BackupV16Fixtures.created)+ other.genericNotes = "different authored notes"+ try context.save()+ }+ let newer = Self.payload(latest: 80, confirmation: Self.confirmedAt.addingTimeInterval(30),+ modifiedAt: BackupV16Fixtures.created.addingTimeInterval(100))+ _ = try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(newer))+ let values = try await fixture.repository.withLockedContext(+ mode: .shared, operation: "reading torn progress") { context in+ try context.fetch(FetchDescriptor<Work>())+ .filter { $0.id == BackupV16Fixtures.minimalWorkID }+ .map(\.catchUpRecord)+ }+ #expect(values.count == 2)+ #expect(values.allSatisfy { $0.latest == 80 })+ }++ @Test("An undecodable progress blob refuses export and names its work")+ func corruptBlobRefusesExport() async throws {+ let fixture = try await M5Fixture()+ _ = try await fixture.repository.confirmImport(plan: BackupV16Fixtures.plan(Self.payload()))+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding corrupt progress") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>())+ .first { $0.id == BackupV16Fixtures.minimalWorkID })+ work.catchUpConfirmationData = Data("broken".utf8)+ try context.save()+ }+ do {+ _ = try await fixture.repository.backupV16Snapshot()+ Issue.record("expected an export refusal")+ } catch let error as BackupV16ExportError {+ guard case .unrepresentableValue(let record, let field, _) = error else {+ Issue.record("expected named unrepresentable value, got \(error)")+ return+ }+ #expect(record.contains(BackupV16Fixtures.minimalWorkID.uuidString))+ #expect(field == "catch-up confirmation")+ }+ }++ @Test("A 15/16 envelope refuses before import can open a write path")+ func previousVersionRefuses() throws {+ let old = BackupV16Fixtures.retiredGenerationDocument()+ let error = #expect(throws: BackupImportError.self) { try BackupImporter.plan(from: old) }+ guard case .unsupportedFormat(let reason) = error else {+ Issue.record("expected unsupported format")+ return+ }+ #expect(reason.contains("format 15/schema 16"))+ #expect(reason.contains("(16/17)"))+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpConvergenceTests.swiftnew file mode 100644index 00000000..ec967b93--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpConvergenceTests.swift@@ -0,0 +1,136 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Catch-up convergence", .serialized)+struct CatchUpConvergenceTests {+ private static func record(_ latest: Int, at moment: Int64, override: LastChapterOverride? = nil) -> CatchUpRecord {+ CatchUpRecord(+ confirmation: CatchUpConfirmation(+ latest: latest, confirmedAtMilliseconds: moment,+ countsUp: latest.isMultiple(of: 2), isEstimate: false),+ override: override)+ }++ @Test("Progress-only divergence converges and a second pass writes nothing")+ func sameUUIDConverges() throws {+ let store = try DuplicateStore()+ let site = store.addSite()+ let id = DuplicateStore.rankedID(1)+ let older = store.addWork(id: id, title: "Serial", createdAt: 0, site: site)+ let newer = store.addWork(id: id, title: "Serial", createdAt: 1, site: site)+ let elected = Self.record(40, at: 2_000, override: .cleared(atMilliseconds: 3_000))+ CatchUpWriter.apply(Self.record(30, at: 1_000), to: [older])+ CatchUpWriter.apply(elected, to: [newer])+ try store.commit()++ _ = try store.reconcile()+ let rows = try store.read { try $0.fetch(FetchDescriptor<Work>()) }+ #expect(rows.count == 2)+ #expect(rows.allSatisfy { $0.catchUpRecord == elected })+ #expect(try store.reconcile().wroteNothing)+ }++ @Test("Deletion re-elects progress that arrived after the write phase")+ func deletionCarriesLateConfirmation() throws {+ let store = try DuplicateStore()+ let site = store.addSite()+ let survivorID = DuplicateStore.rankedID(1)+ let loserID = DuplicateStore.rankedID(2)+ let survivor = store.addWork(+ id: survivorID, title: "Serial", urlIdentity: "serial", createdAt: 0, site: site)+ let loser = store.addWork(+ id: loserID, title: "Serial", urlIdentity: "serial", createdAt: 1, site: site)+ CatchUpWriter.apply(Self.record(30, at: 1_000), to: [survivor])+ CatchUpWriter.apply(Self.record(40, at: 2_000), to: [loser])+ try store.commit()+ _ = try store.reconcile()++ let arrival = Self.record(50, at: 3_000)+ let second = try store.reconcile(afterDerivation: { context in+ let rows = try context.fetch(FetchDescriptor<Work>())+ CatchUpWriter.apply(arrival, to: rows.filter { $0.id == loserID })+ })+ #expect(second.collapsedMembers == 1)+ let remaining = try store.read { try $0.fetch(FetchDescriptor<Work>()) }+ #expect(remaining.count == 1)+ #expect(remaining.first?.id == survivorID)+ #expect(remaining.first?.catchUpRecord == arrival)+ }++ @Test("Deletion recheck elects a survivor arrival and deterministic equal-time values")+ func deletionRecheckUsesBothSides() {+ let survivor = Work(id: UUID(), displayTitle: "Survivor", timestamp: DuplicateStore.epoch)+ let loser = Work(id: UUID(), displayTitle: "Loser", timestamp: DuplicateStore.epoch)+ let tiedSurvivor = Self.record(40, at: 2_000)+ let tiedLoser = Self.record(50, at: 2_000)+ CatchUpWriter.apply(tiedSurvivor, to: [survivor])+ CatchUpWriter.apply(tiedLoser, to: [loser])+ DuplicateReconciler.carryCatchUp(from: [loser], to: [survivor])+ #expect(survivor.catchUpRecord == tiedLoser)++ let laterSurvivor = Self.record(60, at: 3_000)+ CatchUpWriter.apply(laterSurvivor, to: [survivor])+ DuplicateReconciler.carryCatchUp(from: [loser], to: [survivor])+ #expect(survivor.catchUpRecord == laterSurvivor)+ }++ @Test("Reader resolution keeps elected progress regardless of chosen authored variant")+ func resolutionKeepsProgress() async throws {+ let fixture = try await M5Fixture()+ let first = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Serial", hostname: "dup.example"))+ let second = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Serial", hostname: "dup.example"))+ let elected = Self.record(52, at: 3_000)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding resolution") { context in+ let rows = try context.fetch(FetchDescriptor<Work>())+ for row in rows {+ row.lastParsedTitle = "Serial"+ row.titleProvenance = .parsed+ row.genericNotes = row.id == first.id ? "first note" : "second note"+ CatchUpWriter.apply(row.id == first.id ? elected : Self.record(40, at: 2_000), to: [row])+ }+ try context.save()+ }+ let setKey = try await fixture.repository.withLockedContext(+ mode: .shared, operation: "scanning resolution") { context in+ try #require(DuplicateScan.run(context: context).workSets.first?.key)+ }+ let contract = try await fixture.repository.projectDuplicateResolution(setKey: setKey)+ let outcome = try await fixture.repository.commitDuplicateResolution(+ contract, choosing: try #require(contract.variantIDs.last))+ guard case .committed(let survivorID) = outcome else {+ Issue.record("expected a committed resolution, got \(outcome)")+ return+ }+ #expect(survivorID == first.id || survivorID == second.id)+ #expect(try await fixture.repository.work(id: survivorID).catchUp == elected)+ }++ @Test("Merge carries elected progress from source to target")+ func mergeKeepsProgress() async throws {+ let fixture = try await M5Fixture()+ let source = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Source", hostname: "merge.example"))+ let target = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Target", hostname: "merge.example"))+ let elected = Self.record(75, at: 3_000, override: .value(50, atMilliseconds: 4_000))+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding merge") { context in+ let rows = try context.fetch(FetchDescriptor<Work>())+ for row in rows {+ CatchUpWriter.apply(row.id == source.id ? elected : Self.record(60, at: 2_000), to: [row])+ }+ try context.save()+ }+ let contract = try await fixture.repository.projectMerge(+ sourceWorkID: source.id, targetWorkID: target.id)+ guard case .committed = try await fixture.repository.commitMerge(contract) else {+ Issue.record("expected a committed merge")+ return+ }+ #expect(try await fixture.repository.work(id: target.id).catchUp == elected)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpProgressTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpProgressTests.swiftnew file mode 100644index 00000000..a8bb4b2a--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpProgressTests.swift@@ -0,0 +1,145 @@+import Foundation+import Testing++@testable import AsterismCore++@Suite("Catch-up progress")+struct CatchUpProgressTests {+ private func calendar(_ zone: String = "UTC") -> Calendar {+ var result = Calendar(identifier: .gregorian)+ result.timeZone = TimeZone(identifier: zone)!+ return result+ }++ private func instant(_ year: Int, _ month: Int, _ day: Int, _ hour: Int = 12, calendar: Calendar) -> Date {+ calendar.date(from: DateComponents(year: year, month: month, day: day, hour: hour))!+ }++ private func record(_ latest: Int?, at date: Date, countsUp: Bool = true, estimate: Bool = false,+ override: LastChapterOverride? = nil) -> CatchUpRecord {+ CatchUpRecord(+ confirmation: .init(latest: latest, confirmedAtMilliseconds: MillisecondInstant.milliseconds(date),+ countsUp: countsUp, isEstimate: estimate), override: override)+ }++ private func progress(_ record: CatchUpRecord, _ notes: [NumberedNote], on date: Date,+ days: [ReleaseDay] = [.monday], status: WorkStatus = .ongoing,+ calendar: Calendar) -> CatchUpProgress {+ CatchUpProgress.build(record: record, notes: notes, releaseDays: days,+ workStatus: status, day: CivilDay(date, calendar: calendar), calendar: calendar)+ }++ @Test("Whole chapter numbers reject parts and site identifiers")+ func wholeChapter() {+ #expect(ChapterNumber.whole(chapterSequence: "42", chapterTitle: nil) == 42)+ #expect(ChapterNumber.whole(chapterSequence: "5.07", chapterTitle: nil) == nil)+ #expect(ChapterNumber.whole(chapterSequence: "10000", chapterTitle: nil) == nil)+ #expect(ChapterNumber.whole(chapterSequence: "10000", chapterTitle: "Chapter 7") == 7)+ }++ @Test("Numbered notes keep first capture and source title")+ func numberedNotes() {+ let cal = calendar()+ let first = instant(2026, 3, 2, calendar: cal)+ let shared = instant(2026, 3, 9, calendar: cal)+ let entry = EntrySnapshot(+ id: UUID(), captureTitle: "Captured title", captureTitleSource: .host,+ rawURLString: "https://example.test/42", canonicalURLString: nil,+ hostname: "example.test", entryIdentityKey: "42", identityKeyVersion: 1,+ chapterTitle: "Chapter 42", chapterTitleProvenance: .absent,+ note: "", rating: nil, firstCapturedAt: first, lastSharedAt: shared,+ modifiedAt: shared, workID: nil, workAssignmentProvenance: .absent,+ intentionallyUnattached: false)+ #expect(NumberedNote.from([entry]) == [.init(number: 42, firstCapturedAt: first, title: "Chapter 42")])+ }++ @Test("Unknown, exact, estimated and caught-up states")+ func states() {+ let cal = calendar()+ let monday = instant(2026, 3, 2, calendar: cal)+ let tuesday = instant(2026, 3, 3, calendar: cal)+ let note = NumberedNote(number: 40, firstCapturedAt: monday, title: "Chapter 40")+ #expect(progress(.pristine, [note], on: tuesday, calendar: cal).state == .unknown)+ #expect(progress(record(42, at: monday), [], on: tuesday, calendar: cal).state == .unknown)+ #expect(progress(record(42, at: monday), [note], on: tuesday, calendar: cal).state == .exact)+ #expect(progress(record(40, at: monday), [note], on: tuesday, calendar: cal).state == .caughtUp)+ #expect(progress(record(42, at: monday, estimate: true), [note], on: tuesday, calendar: cal).state == .estimated)+ }++ @Test("Override, clear and newer notes choose the read chapter and earliest candidate")+ func readChapter() {+ let cal = calendar()+ let early = instant(2026, 3, 1, calendar: cal)+ let set = instant(2026, 3, 2, calendar: cal)+ let later = instant(2026, 3, 3, calendar: cal)+ let notes = [+ NumberedNote(number: 90, firstCapturedAt: early, title: "Old 90"),+ NumberedNote(number: 45, firstCapturedAt: later, title: "New 45"),+ NumberedNote(number: 45, firstCapturedAt: later.addingTimeInterval(100), title: "Later 45"),+ ]+ let value = record(50, at: set, override: .value(40, atMilliseconds: MillisecondInstant.milliseconds(set)))+ let result = progress(value, notes, on: later, calendar: cal)+ #expect(result.lastRead == 45)+ #expect(result.lastReadSource == .note("New 45"))+ #expect(result.readDay == CivilDay(later, calendar: cal))+ let cleared = record(50, at: set, override: .cleared(atMilliseconds: MillisecondInstant.milliseconds(set)))+ #expect(progress(cleared, notes, on: later, calendar: cal).lastRead == 90)+ let tied = record(50, at: set, override: .value(45, atMilliseconds: MillisecondInstant.milliseconds(set)))+ #expect(progress(tied, notes, on: later, calendar: cal).lastReadSource == .override)+ }++ @Test("The read bound advances after a note passes the confirmation")+ func readBoundDoesNotStall() {+ let cal = calendar()+ let monday = instant(2026, 3, 2, calendar: cal)+ let wednesday = instant(2026, 3, 4, calendar: cal)+ let friday = instant(2026, 3, 6, calendar: cal)+ let note = NumberedNote(number: 45, firstCapturedAt: wednesday, title: "45")+ let result = progress(record(40, at: monday), [note], on: friday, days: [.friday], calendar: cal)+ #expect(result.effectiveLatest == 46)+ #expect(result.behind == 1)+ let oldNote = NumberedNote(number: 45, firstCapturedAt: instant(2026, 2, 1, calendar: cal), title: "45")+ let pinned = progress(record(45, at: monday), [oldNote], on: monday, days: ReleaseDay.allCases, calendar: cal)+ #expect(pinned.effectiveLatest == 45)+ }++ @Test("Counting respects the settings, clock skew, cap and DST civil days")+ func counting() {+ for zone in ["Europe/Amsterdam", "Australia/Sydney"] {+ let cal = calendar(zone)+ let start = zone == "Europe/Amsterdam"+ ? instant(2026, 3, 25, calendar: cal) : instant(2026, 4, 1, calendar: cal)+ let end = zone == "Europe/Amsterdam"+ ? instant(2026, 4, 1, calendar: cal) : instant(2026, 4, 8, calendar: cal)+ let note = NumberedNote(number: 40, firstCapturedAt: start, title: "40")+ #expect(progress(record(42, at: start), [note], on: end,+ days: [.sunday], calendar: cal).effectiveLatest == 43)+ #expect(progress(record(42, at: start, countsUp: false), [note], on: end,+ days: [.sunday], calendar: cal).effectiveLatest == 42)+ #expect(progress(record(42, at: start), [note], on: end,+ days: [.sunday], status: .hiatus, calendar: cal).effectiveLatest == 42)+ #expect(progress(record(42, at: start), [note], on: end,+ days: [], calendar: cal).effectiveLatest == 42)+ #expect(progress(record(42, at: end), [note], on: start,+ days: [.sunday], calendar: cal).effectiveLatest == 42)+ #expect(progress(record(9_999, at: start), [note], on: end,+ days: [.sunday], calendar: cal).effectiveLatest == 9_999)+ }+ }++ @Test("Rebase needs a latest and stores today's estimate with the old override")+ func rebase() {+ let cal = calendar()+ let day = instant(2026, 3, 3, calendar: cal)+ #expect(CatchUpProgress.rebased(record: .pristine, notes: [], releaseDays: [.monday],+ workStatus: .ongoing, now: day, calendar: cal) == nil)+ let old = record(40, at: instant(2026, 3, 2, calendar: cal),+ override: .cleared(atMilliseconds: 12))+ let result = CatchUpProgress.rebased(record: old, notes: [], releaseDays: [.monday],+ workStatus: .ongoing, now: day, calendar: cal)+ #expect(result?.latest == 40)+ #expect(result?.confirmation?.isEstimate == true)+ #expect(result?.confirmation?.confirmedAtMilliseconds == MillisecondInstant.milliseconds(day))+ #expect(result?.override == old.override)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swiftnew file mode 100644index 00000000..d2b7b965--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift@@ -0,0 +1,127 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Catch-up rebase in Work edits", .serialized)+struct CatchUpRebaseRepositoryTests {+ private func calendar() -> Calendar {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(identifier: "UTC")!+ return calendar+ }++ private func seeded(+ latest: Int? = 40, status: WorkStatus = .ongoing,+ days: [ReleaseDay] = [.monday]+ ) throws -> (WriteFixture, UUID) {+ let fixture = try WriteFixture()+ let id = UUID()+ try fixture.seed { store in+ store.insertSite(hostname: "dup.example")+ let work = store.insertWork(+ id: id, hostname: "dup.example", title: "A Serial", offset: 0)+ work.workStatus = status+ work.releaseDays = days+ if let latest {+ work.catchUpConfirmationData = try JSONBlob.encode(CatchUpConfirmation(+ latest: latest,+ confirmedAtMilliseconds: MillisecondInstant.milliseconds(+ WriteFixture.epoch.addingTimeInterval(-7 * 86_400)),+ countsUp: true, isEstimate: false))+ }+ let note = store.insertEntry(+ hostname: "dup.example", title: "Chapter 45", offset: -3 * 86_400)+ note.chapterTitle = "Chapter 45"+ note.work = work+ }+ return (fixture, id)+ }++ private func draft(+ _ work: WorkSnapshot, status: WorkStatus? = nil,+ days: [ReleaseDay]? = nil, seriesID: UUID? = nil+ ) -> WorkMetadataDraft {+ WorkMetadataDraft(+ displayTitle: work.displayTitle, typeAssignment: work.typeDisplay.assignment,+ genreTags: work.genreTags, genericNotes: work.genericNotes,+ workStatus: status ?? work.workStatus, readingStatus: work.readingStatus,+ verdict: work.verdict, releaseDays: days ?? work.releaseDays,+ membership: seriesID.map { SeriesMembership(seriesID: $0, position: 1) },+ thumbnail: .keep)+ }++ @Test("Status crossing ongoing rebases under the old schedule and note evidence")+ func statusCrossing() async throws {+ for (before, after) in [+ (WorkStatus.ongoing, WorkStatus.hiatus),+ (WorkStatus.hiatus, WorkStatus.ongoing),+ ] {+ let (fixture, id) = try seeded(status: before)+ let repository = try await fixture.openForApp()+ let work = try await repository.work(id: id)+ let expected = CatchUpProgress.build(+ work: work, day: CivilDay(WriteFixture.epoch, calendar: calendar()),+ calendar: calendar()).effectiveLatest+ let outcome = try await repository.updateWork(+ id: id, basis: WorkEditBasis(work: work),+ draft: draft(work, status: after), calendar: calendar())+ #expect(outcome == .committed)+ let updated = try #require(fixture.workRows(id: id).first?.catchUpRecord.confirmation)+ #expect(updated.latest == expected)+ #expect(updated.confirmedAtMilliseconds == MillisecondInstant.milliseconds(WriteFixture.epoch))+ #expect(updated.isEstimate)+ #expect(updated.countsUp)+ }+ }++ @Test("Canonical schedule changes rebase; raw-only spelling changes and absent latest do not")+ func scheduleTrigger() async throws {+ let (fixture, id) = try seeded()+ let repository = try await fixture.openForApp()+ let before = try await repository.work(id: id)+ let outcome = try await repository.updateWork(+ id: id, basis: WorkEditBasis(work: before),+ draft: draft(before, days: [.monday, .thursday]), calendar: calendar())+ #expect(outcome == .committed)+ #expect(try fixture.workRows(id: id).first?.catchUpRecord.confirmation?.isEstimate == true)++ let (rawFixture, rawID) = try seeded()+ try rawFixture.seedAdditional { store in+ let rows = try store.context.fetch(FetchDescriptor<Work>())+ rows.first { $0.id == rawID }?.releaseDaysRaw = ["monday", "funday"]+ }+ let rawRepository = try await rawFixture.openForApp()+ let rawWork = try await rawRepository.work(id: rawID)+ let rawOutcome = try await rawRepository.updateWork(+ id: rawID, basis: WorkEditBasis(work: rawWork),+ draft: draft(rawWork, days: [.monday]), calendar: calendar())+ #expect(rawOutcome == .committed)+ #expect(try rawFixture.workRows(id: rawID).first?.catchUpRecord.confirmation?.isEstimate == false)++ let (emptyFixture, emptyID) = try seeded(latest: nil)+ let emptyRepository = try await emptyFixture.openForApp()+ let emptyWork = try await emptyRepository.work(id: emptyID)+ _ = try await emptyRepository.updateWork(+ id: emptyID, basis: WorkEditBasis(work: emptyWork),+ draft: draft(emptyWork, status: .hiatus), calendar: calendar())+ #expect(try emptyFixture.workRows(id: emptyID).first?.catchUpRecord == .pristine)+ }++ @Test("A refused metadata edit keeps the progress record unchanged")+ func refusalDoesNotRebase() async throws {+ let (fixture, id) = try seeded()+ let repository = try await fixture.openForApp()+ let work = try await repository.work(id: id)+ let before = try #require(fixture.workRows(id: id).first?.catchUpRecord)+ let refused = try await repository.updateWork(+ id: id, basis: WorkEditBasis(work: work),+ draft: draft(work, status: .hiatus, seriesID: UUID()), calendar: calendar())+ guard case .conflict(.seriesMissing) = refused else {+ Issue.record("missing chosen series must refuse the edit")+ return+ }+ #expect(try fixture.workRows(id: id).first?.catchUpRecord == before)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRecordTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRecordTests.swiftnew file mode 100644index 00000000..3e1ccbee--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRecordTests.swift@@ -0,0 +1,76 @@+import Foundation+import Testing++@testable import AsterismCore++@Suite("Catch-up record")+struct CatchUpRecordTests {+ @Test("Millisecond conversion follows quantize at floating-point edges")+ func millisecondsFollowQuantize() {+ for seconds in [+ 0.0, 0.001, 1_700_000_000.123, 1_700_000_000.123_4,+ -0.001, -1_700_000_000.123, -1_700_000_000.123_4,+ ] {+ let date = Date(timeIntervalSince1970: seconds)+ let millis = MillisecondInstant.milliseconds(date)+ #expect(MillisecondInstant.date(fromMilliseconds: millis) == MillisecondInstant.quantize(date))+ #expect(MillisecondInstant.milliseconds(MillisecondInstant.date(fromMilliseconds: millis)) == millis)+ }+ #expect(MillisecondInstant.milliseconds(Date(timeIntervalSince1970: 0.000_4)) == 0)+ #expect(MillisecondInstant.milliseconds(Date(timeIntervalSince1970: 0.001_4)) == 1)+ #expect(MillisecondInstant.milliseconds(Date(timeIntervalSince1970: -0.000_4)) == -1)+ #expect(MillisecondInstant.milliseconds(Date(timeIntervalSince1970: -0.001_4)) == -2)+ }++ @Test("JSON blobs round-trip and override wire keys stay fixed")+ func codec() throws {+ let confirmation = CatchUpConfirmation(+ latest: 42, confirmedAtMilliseconds: 1_700_000_000_123,+ countsUp: false, isEstimate: true)+ let override = LastChapterOverride.value(40, atMilliseconds: 1_700_000_000_124)+ #expect(try JSONBlob.decode(CatchUpConfirmation.self, from: JSONBlob.encode(confirmation)) == confirmation)+ #expect(try JSONBlob.decode(LastChapterOverride.self, from: JSONBlob.encode(override)) == override)+ #expect(String(data: try JSONBlob.encode(override), encoding: .utf8) ==+ #"{"atMilliseconds":1700000000124,"kind":"value","number":40}"#)+ #expect(String(data: try JSONBlob.encode(LastChapterOverride.cleared(atMilliseconds: 7)), encoding: .utf8) ==+ #"{"atMilliseconds":7,"kind":"cleared"}"#)+ #expect((try? JSONBlob.decode(LastChapterOverride.self, from: Data(#"{"kind":"future","atMilliseconds":7}"#.utf8))) == nil)+ #expect((try? JSONBlob.decode(LastChapterOverride.self, from: Data("garbage".utf8))) == nil)+ }++ @Test("Fold is order independent and idempotent")+ func foldLaws() {+ let records = [+ CatchUpRecord.pristine,+ CatchUpRecord(confirmation: .init(latest: 12, confirmedAtMilliseconds: 5, countsUp: true, isEstimate: false), override: .value(9, atMilliseconds: 8)),+ CatchUpRecord(confirmation: .init(latest: nil, confirmedAtMilliseconds: 6, countsUp: false, isEstimate: true), override: .cleared(atMilliseconds: 9)),+ CatchUpRecord(confirmation: .init(latest: 20, confirmedAtMilliseconds: 6, countsUp: true, isEstimate: false), override: .value(7, atMilliseconds: 9)),+ ]+ for count in 2...4 {+ let chosen = Array(records.prefix(count))+ let expected = CatchUpFold.elect(chosen)+ for permutation in permutations(chosen) {+ #expect(CatchUpFold.elect(permutation) == expected)+ }+ #expect(CatchUpFold.elect([expected]) == expected)+ }+ let elected = CatchUpFold.elect(records)+ #expect(elected.confirmation?.latest == 20)+ #expect(elected.override == .value(7, atMilliseconds: 9))+ #expect(CatchUpFold.elect([records[1], records[2]]).override == .cleared(atMilliseconds: 9))+ let tiedTime = CatchUpConfirmation(latest: 20, confirmedAtMilliseconds: 6, countsUp: false, isEstimate: false)+ #expect(CatchUpFold.elect([records[3], .init(confirmation: tiedTime, override: nil)]).confirmation == records[3].confirmation)+ let tiedCount = CatchUpConfirmation(latest: 20, confirmedAtMilliseconds: 6, countsUp: true, isEstimate: true)+ #expect(CatchUpFold.elect([records[3], .init(confirmation: tiedCount, override: nil)]).confirmation == tiedCount)+ #expect(CatchUpFold.elect([.init(confirmation: nil, override: .value(8, atMilliseconds: 9)), records[3]]).override == .value(8, atMilliseconds: 9))+ }++ private func permutations<T>(_ values: [T]) -> [[T]] {+ guard !values.isEmpty else { return [[]] }+ return values.indices.flatMap { index in+ var remaining = values+ let first = remaining.remove(at: index)+ return permutations(remaining).map { [first] + $0 }+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRepositoryTests.swiftnew file mode 100644index 00000000..e269b870--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRepositoryTests.swift@@ -0,0 +1,199 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Catch-up repository writes", .serialized)+struct CatchUpRepositoryTests {+ private func calendar() -> Calendar {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(identifier: "UTC")!+ return calendar+ }++ private func record(_ latest: Int = 42, moment: Int64 = 1_799_000_000_000) -> CatchUpRecord {+ CatchUpRecord(+ confirmation: CatchUpConfirmation(+ latest: latest, confirmedAtMilliseconds: moment,+ countsUp: true, isEstimate: true),+ override: nil)+ }++ private func seeded(+ copies: Int = 1, torn: Bool = false, withNote: Bool = false+ ) throws -> (WriteFixture, UUID) {+ let fixture = try WriteFixture()+ let id = UUID()+ let initial = record()+ try fixture.seed { store in+ store.insertSite(hostname: "dup.example")+ for index in 0..<copies {+ let work = store.insertWork(+ id: id, hostname: "dup.example",+ title: torn && index == 1 ? "A different title" : "A Serial",+ offset: TimeInterval(index * 30))+ if torn { work.genericNotes = index == 0 ? "first reader note" : "second reader note" }+ work.catchUpConfirmationData = try JSONBlob.encode(initial.confirmation)+ work.releaseDays = [.monday]+ if withNote && index == 0 {+ let entry = store.insertEntry(+ hostname: "dup.example", title: "Chapter 40", offset: -86_400)+ entry.chapterTitle = "Chapter 40"+ entry.work = work+ }+ }+ }+ return (fixture, id)+ }++ @Test("Sheet state reads the current record, selected day, and note source")+ func sheetStateIsFresh() async throws {+ let (fixture, id) = try seeded(withNote: true)+ let repository = try await fixture.openForApp()+ let day = CivilDay(WriteFixture.epoch, calendar: calendar())+ let state = try await repository.catchUpSheetState(+ workID: id, day: day, calendar: calendar())+ #expect(state.record == record())+ #expect(state.work.id == id)+ #expect(state.progress.lastRead == 40)+ #expect(state.progress.lastReadSource == .note("Chapter 40"))+ #expect(state.progress == CatchUpProgress.build(work: state.work, day: day, calendar: calendar()))+ }++ @Test("Save stamps one complete confirmation on every copy and leaves an unchanged override")+ func saveFansOut() async throws {+ let (fixture, id) = try seeded(copies: 2)+ let repository = try await fixture.openForApp()+ let outcome = try await repository.commitCatchUpProgress(+ id: id, basis: record(),+ draft: CatchUpDraft(latest: 45, countsUp: false, override: .unchanged))+ #expect(outcome == .committed)+ let rows = try fixture.workRows(id: id)+ #expect(rows.count == 2)+ #expect(rows.allSatisfy {+ $0.catchUpRecord.confirmation == CatchUpConfirmation(+ latest: 45,+ confirmedAtMilliseconds: MillisecondInstant.milliseconds(WriteFixture.epoch),+ countsUp: false, isEstimate: false)+ && $0.catchUpRecord.override == nil+ && $0.modifiedAt == WriteFixture.epoch+ })+ }++ @Test("An edited override can be set and later cleared with its moment")+ func overrideEdits() async throws {+ let (fixture, id) = try seeded()+ let repository = try await fixture.openForApp()+ let set = try await repository.commitCatchUpProgress(+ id: id, basis: record(),+ draft: CatchUpDraft(latest: 42, countsUp: true, override: .set(40)))+ #expect(set == .committed)+ let basis = try #require(fixture.workRows(id: id).first?.catchUpRecord)+ #expect(basis.override == .value(40, atMilliseconds: MillisecondInstant.milliseconds(WriteFixture.epoch)))+ let clear = try await repository.commitCatchUpProgress(+ id: id, basis: basis,+ draft: CatchUpDraft(latest: nil, countsUp: true, override: .clear))+ #expect(clear == .committed)+ let updated = try #require(fixture.workRows(id: id).first?.catchUpRecord)+ #expect(updated.latest == nil)+ #expect(updated.override == .cleared(atMilliseconds: MillisecondInstant.milliseconds(WriteFixture.epoch)))+ }++ @Test("Changed progress, torn copies, and invalid numbers refuse without writing")+ func refusalCases() async throws {+ let (fixture, id) = try seeded(copies: 2)+ let repository = try await fixture.openForApp()+ let changed = try await repository.commitCatchUpProgress(+ id: id, basis: .pristine,+ draft: CatchUpDraft(latest: 43, countsUp: true, override: .unchanged))+ #expect(changed == .conflict(.recordChanged(recordID: id)))+ #expect(try fixture.workRows(id: id).allSatisfy { $0.catchUpRecord == record() })+ for number in [-1, 10_000] {+ await #expect(throws: LibraryRepositoryError.self) {+ try await repository.commitCatchUpProgress(+ id: id, basis: record(),+ draft: CatchUpDraft(latest: number, countsUp: true, override: .unchanged))+ }+ await #expect(throws: LibraryRepositoryError.self) {+ try await repository.commitCatchUpProgress(+ id: id, basis: record(),+ draft: CatchUpDraft(latest: 43, countsUp: true, override: .set(number)))+ }+ }+ let (tornFixture, tornID) = try seeded(copies: 2, torn: true)+ let tornRepository = try await tornFixture.openForApp()+ let torn = try await tornRepository.commitCatchUpProgress(+ id: tornID, basis: record(),+ draft: CatchUpDraft(latest: 43, countsUp: true, override: .unchanged))+ guard case .conflict(.torn) = torn else {+ Issue.record("torn Work must refuse a progress save")+ return+ }+ #expect(try tornFixture.workRows(id: tornID).allSatisfy { $0.catchUpRecord == record() })+ }++ @Test("Reading-status action changes only the expected group's status and stamp")+ func readingStatusAction() async throws {+ let (fixture, id) = try seeded(copies: 2)+ let repository = try await fixture.openForApp()+ let stale = try await repository.setReadingStatus(+ id: id, expected: .catchingUp, to: .finished)+ #expect(stale == .conflict(.recordChanged(recordID: id)))+ let committed = try await repository.setReadingStatus(+ id: id, expected: .reading, to: .catchingUp)+ #expect(committed == .committed)+ #expect(try fixture.workRows(id: id).allSatisfy {+ $0.readingStatus == .catchingUp && $0.catchUpRecord == record()+ && $0.modifiedAt == WriteFixture.epoch+ })+ let (tornFixture, tornID) = try seeded(copies: 2, torn: true)+ let tornRepository = try await tornFixture.openForApp()+ let torn = try await tornRepository.setReadingStatus(+ id: tornID, expected: .reading, to: .catchingUp)+ guard case .conflict(.torn) = torn else {+ Issue.record("torn Work must refuse a reading-status action")+ return+ }+ }++ @Test("The presented carrier status decides a split group with a bare sibling")+ func carrierStatusDecides() async throws {+ let fixture = try WriteFixture()+ let id = UUID()+ try fixture.seed { store in+ store.insertSite(hostname: "dup.example")+ let carrier = store.insertWork(+ id: id, hostname: "dup.example", title: "A Serial", offset: 0)+ carrier.readingStatus = .catchingUp+ store.insertWork(id: id, hostname: "dup.example", title: "A Serial", offset: 30)+ }+ let repository = try await fixture.openForApp()+ let stale = try await repository.setReadingStatus(+ id: id, expected: .reading, to: .finished)+ #expect(stale == .conflict(.recordChanged(recordID: id)))+ let changed = try await repository.setReadingStatus(+ id: id, expected: .catchingUp, to: .reading)+ #expect(changed == .committed)+ #expect(try fixture.workRows(id: id).allSatisfy { $0.readingStatus == .reading })+ }++ @Test("A missing or collapsed ID cannot write a different Work")+ func missingIDRefuses() async throws {+ let (fixture, id) = try seeded()+ let repository = try await fixture.openForApp()+ let missing = UUID()+ let collapsed = UUID()+ await repository.recordCollapse(loser: collapsed, survivor: id, type: .work)+ await #expect(throws: LibraryRepositoryError.self) {+ try await repository.commitCatchUpProgress(+ id: missing, basis: record(),+ draft: CatchUpDraft(latest: 50, countsUp: true, override: .unchanged))+ }+ await #expect(throws: LibraryRepositoryError.self) {+ try await repository.setReadingStatus(+ id: collapsed, expected: .reading, to: .catchingUp)+ }+ #expect(try fixture.workRows(id: id).first?.catchUpRecord == record())+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swiftnew file mode 100644index 00000000..378d6846--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift@@ -0,0 +1,41 @@+import Foundation+import Testing++@testable import AsterismCore++@Suite("Catch-up row persistence")+struct CatchUpWriterTests {+ private let first = CatchUpRecord(+ confirmation: CatchUpConfirmation(+ latest: 40, confirmedAtMilliseconds: 1_000, countsUp: true, isEstimate: false),+ override: .value(25, atMilliseconds: 1_100))++ @Test("The writer changes only differing decoded values and a repeat is a no-op")+ func valueGuardedWrite() throws {+ let a = Work(displayTitle: "A", timestamp: .distantPast)+ let b = Work(displayTitle: "B", timestamp: .distantPast)+ b.catchUpConfirmationData = try JSONBlob.encode(first.confirmation)+ b.lastChapterOverrideData = try JSONBlob.encode(first.override)+ let originalConfirmation = b.catchUpConfirmationData+ let originalOverride = b.lastChapterOverrideData++ #expect(CatchUpWriter.apply(first, to: [a, b]))+ #expect(a.catchUpRecord == first)+ #expect(b.catchUpConfirmationData == originalConfirmation)+ #expect(b.lastChapterOverrideData == originalOverride)+ #expect(!CatchUpWriter.apply(first, to: [a, b]))+ }++ @Test("A malformed blob reads as absent while its other field survives")+ func malformedBlobIsTolerated() throws {+ let row = Work(displayTitle: "A", timestamp: .distantPast)+ row.catchUpConfirmationData = Data("broken".utf8)+ row.lastChapterOverrideData = try JSONBlob.encode(first.override)+ #expect(row.catchUpRecord.confirmation == nil)+ #expect(row.catchUpRecord.override == first.override)+ let snapshot = LibraryRepository.snapshot(+ row, entries: [], types: .empty, series: .empty, credits: .empty)+ #expect(snapshot.catchUp.confirmation == nil)+ #expect(snapshot.catchUp.override == first.override)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swiftindex 6b5d2035..3b88593c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift@@ -16,7 +16,7 @@ import Testing /// /// What is left is the two ends: a store on a retired generation is **refused /// before a container converts it**, and an empty store is marked at birth. The-/// refusal case seeds through `V15RecordedStoreFixture` — a store the container+/// refusal case seeds through `V16RecordedStoreFixture` — a store the container /// *would* open — because a store that could not be opened anyway would prove /// nothing about when the refusal happens. @Suite("Certification paths", .serialized)@@ -55,9 +55,9 @@ struct CertificationPathTests { /// the shipped classifier already refused one before any container existed /// (Req 2.9, Decision 1). private func installStoreArrivedAtV15(_ configuration: LibraryConfiguration) throws {- try V15RecordedStoreFixture.install(at: configuration.storeURL)+ try V16RecordedStoreFixture.install(at: configuration.storeURL) #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL)- == ["15.0.0"], "the seed is written by the frozen snapshot, not the live classes")+ == ["16.0.0"], "the seed is written by the frozen snapshot, not the live classes") } // MARK: - The retired generations@@ -78,7 +78,7 @@ struct CertificationPathTests { /// the evidence would take that away. /// /// The 15.0.0 pin only means something alongside the control that follows- /// it: the same store, marked `"15"`, opens and is recorded 16.0.0. That is+ /// it: the same store, marked `"16"`, opens and is recorded 16.0.0. That is /// what makes the pin an ordering claim rather than a store nothing could /// convert. @Test("A store on a retired marker generation is refused before anything converts it",@@ -97,17 +97,17 @@ struct CertificationPathTests { } #expect(try markerContent(cfg) == digit, "a refused open may not rewrite the marker")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["15.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["16.0.0"], "the marker check must decide before ModelContainer.init converts anything") // Control, mirroring the extension-side twin // (`MarkerContractTests.extensionDeclinesBeforeOpeningAContainer`):- // with a `"15"` marker the same store is reached, opened and converted.+ // with a `"16"` marker the same store is reached, opened and converted. // Without it the 15.0.0 assertion above could hold because the store was // unopenable rather than because the marker was read first.- try Data("15\n".utf8).write(to: cfg.readinessMarkerURL, options: .atomic)+ try Data("16\n".utf8).write(to: cfg.readinessMarkerURL, options: .atomic) _ = try await LibraryRepository.openForApp(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["16.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["17.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) == "16",+ #expect(try markerContent(cfg) == "17", "an empty store has nothing to bring forward and is certified at birth (Q26)") withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swiftindex 64ca1d46..eaa82fc9 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift@@ -9,7 +9,7 @@ import SwiftData /// true` before it runs is a save that is about to write something, even if /// what it writes happens to equal what was already there. ///-/// Shared by `EmptyLibraryTests` and `BackupV15ImportTests`, which ask the+/// Shared by `EmptyLibraryTests` and `BackupV16ImportTests`, which ask the /// same question of two fixtures. `InstrumentedSaveStrategy` is the failure /// injector and deliberately not this: it answers "did the save run", never /// "did it have anything to write".
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swiftindex d050b962..5dbc27a9 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swift@@ -296,8 +296,8 @@ struct CharacterConvergenceTests { M5SeedCharacter(id: Self.hanna, name: "Hanna", note: "reckless", workID: Self.workID), ]) - await #expect(throws: BackupV15ExportError.self) {- _ = try await fixture.repository.backupV15Snapshot()+ await #expect(throws: BackupV16ExportError.self) {+ _ = try await fixture.repository.backupV16Snapshot() } withExtendedLifetime(fixture) {} }@@ -379,7 +379,7 @@ struct CharacterCitationRepointingTests { /// The reconciler derives the stamp from the collapsing Entries rather than /// a clock (Q56), so it is routinely *older* than the character it rewrites.- /// `CharacterGroup.modifiedAt` is what `BackupV15Character` carries as its+ /// `CharacterGroup.modifiedAt` is what `BackupV16Character` carries as its /// import value guard, so a backwards stamp would let an archive taken /// before the character's last edit overwrite it. @Test("Repointing never moves a character's modifiedAt backwards")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swiftindex e6219573..a5ec9fd8 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swiftindex 83c62e26..784f7088 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift@@ -249,17 +249,17 @@ struct ConvergedRuleGroupValidationTests { // The premise: the store says this library is fine. #expect(await repository.diagnostics.quarantineMap().isEmpty) - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(payload.titlePatterns.count == 1) #expect(payload.titlePatterns.first?.id == shared) #expect(payload.titlePatterns.first?.siteHostname == payload.sites.first?.hostname) // The reference validator is what refuses a payload holding one rule // UUID twice, so a decode is the assertion that matters here.- let encoded = try BackupV15Codec.encode(+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))- let decoded = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+ let decoded = try BackupV16Codec.decode(encoded) #expect(decoded.payload.titlePatterns.count == 1) } @@ -289,15 +289,15 @@ struct ConvergedRuleGroupValidationTests { // The premise, again: the store says this library is fine. #expect(await repository.diagnostics.quarantineMap().isEmpty) - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(payload.titlePatterns.count == 1) #expect(payload.titlePatterns.first?.isActive == true) #expect(payload.sites.first?.mode == .taught)- let encoded = try BackupV15Codec.encode(+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))- _ = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+ _ = try BackupV16Codec.decode(encoded) } /// The URL-rule counterpart, which is the quieter failure: the archive's@@ -316,7 +316,7 @@ struct ConvergedRuleGroupValidationTests { #expect(await repository.diagnostics.quarantineMap().isEmpty) - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(payload.urlRules.count == 1) #expect(payload.urlRules.first?.isCurrent == true)@@ -337,15 +337,15 @@ struct ConvergedRuleGroupValidationTests { #expect(await repository.diagnostics.quarantineMap().isEmpty) - let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() #expect(payload.urlRules.count == 1) #expect(payload.urlRules.first?.id == shared) #expect(payload.urlRules.first?.isCurrent == true)- let encoded = try BackupV15Codec.encode(+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))- _ = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+ _ = try BackupV16Codec.decode(encoded) } } @@ -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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) let container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.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 e1baea55..64a945c3 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swiftindex 93528f64..e4976f34 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swiftindex 37d1bbfb..2de7a2d9 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swiftindex 925c310c..3c81052a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift@@ -169,9 +169,9 @@ struct CrossSiteDuplicateWorkloadTests { func aDeclinedPairSurvivesTheRoundTrip() async throws { let fixture = try await declineFixture() try await fixture.repository.recordDistinctPairs([WorkPairKey(Self.second, Self.first)])- let archive = try BackupV15Codec.encode(- payload: try await fixture.repository.backupV15Snapshot(),- metadata: BackupV15Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))+ let archive = try BackupV16Codec.encode(+ payload: try await fixture.repository.backupV16Snapshot(),+ metadata: BackupV16Metadata(appBuild: "test", exportedAt: M5Fixture.epoch)) let restored = try await M5Fixture() try await restored.repository.confirmImport(plan: try BackupImporter.plan(from: archive))@@ -378,7 +378,7 @@ struct CrossSiteDuplicateWorkloadTests { displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "reader prose", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) #expect(try await fixture.repository.work(id: Self.first).genericNotes == "reader prose")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swiftindex 91c6689b..200e3eba 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift@@ -549,8 +549,8 @@ struct DuplicatePublicationTests { let toRead = try await source.repository.createWork( NewWorkDraft( displayTitle: "Beware of Chicken", hostname: "example.com", readingStatus: .toRead))- let archive = try BackupV15Codec.encode(- payload: try await source.repository.backupV15Snapshot(),+ let archive = try BackupV16Codec.encode(+ payload: try await source.repository.backupV16Snapshot(), metadata: BackupGoldenLibrary.metadata) let target = try await M5Fixture()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swiftindex 6aa5c3b0..e3bcf519 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.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 0a079d77..77fcac4a 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swiftindex 0ff9afb9..419014da 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift@@ -463,12 +463,12 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture() try await fixture.seedGoldenLibrary() - let before = try await fixture.repository.backupV15Snapshot()+ let before = try await fixture.repository.backupV16Snapshot() let report = try await fixture.repository.emptyLibrary() #expect(report.outcome == .completed) try await fixture.repository.confirmImport(plan: EmptyLibraryFixture.plan(before))- let after = try await fixture.repository.backupV15Snapshot()+ let after = try await fixture.repository.backupV16Snapshot() #expect(after == before) await fixture.tearDown()@@ -492,10 +492,10 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture(saveStrategy: strategy) try await fixture.seedGoldenLibrary() - let archive = try await fixture.repository.backupV15Snapshot()+ let archive = try await fixture.repository.backupV16Snapshot() _ = try await fixture.repository.emptyLibrary() try await fixture.repository.confirmImport(plan: EmptyLibraryFixture.plan(archive))- let restored = try await fixture.repository.backupV15Snapshot()+ let restored = try await fixture.repository.backupV16Snapshot() let stamps = try await fixture.repository.modificationStampsForTesting() strategy.arm()@@ -505,7 +505,7 @@ struct EmptyLibraryTests { #expect( strategy.dirtySaves.allSatisfy { !$0 }, "a second import of an unchanged archive must dirty no save, got \(strategy.dirtySaves)")- #expect(try await fixture.repository.backupV15Snapshot() == restored)+ #expect(try await fixture.repository.backupV16Snapshot() == restored) #expect(try await fixture.repository.modificationStampsForTesting() == stamps) await fixture.tearDown() }@@ -517,7 +517,7 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture() try await fixture.seedGoldenLibrary() - let archive = try await fixture.repository.backupV15Snapshot()+ let archive = try await fixture.repository.backupV16Snapshot() let late = try await fixture.repository.capture( CaptureDraft( captureTitle: "Chapter 9 - After the export",@@ -563,7 +563,7 @@ struct EmptyLibraryTests { draft: WorkMetadataDraft( displayTitle: "A Work", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .reading, verdict: "",- releaseDays: [], membership: nil, thumbnail: .keep))+ releaseDays: [], membership: nil, thumbnail: .keep), calendar: .current) #expect(try await fixture.repository.work(id: work.id).typeDisplay == .untyped) await fixture.tearDown() }@@ -810,7 +810,7 @@ private final class EmptyLibraryFixture { func seedGoldenLibrary() async throws { try await repository.confirmImport( plan: try BackupImporter.plan(- from: try BackupV15Codec.encode(+ from: try BackupV16Codec.encode( payload: BackupGoldenLibrary.payload, metadata: BackupGoldenLibrary.metadata))) }@@ -859,11 +859,11 @@ private final class EmptyLibraryFixture { /// The plan `confirmImport` takes, straight off a payload the export just /// produced — what a reader restoring their own backup hands it.- static func plan(_ payload: BackupV15Payload) -> BackupImportPlan {+ static func plan(_ payload: BackupV16Payload) -> BackupImportPlan { BackupImportPlan( metadata: BackupImportMetadata(- formatVersion: BackupV15Document.formatVersion,- schemaVersion: BackupV15Document.schemaVersion,+ formatVersion: BackupV16Document.formatVersion,+ schemaVersion: BackupV16Document.schemaVersion, appBuild: "empty-library-test", exportedAt: BackupGoldenLibrary.created, capabilityGate: "multi-site", entryCount: payload.entries.count, workCount: payload.works.count),@@ -884,7 +884,7 @@ extension LibraryRepository { /// Every entity's row count, read through the pass's own phase list. /// /// Circular only in appearance: `ModelContractTests` pins that list against- /// `AsterismSchemaV16.models`, so counting through it is counting the+ /// `AsterismSchemaV17.models`, so counting through it is counting the /// schema's entities — and the alternative, a second hand-written list of /// seventeen fetches, is one more thing to forget at the next bump. fileprivate func emptyLibraryRowCounts() async throws -> [String: Int] {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swiftindex 9cfed227..6fe26700 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swift@@ -207,9 +207,9 @@ struct EnumTolerancePolicyTests { #expect(snapshot.works.contains { $0.id == workID }) do {- _ = try await repository.backupV15Snapshot()+ _ = try await repository.backupV16Snapshot() Issue.record("the export archived an unrepresentable value")- } catch let error as BackupV15ExportError {+ } catch let error as BackupV16ExportError { guard case .unrepresentableValue(let record, let field, let value) = error else { Issue.record("expected .unrepresentableValue, got \(error)") return@@ -246,9 +246,9 @@ struct EnumTolerancePolicyTests { let repository = try await library.openForApp() do {- _ = try await repository.backupV15Snapshot()+ _ = try await repository.backupV16Snapshot() Issue.record("the export archived an unreadable citation blob")- } catch let error as BackupV15ExportError {+ } catch let error as BackupV16ExportError { guard case .unrepresentableValue(_, let refused, _) = error else { Issue.record("expected .unrepresentableValue, got \(error)") return
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swiftindex dfe6266e..0f83ba57 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift@@ -271,7 +271,7 @@ struct FanOutWriteTests { genericNotes: "reader prose", workStatus: .finished, readingStatus: .finished, verdict: " a fine ending ", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) let rows = try library.workRows(id: workID)@@ -316,7 +316,7 @@ struct FanOutWriteTests { displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],- membership: nil, thumbnail: .keep))+ membership: nil, thumbnail: .keep), calendar: .current) #expect(outcome == .committed) let rows = try library.workRows(id: workID)@@ -349,7 +349,7 @@ struct FanOutWriteTests { displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .reading, verdict: " ", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) let updated = try await repository.work(id: workID)@@ -408,7 +408,7 @@ struct FanOutWriteTests { displayTitle: "Renamed", typeAssignment: .none, genreTags: [], genericNotes: "overwrite", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) guard case .conflict(.torn) = outcome else { Issue.record("expected a torn conflict, got \(outcome)")@@ -686,7 +686,7 @@ final class WriteFixture { /// identity key — the upsert shape (Decision 8), so the plan updates rather /// than inserts. func importPlan(entryID: UUID, note: String, modifiedAt: Date) throws -> BackupImportPlan {- let entry = BackupV15Entry(+ let entry = BackupV16Entry( id: entryID, captureTitle: "Chapter", captureTitleSource: .host, rawURL: identityKey, canonicalURL: nil, hostname: "dup.example", entryIdentityKey: identityKey,@@ -695,7 +695,7 @@ final class WriteFixture { note: note, rating: nil, firstCapturedAt: Self.epoch, lastSharedAt: Self.epoch, modifiedAt: modifiedAt, workID: nil, intentionallyUnattached: false, citations: EntryCitations())- let site = BackupV15Site(+ let site = BackupV16Site( hostname: "dup.example", displayName: "Dup", mode: .untaught) let payload = BackupImportPayload( entries: [entry], works: [], sites: [site], titlePatterns: [], urlRules: [])
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swiftindex b07650f3..b3a6a5fe 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swift@@ -29,8 +29,8 @@ import Testing /// extension is greyed out and cannot be selected on the device. The exporter's /// own filenames are `Asterism-backup-v4-<timestamp>.json` for the same reason. ///-/// The archive is produced through the real `BackupV15Exporter` — the same-/// `backupV15Snapshot()` → `BackupV15Codec.encode` → decode-validate → write path+/// The archive is produced through the real `BackupV16Exporter` — the same+/// `backupV16Snapshot()` → `BackupV16Codec.encode` → decode-validate → write path /// the app's Settings export uses — so what lands on disk is byte-for-byte the /// kind of file the app produces, checksum and all. The generator then re-reads /// the written file through `BackupImporter.plan(from:)`, which is the same@@ -96,9 +96,9 @@ struct FixtureArchiveGeneratorTests { // it just produced. It picks its own filename in the staging directory; // the archive is moved to `destination` afterwards. let staging = root.appending(path: "staging", directoryHint: .isDirectory)- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) let result = try await exporter.export(- metadata: BackupV15Metadata(appBuild: "fixture-5k", exportedAt: exportedAt))+ metadata: BackupV16Metadata(appBuild: "fixture-5k", exportedAt: exportedAt)) withExtendedLifetime(container) {} try FileManager.default.createDirectory(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-15-16-golden.json b/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-15-16-golden.jsondeleted file mode 100644index e274f87b..00000000--- a/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-15-16-golden.json+++ /dev/null@@ -1 +0,0 @@-{"appBuild":"golden","backupFormatVersion":15,"capabilityGate":"multi-site","checksum":"55c847921e26c78f991251486f774da60bc85a062bf44a079b2b38aee907d7c9","databaseSchemaVersion":16,"entryCount":4,"exportedAt":"1970-01-12T13:46:40.000Z","payload":{"characters":[{"aliases":["Klar"],"createdAt":"1970-01-12T13:46:40.000Z","facts":[{"nameKey":"grover","quote":"promised to guide them home","source":{"entryID":"22222222-2222-2222-2222-222222222222","kind":"entry"},"statement":"Promised to guide them home."}],"id":"C4A2ACE0-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","name":"Grover","nameKey":"grover","note":"The guide.","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"aliases":[],"createdAt":"1970-01-12T13:46:40.000Z","facts":[],"id":"C4A2ACE0-0000-4000-8000-000000000002","modifiedAt":"1970-01-12T13:46:40.000Z","name":"The Stranger","nameKey":"the stranger","note":""}],"creatorRoles":[{"createdAt":"1970-01-01T00:00:00.000Z","id":"E0000001-0000-4000-8000-000000000001","modifiedAt":"1970-01-01T00:00:00.000Z","name":"author","nameModifiedAt":"1970-01-01T00:00:00.000Z","position":0,"positionModifiedAt":"1970-01-01T00:00:00.000Z","stateModifiedAt":"1970-01-01T00:00:00.000Z","stateRaw":"active"},{"createdAt":"1970-01-01T00:00:00.000Z","id":"E0000002-0000-4000-8000-000000000002","modifiedAt":"1970-01-01T00:00:00.000Z","name":"artist","nameModifiedAt":"1970-01-01T00:00:00.000Z","position":1,"positionModifiedAt":"1970-01-01T00:00:00.000Z","stateModifiedAt":"1970-01-01T00:00:00.000Z","stateRaw":"active"},{"createdAt":"1970-01-01T00:00:00.000Z","id":"E0000003-0000-4000-8000-000000000003","modifiedAt":"1970-01-01T00:00:00.000Z","name":"translator","nameModifiedAt":"1970-01-01T00:00:00.000Z","position":2,"positionModifiedAt":"1970-01-01T00:00:00.000Z","stateModifiedAt":"1970-01-01T00:00:00.000Z","stateRaw":"active"},{"createdAt":"1970-01-12T13:46:40.000Z","id":"E0000004-0000-4000-8000-000000000004","modifiedAt":"1970-01-12T13:46:40.000Z","name":"letterer","nameModifiedAt":"1970-01-12T13:46:40.000Z","position":3,"positionModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"active"},{"createdAt":"1970-01-12T13:46:40.000Z","id":"E0000005-0000-4000-8000-000000000005","modifiedAt":"1970-01-12T13:46:40.000Z","name":"editor","nameModifiedAt":"1970-01-12T13:46:40.000Z","position":4,"positionModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"removed"}],"creators":[{"createdAt":"1970-01-12T13:46:40.000Z","id":"C8EA1080-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","name":"Mori Ayane","nameModifiedAt":"1970-01-12T13:46:40.000Z","notes":"Also draws.","notesModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"active"},{"createdAt":"1970-01-12T13:46:40.000Z","id":"C8EA1080-0000-4000-8000-000000000002","modifiedAt":"1970-01-12T13:46:40.000Z","name":"Studio Lantern","nameModifiedAt":"1970-01-12T13:46:40.000Z","notes":"","notesModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"active"},{"canonicalID":"C8EA1080-0000-4000-8000-000000000001","createdAt":"1970-01-12T13:46:40.000Z","id":"C8EA1080-0000-4000-8000-000000000003","modifiedAt":"1970-01-12T13:46:40.000Z","name":"mori ayane","nameModifiedAt":"1970-01-12T13:46:40.000Z","notes":"","notesModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"merged"}],"credits":[{"createdAt":"1970-01-12T13:46:40.000Z","creatorID":"C8EA1080-0000-4000-8000-000000000001","id":"C8ED1700-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","roleIDs":["E0000001-0000-4000-8000-000000000001","E0000005-0000-4000-8000-000000000005"],"workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"createdAt":"1970-01-12T13:46:40.000Z","creatorID":"C8EA1080-0000-4000-8000-000000000002","id":"C8ED1700-0000-4000-8000-000000000002","modifiedAt":"1970-01-12T13:46:40.000Z","roleIDs":["E0000002-0000-4000-8000-000000000002","E000000F-0000-4000-8000-00000000000F"],"workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2"},{"createdAt":"1970-01-12T13:46:40.000Z","creatorID":"C8EA1080-0000-4000-8000-000000000001","id":"C8ED1700-0000-4000-8000-000000000003","modifiedAt":"1970-01-12T13:46:40.000Z","roleIDs":["E0000001-0000-4000-8000-000000000001"],"workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9"}],"distinctPairs":[{"higherWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","id":"88888888-0000-4000-8000-000000000001","lowerWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2","recordedAt":"1970-01-12T13:46:40.000Z"}],"entries":[{"captureTitle":"TtH • Story • Actual Title","captureTitleSource":"host","chapterSequence":"94","characterExtractionFingerprint":"448c04a700521270a7f5215cd2cfbbe77818591b29899fa94ca100201738f368","citations":{"chapterSequence":{"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD"},"chapterTitle":{"kind":"none"},"identity":{"composed":{"nameTitle":{"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC"},"url":{"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD"}}},"workAssignment":{"pattern":{"_0":{"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC"}}}},"conservativeIdentityKey":"https://golden.example/read?chapter=94&x=1","entryIdentityKey":"v3|h14:golden.example|n12:Actual Title|s2:94","firstCapturedAt":"1970-01-12T13:46:40.000Z","hostname":"golden.example","id":"22222222-2222-2222-2222-222222222222","identityBasis":"urlRule","intentionallyUnattached":false,"lastSharedAt":"1970-01-12T13:46:40.000Z","modifiedAt":"1970-01-12T13:46:40.000Z","note":"Grover promised to guide them home.","rating":"up","rawURL":"https://golden.example/read?chapter=94&x=1","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"captureTitle":"Plain Work","captureTitleSource":"manual","chapterTitle":"A Plain Chapter","citations":{"chapterTitle":{"kind":"manual"},"identity":{"rawURL":{}},"workAssignment":{"manual":{}}},"conservativeIdentityKey":"https://plain.example/read/7","entryIdentityKey":"https://plain.example/read/7","firstCapturedAt":"1970-01-12T13:46:40.000Z","hostname":"plain.example","id":"22222222-2222-2222-2222-222222222223","identityBasis":"conservative","intentionallyUnattached":false,"lastSharedAt":"1970-01-12T13:46:40.000Z","modifiedAt":"1970-01-12T13:46:40.000Z","note":"","rawURL":"https://plain.example/read/7","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2"},{"canonicalURL":"https://trimmed.example/posts/hello","captureTitle":"A Standalone - Trimmed Example","captureTitleSource":"host","citations":{"chapterTitle":{"kind":"none"},"identity":{"rawURL":{}},"workAssignment":{"manual":{}}},"conservativeIdentityKey":"https://trimmed.example/posts/hello?utm_source=share","entryIdentityKey":"https://trimmed.example/posts/hello?utm_source=share","firstCapturedAt":"1970-01-12T13:46:40.000Z","hostname":"trimmed.example","id":"22222222-2222-2222-2222-222222222224","identityBasis":"conservative","intentionallyUnattached":false,"lastSharedAt":"1970-01-12T13:46:40.000Z","modifiedAt":"1970-01-12T13:46:40.000Z","note":"","rawURL":"https://trimmed.example/posts/hello?utm_source=share","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE3"},{"captureTitle":"Twice Over","captureTitleSource":"manual","citations":{"chapterTitle":{"kind":"none"},"identity":{"rawURL":{}},"workAssignment":{"manual":{}}},"conservativeIdentityKey":"https://dupe.example/read/1","entryIdentityKey":"https://dupe.example/read/1","firstCapturedAt":"1970-01-12T13:46:40.000Z","hostname":"dupe.example","id":"D0000000-0000-4000-8000-000000000002","identityBasis":"conservative","intentionallyUnattached":false,"lastSharedAt":"1970-01-12T13:46:40.000Z","modifiedAt":"1970-01-12T13:46:40.000Z","note":"","rawURL":"https://dupe.example/read/1","workID":"D0000000-0000-4000-8000-000000000001"}],"links":[{"createdAt":"1970-01-12T13:46:40.000Z","higherWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","id":"11115E51-0000-4000-8000-000000000001","linkType":"adaptation","lowerWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE3","modifiedAt":"1970-01-12T13:46:40.000Z"},{"createdAt":"1970-01-12T13:46:40.000Z","higherWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9","id":"11115E51-0000-4000-8000-000000000002","linkType":"spin-off","lowerWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2","modifiedAt":"1970-01-12T13:46:40.000Z"}],"memberships":[{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"golden.example","id":"77777777-0000-4000-8000-000000000001","urlIdentity":"golden.example/story/actual-title","urlIdentityRuleID":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD","urlIdentityState":"rule","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","workURLString":"https://golden.example/story/actual-title"},{"createdAt":"1970-01-12T13:46:41.000Z","hostname":"plain.example","id":"77777777-0000-4000-8000-000000000002","urlIdentityState":"none","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","workURLString":"https://plain.example/works/actual-title"},{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"plain.example","id":"77777777-0000-4000-8000-000000000003","urlIdentityState":"none","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2"},{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"trimmed.example","id":"77777777-0000-4000-8000-000000000004","urlIdentityState":"none","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE3"},{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"plain.example","id":"77777777-0000-4000-8000-000000000005","urlIdentity":"plain.example/absent","urlIdentityState":"legacyUnverified","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9"},{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"dupe.example","id":"77777777-0000-4000-8000-000000000006","urlIdentityState":"none","workID":"D0000000-0000-4000-8000-000000000001"}],"placeSuppressions":[{"actionAt":"1970-01-12T13:46:40.000Z","id":"5099E5ED-0000-4000-8000-000000000011","kindRaw":"candidate","nameKey":"low road","statusRaw":"active","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"actionAt":"1970-01-12T13:46:40.000Z","evidence":"above the pass","id":"5099E5ED-0000-4000-8000-000000000012","kindRaw":"fact","nameKey":"high keep","sourceEntryID":"22222222-2222-2222-2222-222222222222","sourceKindRaw":"entry","statusRaw":"active","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"}],"places":[{"aliases":["The Keep"],"createdAt":"1970-01-12T13:46:40.000Z","facts":[{"nameKey":"high keep","quote":"above the pass","source":{"entryID":"22222222-2222-2222-2222-222222222222","kind":"entry"},"statement":"Sits above the pass."}],"id":"91ACE000-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","name":"The High Keep","nameKey":"high keep","note":"The fortress above the pass.","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"aliases":[],"createdAt":"1970-01-12T13:46:40.000Z","facts":[],"id":"91ACE000-0000-4000-8000-000000000002","modifiedAt":"1970-01-12T13:46:40.000Z","name":"The Drowned Road","nameKey":"drowned road","note":"","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9"}],"series":[{"createdAt":"1970-01-12T13:46:40.000Z","id":"5E81E5A0-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","name":"Ashfall Cycle","notes":"Read 2.5 after 2."}],"sites":[{"displayName":"Dupe","hostname":"dupe.example","mode":"untaught"},{"displayName":"Golden","hostname":"golden.example","mode":"taught"},{"displayName":"Plain","hostname":"plain.example","mode":"untaught"},{"displayName":"Trimmed","hostname":"trimmed.example","mode":"taught"}],"suppressions":[{"actionAt":"1970-01-12T13:46:40.000Z","id":"5099E5ED-0000-4000-8000-000000000001","kindRaw":"candidate","nameKey":"the crowned one","statusRaw":"active","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"actionAt":"1970-01-12T13:46:40.000Z","evidence":"promised to guide them home","id":"5099E5ED-0000-4000-8000-000000000002","kindRaw":"fact","nameKey":"grover","sourceEntryID":"22222222-2222-2222-2222-222222222222","sourceKindRaw":"entry","statusRaw":"active","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"}],"titlePatterns":[{"createdAt":"1970-01-12T13:46:40.000Z","definition":{"definition":{"wholeTitle":{}},"trimSuffix":" - Trimmed Example"},"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCC2","isActive":true,"siteHostname":"trimmed.example","version":1},{"createdAt":"1970-01-12T13:46:40.000Z","definition":{"definition":{"wholeTitle":{}},"trimPrefix":"TtH • Story • "},"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC","isActive":true,"siteHostname":"golden.example","version":1}],"urlRules":[{"createdAt":"1970-01-12T13:46:40.000Z","definition":{"sequence":{"locator":{"query":{"name":"chapter"}}}},"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD","isCurrent":true,"origin":"readerTaught","siteHostname":"golden.example","version":1}],"workTypes":[{"canonicalID":"D0000001-0000-4000-8000-000000000001","createdAt":"1970-01-12T13:46:40.000Z","id":"00000000-0000-0000-0000-0000000000A1","modifiedAt":"1970-01-12T13:46:40.000Z","name":"novel","stateRaw":"merged"},{"canonicalID":"00000000-0000-0000-0000-0000000000A1","createdAt":"1970-01-12T13:46:40.000Z","id":"00000000-0000-0000-0000-0000000000A2","modifiedAt":"1970-01-12T13:46:40.000Z","name":"novella","stateRaw":"merged"},{"createdAt":"1970-01-01T00:00:00.000Z","id":"D0000001-0000-4000-8000-000000000001","modifiedAt":"1970-01-01T00:00:00.000Z","name":"novel","stateRaw":"active"},{"createdAt":"1970-01-01T00:00:00.000Z","id":"D0000002-0000-4000-8000-000000000002","modifiedAt":"1970-01-01T00:00:00.000Z","name":"webtoon","stateRaw":"active"}],"works":[{"createdAt":"1970-01-12T13:46:40.000Z","displayTitle":"Twice Over","genericNotes":"","genreTags":[],"id":"D0000000-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"reading","releaseDays":[],"titleProvenance":"manual","verdict":"","workStatus":"ongoing"},{"createdAt":"1970-01-12T13:46:40.000Z","displayTitle":"Plain Work","genericNotes":"","genreTags":[],"id":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2","modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"finished","releaseDays":[],"seriesID":"5E81E5A0-0000-4000-8000-000000000001","seriesPosition":1,"titleProvenance":"manual","typeName":"novel","verdict":"","workStatus":"finished","workTypeID":"00000000-0000-0000-0000-0000000000A2"},{"createdAt":"1970-01-12T13:46:40.000Z","displayTitle":"A Standalone","genericNotes":"","genreTags":[],"id":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE3","modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"reading","releaseDays":[],"seriesID":"5E81E5A0-0000-4000-8000-000000000009","seriesPosition":4,"titleProvenance":"manual","verdict":"","workStatus":"ongoing"},{"createdAt":"1970-01-12T13:46:40.000Z","displayTitle":"Actual Title","genericNotes":"The guide is not what he seems.","genericNotesExtractionFingerprint":"15b785793033dc26edf6396b3f0e1c27aa1ffaa61043ff49f907a970319a0499","genreTags":["fantasy"],"id":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","lastParsedTitle":"Actual Title","modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"abandoned","releaseDays":["monday","thursday"],"seriesID":"5E81E5A0-0000-4000-8000-000000000001","seriesPosition":2.5,"thumbnail":"/9j/4AAQSkZJRgABAQAASABIAAD/wAARCAOEAlgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9sAQwABAQEBAQECAQECAwICAgMEAwMDAwQGBAQEBAQGBwYGBgYGBgcHBwcHBwcHCAgICAgICQkJCQkLCwsLCwsLCwsL/9sAQwECAgIDAwMFAwMFCwgGCAsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsL/90ABAAm/9oADAMBAAIRAxEAPwD8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9k=","thumbnailShape":"portrait","titleProvenance":"parsed","typeName":"novel","verdict":"Stalled three years in; I gave up waiting.","workStatus":"hiatus","workTypeID":"00000000-0000-0000-0000-0000000000A1"}]},"workCount":4}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-16-17-golden.json b/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-16-17-golden.jsonnew file mode 100644index 00000000..bab79e94--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-16-17-golden.json@@ -0,0 +1 @@+{"appBuild":"golden","backupFormatVersion":16,"capabilityGate":"multi-site","checksum":"cfde6e107bfcadfbce3580cf6c1167a39fb4a734b63cd0aab0cc6815f90a19ba","databaseSchemaVersion":17,"entryCount":4,"exportedAt":"1970-01-12T13:46:40.000Z","payload":{"characters":[{"aliases":["Klar"],"createdAt":"1970-01-12T13:46:40.000Z","facts":[{"nameKey":"grover","quote":"promised to guide them home","source":{"entryID":"22222222-2222-2222-2222-222222222222","kind":"entry"},"statement":"Promised to guide them home."}],"id":"C4A2ACE0-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","name":"Grover","nameKey":"grover","note":"The guide.","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"aliases":[],"createdAt":"1970-01-12T13:46:40.000Z","facts":[],"id":"C4A2ACE0-0000-4000-8000-000000000002","modifiedAt":"1970-01-12T13:46:40.000Z","name":"The Stranger","nameKey":"the stranger","note":""}],"creatorRoles":[{"createdAt":"1970-01-01T00:00:00.000Z","id":"E0000001-0000-4000-8000-000000000001","modifiedAt":"1970-01-01T00:00:00.000Z","name":"author","nameModifiedAt":"1970-01-01T00:00:00.000Z","position":0,"positionModifiedAt":"1970-01-01T00:00:00.000Z","stateModifiedAt":"1970-01-01T00:00:00.000Z","stateRaw":"active"},{"createdAt":"1970-01-01T00:00:00.000Z","id":"E0000002-0000-4000-8000-000000000002","modifiedAt":"1970-01-01T00:00:00.000Z","name":"artist","nameModifiedAt":"1970-01-01T00:00:00.000Z","position":1,"positionModifiedAt":"1970-01-01T00:00:00.000Z","stateModifiedAt":"1970-01-01T00:00:00.000Z","stateRaw":"active"},{"createdAt":"1970-01-01T00:00:00.000Z","id":"E0000003-0000-4000-8000-000000000003","modifiedAt":"1970-01-01T00:00:00.000Z","name":"translator","nameModifiedAt":"1970-01-01T00:00:00.000Z","position":2,"positionModifiedAt":"1970-01-01T00:00:00.000Z","stateModifiedAt":"1970-01-01T00:00:00.000Z","stateRaw":"active"},{"createdAt":"1970-01-12T13:46:40.000Z","id":"E0000004-0000-4000-8000-000000000004","modifiedAt":"1970-01-12T13:46:40.000Z","name":"letterer","nameModifiedAt":"1970-01-12T13:46:40.000Z","position":3,"positionModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"active"},{"createdAt":"1970-01-12T13:46:40.000Z","id":"E0000005-0000-4000-8000-000000000005","modifiedAt":"1970-01-12T13:46:40.000Z","name":"editor","nameModifiedAt":"1970-01-12T13:46:40.000Z","position":4,"positionModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"removed"}],"creators":[{"createdAt":"1970-01-12T13:46:40.000Z","id":"C8EA1080-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","name":"Mori Ayane","nameModifiedAt":"1970-01-12T13:46:40.000Z","notes":"Also draws.","notesModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"active"},{"createdAt":"1970-01-12T13:46:40.000Z","id":"C8EA1080-0000-4000-8000-000000000002","modifiedAt":"1970-01-12T13:46:40.000Z","name":"Studio Lantern","nameModifiedAt":"1970-01-12T13:46:40.000Z","notes":"","notesModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"active"},{"canonicalID":"C8EA1080-0000-4000-8000-000000000001","createdAt":"1970-01-12T13:46:40.000Z","id":"C8EA1080-0000-4000-8000-000000000003","modifiedAt":"1970-01-12T13:46:40.000Z","name":"mori ayane","nameModifiedAt":"1970-01-12T13:46:40.000Z","notes":"","notesModifiedAt":"1970-01-12T13:46:40.000Z","stateModifiedAt":"1970-01-12T13:46:40.000Z","stateRaw":"merged"}],"credits":[{"createdAt":"1970-01-12T13:46:40.000Z","creatorID":"C8EA1080-0000-4000-8000-000000000001","id":"C8ED1700-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","roleIDs":["E0000001-0000-4000-8000-000000000001","E0000005-0000-4000-8000-000000000005"],"workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"createdAt":"1970-01-12T13:46:40.000Z","creatorID":"C8EA1080-0000-4000-8000-000000000002","id":"C8ED1700-0000-4000-8000-000000000002","modifiedAt":"1970-01-12T13:46:40.000Z","roleIDs":["E0000002-0000-4000-8000-000000000002","E000000F-0000-4000-8000-00000000000F"],"workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2"},{"createdAt":"1970-01-12T13:46:40.000Z","creatorID":"C8EA1080-0000-4000-8000-000000000001","id":"C8ED1700-0000-4000-8000-000000000003","modifiedAt":"1970-01-12T13:46:40.000Z","roleIDs":["E0000001-0000-4000-8000-000000000001"],"workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9"}],"distinctPairs":[{"higherWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","id":"88888888-0000-4000-8000-000000000001","lowerWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2","recordedAt":"1970-01-12T13:46:40.000Z"}],"entries":[{"captureTitle":"TtH • Story • Actual Title","captureTitleSource":"host","chapterSequence":"94","characterExtractionFingerprint":"448c04a700521270a7f5215cd2cfbbe77818591b29899fa94ca100201738f368","citations":{"chapterSequence":{"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD"},"chapterTitle":{"kind":"none"},"identity":{"composed":{"nameTitle":{"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC"},"url":{"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD"}}},"workAssignment":{"pattern":{"_0":{"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC"}}}},"conservativeIdentityKey":"https://golden.example/read?chapter=94&x=1","entryIdentityKey":"v3|h14:golden.example|n12:Actual Title|s2:94","firstCapturedAt":"1970-01-12T13:46:40.000Z","hostname":"golden.example","id":"22222222-2222-2222-2222-222222222222","identityBasis":"urlRule","intentionallyUnattached":false,"lastSharedAt":"1970-01-12T13:46:40.000Z","modifiedAt":"1970-01-12T13:46:40.000Z","note":"Grover promised to guide them home.","rating":"up","rawURL":"https://golden.example/read?chapter=94&x=1","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"captureTitle":"Plain Work","captureTitleSource":"manual","chapterTitle":"A Plain Chapter","citations":{"chapterTitle":{"kind":"manual"},"identity":{"rawURL":{}},"workAssignment":{"manual":{}}},"conservativeIdentityKey":"https://plain.example/read/7","entryIdentityKey":"https://plain.example/read/7","firstCapturedAt":"1970-01-12T13:46:40.000Z","hostname":"plain.example","id":"22222222-2222-2222-2222-222222222223","identityBasis":"conservative","intentionallyUnattached":false,"lastSharedAt":"1970-01-12T13:46:40.000Z","modifiedAt":"1970-01-12T13:46:40.000Z","note":"","rawURL":"https://plain.example/read/7","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2"},{"canonicalURL":"https://trimmed.example/posts/hello","captureTitle":"A Standalone - Trimmed Example","captureTitleSource":"host","citations":{"chapterTitle":{"kind":"none"},"identity":{"rawURL":{}},"workAssignment":{"manual":{}}},"conservativeIdentityKey":"https://trimmed.example/posts/hello?utm_source=share","entryIdentityKey":"https://trimmed.example/posts/hello?utm_source=share","firstCapturedAt":"1970-01-12T13:46:40.000Z","hostname":"trimmed.example","id":"22222222-2222-2222-2222-222222222224","identityBasis":"conservative","intentionallyUnattached":false,"lastSharedAt":"1970-01-12T13:46:40.000Z","modifiedAt":"1970-01-12T13:46:40.000Z","note":"","rawURL":"https://trimmed.example/posts/hello?utm_source=share","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE3"},{"captureTitle":"Twice Over","captureTitleSource":"manual","citations":{"chapterTitle":{"kind":"none"},"identity":{"rawURL":{}},"workAssignment":{"manual":{}}},"conservativeIdentityKey":"https://dupe.example/read/1","entryIdentityKey":"https://dupe.example/read/1","firstCapturedAt":"1970-01-12T13:46:40.000Z","hostname":"dupe.example","id":"D0000000-0000-4000-8000-000000000002","identityBasis":"conservative","intentionallyUnattached":false,"lastSharedAt":"1970-01-12T13:46:40.000Z","modifiedAt":"1970-01-12T13:46:40.000Z","note":"","rawURL":"https://dupe.example/read/1","workID":"D0000000-0000-4000-8000-000000000001"}],"links":[{"createdAt":"1970-01-12T13:46:40.000Z","higherWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","id":"11115E51-0000-4000-8000-000000000001","linkType":"adaptation","lowerWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE3","modifiedAt":"1970-01-12T13:46:40.000Z"},{"createdAt":"1970-01-12T13:46:40.000Z","higherWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9","id":"11115E51-0000-4000-8000-000000000002","linkType":"spin-off","lowerWorkID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2","modifiedAt":"1970-01-12T13:46:40.000Z"}],"memberships":[{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"golden.example","id":"77777777-0000-4000-8000-000000000001","urlIdentity":"golden.example/story/actual-title","urlIdentityRuleID":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD","urlIdentityState":"rule","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","workURLString":"https://golden.example/story/actual-title"},{"createdAt":"1970-01-12T13:46:41.000Z","hostname":"plain.example","id":"77777777-0000-4000-8000-000000000002","urlIdentityState":"none","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","workURLString":"https://plain.example/works/actual-title"},{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"plain.example","id":"77777777-0000-4000-8000-000000000003","urlIdentityState":"none","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2"},{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"trimmed.example","id":"77777777-0000-4000-8000-000000000004","urlIdentityState":"none","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE3"},{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"plain.example","id":"77777777-0000-4000-8000-000000000005","urlIdentity":"plain.example/absent","urlIdentityState":"legacyUnverified","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9"},{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"dupe.example","id":"77777777-0000-4000-8000-000000000006","urlIdentityState":"none","workID":"D0000000-0000-4000-8000-000000000001"}],"placeSuppressions":[{"actionAt":"1970-01-12T13:46:40.000Z","id":"5099E5ED-0000-4000-8000-000000000011","kindRaw":"candidate","nameKey":"low road","statusRaw":"active","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"actionAt":"1970-01-12T13:46:40.000Z","evidence":"above the pass","id":"5099E5ED-0000-4000-8000-000000000012","kindRaw":"fact","nameKey":"high keep","sourceEntryID":"22222222-2222-2222-2222-222222222222","sourceKindRaw":"entry","statusRaw":"active","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"}],"places":[{"aliases":["The Keep"],"createdAt":"1970-01-12T13:46:40.000Z","facts":[{"nameKey":"high keep","quote":"above the pass","source":{"entryID":"22222222-2222-2222-2222-222222222222","kind":"entry"},"statement":"Sits above the pass."}],"id":"91ACE000-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","name":"The High Keep","nameKey":"high keep","note":"The fortress above the pass.","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"aliases":[],"createdAt":"1970-01-12T13:46:40.000Z","facts":[],"id":"91ACE000-0000-4000-8000-000000000002","modifiedAt":"1970-01-12T13:46:40.000Z","name":"The Drowned Road","nameKey":"drowned road","note":"","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9"}],"series":[{"createdAt":"1970-01-12T13:46:40.000Z","id":"5E81E5A0-0000-4000-8000-000000000001","modifiedAt":"1970-01-12T13:46:40.000Z","name":"Ashfall Cycle","notes":"Read 2.5 after 2."}],"sites":[{"displayName":"Dupe","hostname":"dupe.example","mode":"untaught"},{"displayName":"Golden","hostname":"golden.example","mode":"taught"},{"displayName":"Plain","hostname":"plain.example","mode":"untaught"},{"displayName":"Trimmed","hostname":"trimmed.example","mode":"taught"}],"suppressions":[{"actionAt":"1970-01-12T13:46:40.000Z","id":"5099E5ED-0000-4000-8000-000000000001","kindRaw":"candidate","nameKey":"the crowned one","statusRaw":"active","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"actionAt":"1970-01-12T13:46:40.000Z","evidence":"promised to guide them home","id":"5099E5ED-0000-4000-8000-000000000002","kindRaw":"fact","nameKey":"grover","sourceEntryID":"22222222-2222-2222-2222-222222222222","sourceKindRaw":"entry","statusRaw":"active","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"}],"titlePatterns":[{"createdAt":"1970-01-12T13:46:40.000Z","definition":{"definition":{"wholeTitle":{}},"trimSuffix":" - Trimmed Example"},"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCC2","isActive":true,"siteHostname":"trimmed.example","version":1},{"createdAt":"1970-01-12T13:46:40.000Z","definition":{"definition":{"wholeTitle":{}},"trimPrefix":"TtH • Story • "},"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC","isActive":true,"siteHostname":"golden.example","version":1}],"urlRules":[{"createdAt":"1970-01-12T13:46:40.000Z","definition":{"sequence":{"locator":{"query":{"name":"chapter"}}}},"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD","isCurrent":true,"origin":"readerTaught","siteHostname":"golden.example","version":1}],"workTypes":[{"canonicalID":"D0000001-0000-4000-8000-000000000001","createdAt":"1970-01-12T13:46:40.000Z","id":"00000000-0000-0000-0000-0000000000A1","modifiedAt":"1970-01-12T13:46:40.000Z","name":"novel","stateRaw":"merged"},{"canonicalID":"00000000-0000-0000-0000-0000000000A1","createdAt":"1970-01-12T13:46:40.000Z","id":"00000000-0000-0000-0000-0000000000A2","modifiedAt":"1970-01-12T13:46:40.000Z","name":"novella","stateRaw":"merged"},{"createdAt":"1970-01-01T00:00:00.000Z","id":"D0000001-0000-4000-8000-000000000001","modifiedAt":"1970-01-01T00:00:00.000Z","name":"novel","stateRaw":"active"},{"createdAt":"1970-01-01T00:00:00.000Z","id":"D0000002-0000-4000-8000-000000000002","modifiedAt":"1970-01-01T00:00:00.000Z","name":"webtoon","stateRaw":"active"}],"works":[{"countsUpOnReleaseDays":true,"createdAt":"1970-01-12T13:46:40.000Z","displayTitle":"Twice Over","genericNotes":"","genreTags":[],"id":"D0000000-0000-4000-8000-000000000001","latestIsEstimate":false,"modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"reading","releaseDays":[],"titleProvenance":"manual","verdict":"","workStatus":"ongoing"},{"countsUpOnReleaseDays":true,"createdAt":"1970-01-12T13:46:40.000Z","displayTitle":"Plain Work","genericNotes":"","genreTags":[],"id":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE2","latestIsEstimate":false,"modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"finished","releaseDays":[],"seriesID":"5E81E5A0-0000-4000-8000-000000000001","seriesPosition":1,"titleProvenance":"manual","typeName":"novel","verdict":"","workStatus":"finished","workTypeID":"00000000-0000-0000-0000-0000000000A2"},{"countsUpOnReleaseDays":true,"createdAt":"1970-01-12T13:46:40.000Z","displayTitle":"A Standalone","genericNotes":"","genreTags":[],"id":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE3","latestIsEstimate":false,"modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"reading","releaseDays":[],"seriesID":"5E81E5A0-0000-4000-8000-000000000009","seriesPosition":4,"titleProvenance":"manual","verdict":"","workStatus":"ongoing"},{"countsUpOnReleaseDays":false,"createdAt":"1970-01-12T13:46:40.000Z","displayTitle":"Actual Title","genericNotes":"The guide is not what he seems.","genericNotesExtractionFingerprint":"15b785793033dc26edf6396b3f0e1c27aa1ffaa61043ff49f907a970319a0499","genreTags":["fantasy"],"id":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE","lastChapterOverrideAt":"1970-01-12T13:46:54.000Z","lastParsedTitle":"Actual Title","latestConfirmedAt":"1970-01-12T13:46:52.000Z","latestIsEstimate":true,"latestReleasedChapter":52,"modifiedAt":"1970-01-12T13:46:40.000Z","readingStatus":"abandoned","releaseDays":["monday","thursday"],"seriesID":"5E81E5A0-0000-4000-8000-000000000001","seriesPosition":2.5,"thumbnail":"/9j/4AAQSkZJRgABAQAASABIAAD/wAARCAOEAlgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9sAQwABAQEBAQECAQECAwICAgMEAwMDAwQGBAQEBAQGBwYGBgYGBgcHBwcHBwcHCAgICAgICQkJCQkLCwsLCwsLCwsL/9sAQwECAgIDAwMFAwMFCwgGCAsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsLCwsL/90ABAAm/9oADAMBAAIRAxEAPwD8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9D8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9H8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9L8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9P8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9T8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9X8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9b8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9f8p6KKK/pg/HwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA/9k=","thumbnailShape":"portrait","titleProvenance":"parsed","typeName":"novel","verdict":"Stalled three years in; I gave up waiting.","workStatus":"hiatus","workTypeID":"00000000-0000-0000-0000-0000000000A1"}]},"workCount":4}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swiftindex 2bc94fbb..3ce22337 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 `"16"`, the seventh two-character+ /// `"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 = "16\n"+ private static let markerContents = "17\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@@ -302,8 +302,8 @@ struct FrozenLibraryPathTests { /// both deliberately unversioned by name because they always mean the /// current generation. let declaresAStoreSchemaOrMarkerGeneration: Set<String> = [- "AsterismSchemaV15", "AsterismSchemaV16",- "AsterismV16MigrationPlan",+ "AsterismSchemaV16", "AsterismSchemaV17",+ "AsterismV17MigrationPlan", "atOrAboveV5", "belowV5", "firstV5Major", ] /// The archive format — 15/16, the one shape the app reads and writes,@@ -325,22 +325,22 @@ struct FrozenLibraryPathTests { /// single format, and a digit in their names would be a digit describing /// nothing. let namesTheArchiveFormat: Set<String> = [- "BackupV15Entry", "BackupV15Site", "BackupV15TitlePattern", "BackupV15URLRule",- "BackupV15Work", "BackupV15WorkType", "BackupV15Membership", "BackupV15DistinctPair",- "BackupV15Character", "BackupV15Codec", "BackupV15Series", "BackupV15Link",- "BackupV15Document", "BackupV15ExportError", "BackupV15Exporter", "BackupV15Metadata",- "BackupV15Payload", "BackupV15ReferenceValidator",- "BackupV15SnapshotProviding", "BackupV15Suppression",- "BackupV15Creator", "BackupV15CreatorRole", "BackupV15Credit",- "BackupV15Place", "BackupV15PlaceSuppression",- "backupV15Snapshot",+ "BackupV16Entry", "BackupV16Site", "BackupV16TitlePattern", "BackupV16URLRule",+ "BackupV16Work", "BackupV16WorkType", "BackupV16Membership", "BackupV16DistinctPair",+ "BackupV16Character", "BackupV16Codec", "BackupV16Series", "BackupV16Link",+ "BackupV16Document", "BackupV16ExportError", "BackupV16Exporter", "BackupV16Metadata",+ "BackupV16Payload", "BackupV16ReferenceValidator",+ "BackupV16SnapshotProviding", "BackupV16Suppression",+ "BackupV16Creator", "BackupV16CreatorRole", "BackupV16Credit",+ "BackupV16Place", "BackupV16PlaceSuppression",+ "backupV16Snapshot", "importedV2", "importedV2Path",- "mapV15EntryRecord", "mapV15SiteRecord", "mapV15TitlePatternRecord",- "mapV15URLRuleRecord", "mapV15WorkRecord",- "mapV15CharacterRecord", "mapV15SuppressionRecord",- "mapV15PlaceRecord", "mapV15PlaceSuppressionRecord",- "mapV15CreatorRecords", "mapV15CreatorRoleRecords",- "projectV15Payload",+ "mapV16EntryRecord", "mapV16SiteRecord", "mapV16TitlePatternRecord",+ "mapV16URLRuleRecord", "mapV16WorkRecord",+ "mapV16CharacterRecord", "mapV16SuppressionRecord",+ "mapV16PlaceRecord", "mapV16PlaceSuppressionRecord",+ "mapV16CreatorRecords", "mapV16CreatorRoleRecords",+ "projectV16Payload", ] /// The Entry identity-key generation, `EntryIdentityKeyV2Codec` / /// `V3Codec`. A v2 key and a v3 key are different encodings of the same@@ -390,13 +390,13 @@ struct FrozenLibraryPathTests { } #expect( declared.sorted() == [- "AsterismSchemaV15", "AsterismSchemaV16",+ "AsterismSchemaV16", "AsterismSchemaV17", ], "the package declares versioned schemas \(declared); Req 3.3 allows only ones a plan references") - let referenced = AsterismV16MigrationPlan.schemas.map { String(describing: $0) }+ let referenced = AsterismV17MigrationPlan.schemas.map { String(describing: $0) } #expect(- referenced == ["AsterismSchemaV15", "AsterismSchemaV16"],+ referenced == ["AsterismSchemaV16", "AsterismSchemaV17"], "the plan references \(referenced), which is not the set of declared schemas") // One lightweight stage, and it purely **removes**: V15 → V16 drops // one `Site` column inside `ModelContainer.init` and no table at all,@@ -408,13 +408,13 @@ struct FrozenLibraryPathTests { // superseded them (Q15 of `work-creators`, Q65 of `place-extraction`, // `work-thumbnails`, `update-schedule`, and this bump). #expect(- AsterismV16MigrationPlan.stages.count == 1,- "the plan stages \(AsterismV16MigrationPlan.stages.count) migrations; V15 → V16 is one")+ AsterismV17MigrationPlan.stages.count == 1,+ "the plan stages \(AsterismV17MigrationPlan.stages.count) migrations; V15 → V16 is one") #expect(- AsterismSchemaV15.versionIdentifier == Schema.Version(15, 0, 0),+ AsterismSchemaV16.versionIdentifier == Schema.Version(16, 0, 0), "the frozen snapshot's version stamp is the `from` side every V15 store is matched on") #expect(- AsterismSchemaV16.versionIdentifier == Schema.Version(16, 0, 0),+ AsterismSchemaV17.versionIdentifier == Schema.Version(17, 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 fb93602b..6b5305d8 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift@@ -244,6 +244,39 @@ struct GroupFetchTests { #expect(group.authoredContent == nil) #expect(group.variants.count == 2) }++ @Test("Progress elects across split rows without changing authored variants")+ func progressElectionIsIndependentOfCarrier() throws {+ let store = try GroupStore()+ let id = UUID()+ let bare = store.addWork(id: id, title: "A Serial")+ let carrier = store.addWork(id: id, title: "A Serial", offset: 60)+ carrier.genericNotes = "reader prose"+ try store.commit()+ let before = try LibraryRepository.fetchWorkGroup(id: id, context: store.context)++ let newerConfirmation = CatchUpConfirmation(+ latest: 50, confirmedAtMilliseconds: 2_000, countsUp: true, isEstimate: false)+ bare.catchUpConfirmationData = try JSONBlob.encode(newerConfirmation)+ carrier.catchUpConfirmationData = try JSONBlob.encode(CatchUpConfirmation(+ latest: 40, confirmedAtMilliseconds: 1_000, countsUp: false, isEstimate: false))+ carrier.lastChapterOverrideData = try JSONBlob.encode(+ LastChapterOverride.value(20, atMilliseconds: 3_000))+ try store.commit()++ let group = try LibraryRepository.fetchWorkGroup(id: id, context: store.context)+ #expect(group.carrier === carrier)+ #expect(group.variantIDs == before.variantIDs)+ #expect(group.authoredContent == before.authoredContent)+ let row = LibraryRepository.snapshot(+ bare, entries: [], types: .empty, series: .empty, credits: .empty)+ #expect(row.catchUp.confirmation == newerConfirmation)+ let presented = try LibraryRepository.snapshot(+ group, entryRows: [], canonicalWorkIDs: [:], types: .empty,+ series: .empty, credits: .empty)+ #expect(presented.catchUp.confirmation == newerConfirmation)+ #expect(presented.catchUp.override == .value(20, atMilliseconds: 3_000))+ } } // MARK: - Fixture@@ -260,12 +293,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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swiftindex 54adf186..97f3739a 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/HeldStoreLock.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/HeldStoreLock.swiftindex 7e0de365..773fda56 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/HeldStoreLock.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/HeldStoreLock.swift@@ -9,7 +9,7 @@ import SQLite3 /// its SQLite connection synchronously. The close follows on its own, takes the /// exclusive lock while it checkpoints, and any raw connection that reads inside /// that window is answered `SQLITE_BUSY` — "database is locked". Measured on this-/// repository (2026-09-19): straight after `V15RecordedStoreFixture.install` the+/// repository (2026-09-19): straight after `V16RecordedStoreFixture.install` the /// first read failed with code 5 beside a 168,952-byte log, and the same read /// succeeded 3.8 ms later beside an empty one. A window that short cannot be hit /// on purpose, so the regressions hold the same lock themselves.
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swiftindex 8e0b9c71..2356c3e6 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryGraphBaselineTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryGraphBaselineTests.swiftindex bd48948a..f2fe1b47 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryGraphBaselineTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryGraphBaselineTests.swift@@ -416,7 +416,11 @@ enum LibraryGraphSerializer { "# it. Hand-edited by deleting that one field from each site line", "# and reviewing the diff line by line (Req 7.4), not by", "# regenerating the file.",- "format 13",+ "# format 14 is schema V17 (catch-up-progress): every work line gains",+ "# catchUpConfirmationData and lastChapterOverrideData after releaseDaysRaw.",+ "# Both optional blobs are nil on a converted V16 row; no entity or",+ "# relationship changes. Hand-edited into the recorded work line.",+ "format 14", "counts entries=\(entries.count) works=\(works.count) sites=\(sites.count) " + "titlePatterns=\(patterns.count) urlRulePatterns=\(rules.count) " + "workTypes=\(workTypes.count) memberships=\(memberships.count) "@@ -495,6 +499,10 @@ enum LibraryGraphSerializer { // because what this file records is the store's shape. ("releaseDaysRaw", "[" + work.releaseDaysRaw.map(quoted).joined(separator: ",") + "]"),+ ("catchUpConfirmationData",+ optional(work.catchUpConfirmationData?.base64EncodedString())),+ ("lastChapterOverrideData",+ optional(work.lastChapterOverrideData?.base64EncodedString())), ("seriesID", optional(work.seriesID?.uuidString)), ("seriesPosition", optional(work.seriesPosition.map { "\($0)" })), // V14's presence columns, and **only** those two: reading
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swiftindex 9dee9f66..8d92bdb9 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swiftindex 511d7e9f..5574fc6a 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swiftindex 498051f9..d366fdd6 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift@@ -357,7 +357,7 @@ private struct LookupCaptureFixture { _ seed: (ModelContext, String) -> Void ) throws -> LookupCaptureFixture { let url = "https://example.com/chapter-1"- let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swiftindex 469ee2d9..ccd6622f 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swift@@ -140,7 +140,7 @@ struct M4BulkChunkPerformanceTests { /// hostname, every one of them carrying the Site relationship whose assignment /// is the cost being measured. private enum M4ChunkFixture {- static func exportedFixturePayload() async throws -> BackupV15Payload {+ static func exportedFixturePayload() async throws -> BackupV16Payload { let root = FileManager.default.temporaryDirectory .appending( path: "asterism-m4-chunk-source-\(UUID().uuidString)", directoryHint: .isDirectory)@@ -154,7 +154,7 @@ private enum M4ChunkFixture { let repository = LibraryRepository.makeRepository( configuration, container, .m4, SystemRepositoryClock(), ModelContextSaveStrategy()) try await repository.seedM4PerformanceFixture()- let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() withExtendedLifetime(container) {} return payload }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swiftindex ca72a3d4..da7c0af6 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swift@@ -274,7 +274,7 @@ struct M4DuplicateScalePerformanceTests { /// records what the projection alone costs so the claim is a reading rather /// than an argument. ///- /// The *projection* is timed, not `BackupV15Exporter.export`: the encode,+ /// The *projection* is timed, not `BackupV16Exporter.export`: the encode, /// the decode-validation and the file write dominate and none of them /// changed. @Test("Backup projection over a duplicate-free library (Q116, informational)")@@ -283,7 +283,7 @@ struct M4DuplicateScalePerformanceTests { let repository = try await store.openApp() let measured = try await measureDistributionAsync(iterations: 5) {- _ = try await repository.backupV15Snapshot()+ _ = try await repository.backupV16Snapshot() } reportPerformance("backup-projection-duplicate-free", measured) }@@ -342,7 +342,7 @@ struct M4DuplicateScalePerformanceTests { .appending( path: "asterism-m4-cover-export-\(UUID().uuidString)", directoryHint: .isDirectory) defer { try? FileManager.default.removeItem(at: staging) }- let exporter = BackupV15Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV16Exporter(repository: repository, stagingDirectory: staging) // The same settle its sibling takes, and for the same reason: the store // open above allocates, `measurePeakResident` reads its baseline the // moment the block starts, and a baseline read over the open's own@@ -353,7 +353,7 @@ struct M4DuplicateScalePerformanceTests { let (result, peak, duration) = try await measurePeakResident { try await exporter.export(- metadata: BackupV15Metadata(appBuild: "m4-performance", exportedAt: Date()))+ metadata: BackupV16Metadata(appBuild: "m4-performance", exportedAt: Date())) } let size = try Self.fileSize(of: result.fileURL) @@ -516,9 +516,9 @@ struct M4DuplicateScalePerformanceTests { ) async throws -> (fileURL: URL, size: Int) { let source = try await M4DuplicatePerformanceStore(state: nil) let repository = try await source.openApp()- let exported = try await BackupV15Exporter(+ let exported = try await BackupV16Exporter( repository: repository, stagingDirectory: staging- ).export(metadata: BackupV15Metadata(appBuild: "m4-performance", exportedAt: Date()))+ ).export(metadata: BackupV16Metadata(appBuild: "m4-performance", exportedAt: Date())) await repository.shutdown() return (exported.fileURL, try fileSize(of: exported.fileURL)) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ScaleFixtureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ScaleFixtureTests.swiftindex f2c74864..a460db97 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ScaleFixtureTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ScaleFixtureTests.swift@@ -375,6 +375,11 @@ struct M4ScaleFixtureTests { #expect( caughtUp.allSatisfy { plain[$0].releaseDays.isEmpty }, "a catch-up work must not be one of the scheduled third")+ #expect(caughtUp.allSatisfy { index in+ let record = plain[index].catchUpRecord+ return record.latest != nil && record.override != nil+ && (record.confirmation?.confirmedAtMilliseconds ?? 0) < 0+ }, "every measured catch-up work needs a past latest and override") // Everything else stays on the default — the 334 are untouched and still // reach `TodaySchedule.build`. Asserted once, above, as part of the // ongoing-and-reading pin: `scheduled` is read from the seeded store@@ -386,7 +391,10 @@ struct M4ScaleFixtureTests { // after the first. #expect( works.filter { LibraryRepository.isDuplicateFixtureWork($0) }- .allSatisfy { $0.releaseDays.isEmpty && $0.readingStatus == .reading })+ .allSatisfy {+ $0.releaseDays.isEmpty && $0.readingStatus == .reading+ && $0.catchUpRecord == .pristine+ }) let entries = try seeded.fetch(FetchDescriptor<Entry>()) let base = entries
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swiftindex b90ff315..6fffda7b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift@@ -3,36 +3,9 @@ import SwiftData import Testing @testable import AsterismCore -/// Task 4: the two-process marker contract (Q14, Req 2.3).-///-/// `openContainer` is shared by both processes, so `ModelContainer.init`-/// performs the lightweight conversion in whichever process opens first — and-/// the extension takes only a *shared* lock, so nothing serialises it against-/// the app. The defence is the readiness marker, read *before* either process-/// constructs a container.-///-/// **The app opens two generations and the extension one.**-/// `remove-article-mode` publishes `"16"` and holds `"15"` in-/// `appOpenableMarkerVersions` as the generation V16 upgrades from (Req 4.4):-/// the app opens it — the lightweight stage drops one `Site` column and no-/// table at all inside `ModelContainer.init` — validates the store and-/// republishes at `"16"`, with no data pass and no reconciler. The extension-/// refuses `"15"` outright, because it holds only a shared lock and must never-/// convert or write — which matters more for a *removing* stage than it did for-/// the adding ones. `"4"`–`"14"` stay retired (`data-model-cleanups`-/// Decision 2, Q2 of `drop-superseded-columns` for `"7"`, Q18 of-/// `work-and-reading-status` for `"8"`, Q32 of `series-and-related-works` for-/// `"9"`, Q15 of `work-creators` for `"10"`, Q48 of `place-extraction` for-/// `"11"`, `work-thumbnails` for `"12"`, `update-schedule` for `"13"` and this-/// bump for `"14"`) and are refused by both.-///-/// The extension's refusal therefore **forks** (Req 2.3), as it did before-/// Decision 2 collapsed it: a generation the app opens is resolvable by opening-/// the app, and the message says so; anything else is not, and gets the shipped-/// "has not initialized" wording. The state the first branch is for is the-/// update window — the gap between the app being updated and first launched,-/// where the library still records the previous generation (Req 8.7 of-/// `configurable-work-types`).+/// The app accepts the current marker `"17"` and one lagging marker `"16"`.+/// The extension accepts only `"17"`; it refuses the lagging generation+/// before constructing a container, so it never runs the V16 → V17 stage. @Suite("Marker contract", .serialized) struct MarkerContractTests { @@ -55,7 +28,7 @@ struct MarkerContractTests { /// A first run: creates an empty store and marks it ready at birth. An /// empty store has nothing to migrate, so mark-at-birth certifies it at- /// `"16"` directly (Q26).+ /// `"17"` directly (Q26). private func makeReadyLibrary(_ configuration: LibraryConfiguration) async throws { _ = try await LibraryRepository.openForApp(configuration) }@@ -98,12 +71,12 @@ struct MarkerContractTests { func appAcceptsTheCurrentMarkerVersion() async throws { let (_, cfg) = try config() try await makeReadyLibrary(cfg)- #expect(try markerContent(cfg) == "16",+ #expect(try markerContent(cfg) == "17", "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) == "16", "and the open leaves the marker as it found it")+ #expect(try markerContent(cfg) == "17", "and the open leaves the marker as it found it") } /// Req 4.4: the previous generation is *opened*, not refused — the stage@@ -113,13 +86,13 @@ struct MarkerContractTests { func appUpgradesTheLaggingGeneration() async throws { let (_, cfg) = try config() try await makeReadyLibrary(cfg)- try writeMarker(cfg, "15\n")+ try writeMarker(cfg, "16\n") let (result, repository) = try await LibraryRepository.openForApp(cfg) await repository.shutdown() #expect(result == .ready(.seededEmpty))- #expect(try markerContent(cfg) == "16",+ #expect(try markerContent(cfg) == "17", "the marker moves only after the converted store has validated") } @@ -165,7 +138,7 @@ struct MarkerContractTests { func extensionAcceptsTheCurrentVersion() async throws { let (_, cfg) = try config() try await makeReadyLibrary(cfg)- #expect(try markerContent(cfg) == "16")+ #expect(try markerContent(cfg) == "17") let (result, _) = try await LibraryRepository.openForExtension(cfg) #expect(result == .ready(.seededEmpty))@@ -183,19 +156,19 @@ struct MarkerContractTests { /// Req 8.7 of `configurable-work-types`, now with the live generation: /// between the app being updated and first launched the library still- /// records `"15"`, and a capture in that window must fail safely rather than+ /// records `"16"`, and a capture in that window must fail safely rather than /// convert the store under a shared lock. The message is the actionable one, /// because opening the app is what resolves it. @Test("The extension declines the update window and says to open the app") func extensionDeclinesTheUpdateWindow() async throws { let (_, cfg) = try config() try await makeReadyLibrary(cfg)- try writeMarker(cfg, "15\n")+ try writeMarker(cfg, "16\n") await #expect(throws: Self.openTheApp) { try await LibraryRepository.openForExtension(cfg) }- #expect(try markerContent(cfg) == "15", "the extension may not republish readiness")+ #expect(try markerContent(cfg) == "16", "the extension may not republish readiness") } /// The other half of the fork: a generation the app does not open either@@ -222,21 +195,21 @@ struct MarkerContractTests { // shared lock (Q14). A store that cannot be opened at all would prove // nothing about the ordering, which is why this uses the // frozen-snapshot seed.- try V15RecordedStoreFixture.install(at: cfg.storeURL)+ try V16RecordedStoreFixture.install(at: cfg.storeURL) try writeMarker(cfg, "4\n") await #expect(throws: Self.declined) { try await LibraryRepository.openForExtension(cfg) }- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["15.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["16.0.0"], "the marker check must decide before ModelContainer.init converts anything") - // Control: with a "16" marker the same store is reached, opened, and+ // 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, "16\n")+ try writeMarker(cfg, "17\n") _ = try await LibraryRepository.openForExtension(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["16.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["17.0.0"], "the same store converts once the marker check passes") }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSixteenTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swiftsimilarity index 80%rename from Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSixteenTests.swiftrename to Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swiftindex 1a210f58..dc2a1995 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSixteenTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift@@ -4,43 +4,28 @@ import Testing @testable import AsterismCore -/// The `"15"` → `"16"` generation, end to end (Req 4.4).-///-/// V16's arm has the same shape as V15's: the lightweight stage does the whole-/// of the conversion inside `ModelContainer.init`, so there is no data pass and-/// no reconciler to run after it. What is left is the sequence — open, validate,-/// publish — the failure that must leave the marker where it found it, and both-/// halves of the extension's fork.-///-/// V16 **removes one column**, where V15 added one: `Site.junkSuffixRule`, and-/// no table anywhere. It is the first removing stage since V8 → V9, which is-/// why the extension's refusal matters more here than it did at the adding-/// bumps — a concurrent share-sheet open part-way through a removal is-/// destructive rather than merely early. `V15RecordedStoreTests` is where the-/// removal is asserted row by row; this suite is about the marker and the-/// order.-///-/// Every case runs over a library a **V15 build** left behind: a store recorded-/// at 15.0.0 with a populated junk-suffix rule, marked `"15"`.-@Suite("Marker generation 16", .serialized)-struct MarkerGenerationSixteenTests {+/// The `"16"` → `"17"` readiness generation. The app converts a V16+/// recorded store, validates it, and publishes `"17"`; the extension refuses+/// the lagging marker before constructing a container.+@Suite("Marker generation 17", .serialized)+struct MarkerGenerationSeventeenTests { private final class Root { let url: URL let configuration: LibraryConfiguration init() throws { url = FileManager.default.temporaryDirectory.appending(- path: "MarkerSixteen-\(UUID())", directoryHint: .isDirectory)+ path: "MarkerSeventeen-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) configuration = LibraryConfiguration(rootDirectory: url) } deinit { try? FileManager.default.removeItem(at: url) } /// What a device that has run the V15 build holds: the store recorded- /// at 15.0.0, and the marker at `"15"`.- func seedV15Library() throws {- try V15RecordedStoreFixture.install(at: configuration.storeURL)- try writeMarker("15\n")+ /// at 15.0.0, and the marker at `"16"`.+ func seedV16Library() throws {+ try V16RecordedStoreFixture.install(at: configuration.storeURL)+ try writeMarker("16\n") } func writeMarker(_ content: String) throws {@@ -56,20 +41,20 @@ struct MarkerGenerationSixteenTests { // MARK: - The classification @Test("A \"15\" marker over a store classifies as the lagging generation")- func fifteenIsLagging() throws {+ func sixteenIsLagging() throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() #expect(try LibraryRepository.classify(root.configuration, fileManager: .default)- == .markerLagging(generation: "15"))+ == .markerLagging(generation: "16")) withExtendedLifetime(root) {} } @Test("A \"16\" marker over a store classifies ready")- func sixteenIsReady() throws {+ func seventeenIsReady() throws { let root = try Root()- try root.seedV15Library()- try root.writeMarker("16\n")+ try root.seedV16Library()+ try root.writeMarker("17\n") #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready) withExtendedLifetime(root) {}@@ -81,10 +66,10 @@ struct MarkerGenerationSixteenTests { /// (`update-schedule`), so the plan can no longer convert such a store /// either. @Test("Any other generation is unrecognised, and the refusal names it",- arguments: ["4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"])+ arguments: ["4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]) func otherGenerationsAreUnrecognised(digit: String) throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() try root.writeMarker("\(digit)\n") guard case .unrecognised(let reason) = try LibraryRepository.classify(@@ -104,7 +89,7 @@ struct MarkerGenerationSixteenTests { @Test("The app arm converts, validates and republishes") func armRunsTheWholeSequence() async throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() let (result, repository) = try await LibraryRepository.openForApp(root.configuration) defer { withExtendedLifetime(root) {} }@@ -116,9 +101,9 @@ struct MarkerGenerationSixteenTests { } #expect(counts.works == 1) #expect(counts.entries == 3)- #expect(try root.markerText() == "16")+ #expect(try root.markerText() == "17") #expect(try V4RecordedStoreFixture.recordedModelVersions(at: root.configuration.storeURL)- == ["16.0.0"], "the store the arm opened is recorded at the version it converted to")+ == ["17.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"@@ -133,8 +118,8 @@ struct MarkerGenerationSixteenTests { } await repository.shutdown() #expect(facts.memberships == [- "\(V15RecordedStoreFixture.hostname)|\(V15RecordedStoreFixture.workIdentity)"- + "|\(V15RecordedStoreFixture.workID.uuidString)",+ "\(V16RecordedStoreFixture.hostname)|\(V16RecordedStoreFixture.workIdentity)"+ + "|\(V16RecordedStoreFixture.workID.uuidString)", ]) // The arm converts nothing beyond the stage, so the fixture's one // nil-blob Entry is still nil-blob on the far side — a report, not a@@ -147,7 +132,7 @@ struct MarkerGenerationSixteenTests { @Test("The second open is an ordinary ready open") func secondOpenIsReady() async throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() let (_, first) = try await LibraryRepository.openForApp(root.configuration) await first.shutdown() @@ -159,14 +144,13 @@ struct MarkerGenerationSixteenTests { Issue.record("expected a ready library, got \(result)") return }- #expect(try root.markerText() == "16")+ #expect(try root.markerText() == "17") withExtendedLifetime(root) {} } - /// **The marker goes last**, so a throw anywhere above it leaves `"15"` on+ /// **The marker goes last**, so a throw anywhere above it leaves `"16"` on /// disk and the next open re-enters the arm over an already converted store- /// — which is a no-op, because removing a column that is already gone is- /// one.+ /// — which is safe because the optional columns are already present. /// /// The arm has exactly two things that can throw — the open and the /// validation — and both are above `publishReadiness`. This drives the open,@@ -176,17 +160,17 @@ struct MarkerGenerationSixteenTests { @Test("A failed open leaves the marker at \"15\", and the next open completes it") func aFailedOpenLeavesTheMarkerAlone() async throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() let intact = try Data(contentsOf: root.configuration.storeURL) try Data("not a database".utf8).write(to: root.configuration.storeURL, options: .atomic) await #expect(throws: (any Error).self) { try await LibraryRepository.openForApp(root.configuration) }- #expect(try root.markerText() == "15",+ #expect(try root.markerText() == "16", "the marker may not move over an open that did not complete") #expect(try LibraryRepository.classify(root.configuration, fileManager: .default)- == .markerLagging(generation: "15"),+ == .markerLagging(generation: "16"), "the next open re-enters the same arm") try intact.write(to: root.configuration.storeURL, options: .atomic)@@ -196,7 +180,7 @@ struct MarkerGenerationSixteenTests { Issue.record("expected the retry to reach a ready library, got \(result)") return }- #expect(try root.markerText() == "16")+ #expect(try root.markerText() == "17") withExtendedLifetime(root) {} } @@ -206,7 +190,7 @@ struct MarkerGenerationSixteenTests { @Test("A library with a quarantined hostname still opens, and reports it") func validationDiagnosesRatherThanRefuses() async throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() // Break the cited chapter pattern's definition, which is an // `.unreadableTitlePattern` quarantine on V15 and must stay one on V16. do {@@ -226,14 +210,14 @@ struct MarkerGenerationSixteenTests { let (result, repository) = try await LibraryRepository.openForApp(root.configuration) let quarantined = await repository.quarantineReason(- hostname: V15RecordedStoreFixture.hostname)+ hostname: V16RecordedStoreFixture.hostname) await repository.shutdown() guard case .ready = result else { Issue.record("a diagnosable library must still open, got \(result)") return }- #expect(try root.markerText() == "16")+ #expect(try root.markerText() == "17") #expect(quarantined != nil, "the broken title rule quarantines its hostname, as on V15") withExtendedLifetime(root) {} }@@ -250,7 +234,7 @@ struct MarkerGenerationSixteenTests { @Test("A failed publish leaves the historical marker and the sidecar in place") func aFailedPublishKeepsTheResidualEvidence() throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() try Data("3\n".utf8).write( to: root.configuration.historicalMarkerURL, options: .atomic) try Data("stale\n".utf8).write(@@ -266,9 +250,9 @@ struct MarkerGenerationSixteenTests { #expect(throws: (any Error).self) { try LibraryRepository.act(- on: .markerLagging(generation: "15"), root.configuration, hooks: .production)+ on: .markerLagging(generation: "16"), root.configuration, hooks: .production) }- #expect(try root.markerText() == "15",+ #expect(try root.markerText() == "16", "the marker may not move over a publish that did not complete") #expect(files.fileExists(atPath: root.configuration.historicalMarkerURL.path)) #expect(files.fileExists(atPath: root.configuration.migrationSidecarURL.path),@@ -281,24 +265,24 @@ struct MarkerGenerationSixteenTests { @Test("The extension refuses \"15\" and says to open the app") func extensionRefusesTheLaggingGeneration() async throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() await #expect(throws: LibraryRepositoryError.libraryUnavailable( operation: "opening library from extension", reason: "Open Asterism to finish updating the library")) { try await LibraryRepository.openForExtension(root.configuration) }- #expect(try root.markerText() == "15", "the extension may not convert or republish")+ #expect(try root.markerText() == "16", "the extension may not convert or republish") #expect(try V4RecordedStoreFixture.recordedModelVersions(at: root.configuration.storeURL)- == ["15.0.0"], "and may not let ModelContainer.init convert the store")+ == ["16.0.0"], "and may not let ModelContainer.init convert the store") withExtendedLifetime(root) {} } @Test("The extension keeps the existing reason for a generation no build opens",- arguments: ["4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"])+ arguments: ["4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]) func extensionRefusesUnknownDigits(digit: String) async throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() try root.writeMarker("\(digit)\n") await #expect(throws: LibraryRepositoryError.libraryUnavailable(@@ -312,10 +296,10 @@ struct MarkerGenerationSixteenTests { @Test("The extension opens \"16\"") func extensionOpensTheCurrentGeneration() async throws { let root = try Root()- try root.seedV15Library()+ try root.seedV16Library() let (_, repository) = try await LibraryRepository.openForApp(root.configuration) await repository.shutdown()- #expect(try root.markerText() == "16")+ #expect(try root.markerText() == "17") 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 61dd025c..85b239c4 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swiftindex 814b5ab5..525fc710 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swift@@ -109,7 +109,7 @@ extension LibraryRepository { } } - /// Exports and decode-validates, which is exactly what `BackupV15Exporter`+ /// Exports and decode-validates, which is exactly what `BackupV16Exporter` /// does — and `BackupArchiveReferenceChecks` is where a membership whose /// hostname and cited identity rule describe **different sites** is refused, /// along with the rest of the identity tuple. Three separate membership bugs@@ -119,11 +119,11 @@ extension LibraryRepository { sourceLocation: SourceLocation = #_sourceLocation ) async throws { do {- let payload = try await backupV15Snapshot()- let encoded = try BackupV15Codec.encode(+ let payload = try await backupV16Snapshot()+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))- _ = try BackupV15Codec.decode(encoded)+ metadata: BackupV16Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))+ _ = try BackupV16Codec.decode(encoded) } catch { Issue.record( comment ?? "the archive is not legal: \(error)", sourceLocation: sourceLocation)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swiftindex be083401..da0bc9ea 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swiftindex 069f651a..782b7d9e 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 == "16")+ #expect(call.markerVersion == "17") #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 == "16")+ #expect(log.calls.first?.markerVersion == "17") #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 == "16")+ #expect(log.calls.first?.markerVersion == "17") #expect(await repository.mirroring.isMirroring) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swiftindex adc4f3ae..bfbff374 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift@@ -128,7 +128,7 @@ struct ModelContractTests { #expect(throws: ModelInvariantError.self) { try URLIdentityRule(version: 1, component: .pathSegment, queryName: "chapter") } // `JunkSuffixRule` has had no live consumer since V16 dropped // `Site.junkSuffixRule`, and this line is deliberately kept: the frozen- // `AsterismSchemaV15` snapshot is frozen *by reference* to the type, so+ // `AsterismSchemaV16` snapshot is frozen *by reference* to the type, so // its shape is still a stored shape (Req 4.5, Q8). #expect(throws: ModelInvariantError.self) { try JunkSuffixRule(version: 0, anchors: []) } #expect(throws: ModelInvariantError.self) { try FieldProvenance(kind: .pattern, patternID: nil) }@@ -201,10 +201,10 @@ struct ModelContractTests { "Series", "WorkLink", "Creator", "CreatorRole", "WorkCredit", "Place", "PlaceSuppression", ]+ #expect(AsterismSchemaV17.versionIdentifier == Schema.Version(17, 0, 0))+ #expect(AsterismSchemaV17.models.map { String(describing: $0) } == seventeen) #expect(AsterismSchemaV16.versionIdentifier == Schema.Version(16, 0, 0)) #expect(AsterismSchemaV16.models.map { String(describing: $0) } == seventeen)- #expect(AsterismSchemaV15.versionIdentifier == Schema.Version(15, 0, 0))- #expect(AsterismSchemaV15.models.map { String(describing: $0) } == seventeen) } /// `empty-library` Req 3.1: the deletion pass names **every** entity the@@ -219,7 +219,7 @@ struct ModelContractTests { func emptyLibraryPhasesCoverTheSchema() { let phased = Set( LibraryRepository.emptyLibraryPhases.flatMap { $0.entities.map(\.name) })- let declared = Set(AsterismSchemaV16.models.map { String(describing: $0) })+ let declared = Set(AsterismSchemaV17.models.map { String(describing: $0) }) #expect( phased == declared, """@@ -248,72 +248,30 @@ struct ModelContractTests { /// its name while changing destination, cardinality, delete rule or /// inverse, are all shape changes a lightweight stage may not make, and all /// invisible to a comparison of names.- @Test("V16's Site is V15's minus exactly junkSuffixRule, and no other entity moves")- func siteColumnsAreTheJunkSuffixDeltaAtV16() {- let retained = [- "hostname", "displayName", "modeRaw",- "patterns", "urlRules", "entries", "workMemberships",- ]- let removed = ["junkSuffixRule"]- let live = Self.properties(of: "Site", in: Schema(versionedSchema: AsterismSchemaV16.self))- let frozen = Self.properties(- of: "Site", in: Schema(versionedSchema: AsterismSchemaV15.self))- for column in retained {- #expect(frozen.contains(column), "Site.\(column) is missing from the V15 schema")- #expect(live.contains(column), "Site.\(column) is missing from the V16 schema")+ @Test("V17 Work adds exactly two optional Data columns; other entities are unchanged")+ func catchUpBlobColumnsAreTheOnlyV17Delta() throws {+ let liveSchema = Schema(versionedSchema: AsterismSchemaV17.self)+ let frozenSchema = Schema(versionedSchema: AsterismSchemaV16.self)+ #expect(Set(liveSchema.entities.map(\.name)) == Set(frozenSchema.entities.map(\.name)))+ let added: Set<String> = ["catchUpConfirmationData", "lastChapterOverrideData"]+ let live = Self.propertyShapes(of: "Work", in: liveSchema)+ let frozen = Self.propertyShapes(of: "Work", in: frozenSchema)+ #expect(Set(live.keys).subtracting(frozen.keys) == added)+ #expect(Set(frozen.keys).subtracting(live.keys).isEmpty)+ #expect(live.filter { !added.contains($0.key) } == frozen)+ for name in added {+ let entity = try #require(liveSchema.entities.first { $0.name == "Work" })+ let column = try #require(entity.properties.first { $0.name == name } as? Schema.Attribute)+ #expect(column.isOptional)+ #expect(!column.isUnique)+ #expect(column.valueType == Data.self || column.valueType == Data?.self)+ #expect(!column.options.contains(.externalStorage)) }- for column in removed {- #expect(frozen.contains(column), "Site.\(column) is not in the frozen V15 snapshot")- #expect(!live.contains(column), "Site.\(column) is still in the V16 schema")+ for name in liveSchema.entities.map(\.name) where name != "Work" {+ #expect(Self.propertyShapes(of: name, in: liveSchema)+ == Self.propertyShapes(of: name, in: frozenSchema),+ "V16 -> V17 changed \(name) beyond Work") }- #expect(- frozen.subtracting(live) == Set(removed),- """- V15 -> V16 is meant to remove exactly junkSuffixRule, but \- it removed \(frozen.subtracting(live).sorted())- """)- #expect(- live.subtracting(frozen).isEmpty,- "V15 -> V16 adds \(live.subtracting(frozen).sorted()); this stage only removes")-- let liveSchema = Schema(versionedSchema: AsterismSchemaV16.self)- let frozenSchema = Schema(versionedSchema: AsterismSchemaV15.self)-- // `Site`'s surviving columns are unchanged in *shape*, not merely- // present by name: the same delta over `propertyShapes`, with the- // removed column dropped from the frozen side.- let liveSiteShapes = Self.propertyShapes(of: "Site", in: liveSchema)- let frozenSiteShapes = Self.propertyShapes(of: "Site", in: frozenSchema)- .filter { !removed.contains($0.key) }- #expect(- liveSiteShapes == frozenSiteShapes,- """- V15 -> V16 changed a surviving Site column's shape: \- \(Self.shapeDifferences(live: liveSiteShapes, frozen: frozenSiteShapes))- """)-- // Every other entity is identical property for property — name, value- // type, optionality, uniqueness and attribute options for a column;- // destination, optionality, cardinality, delete rule and inverse for a- // relationship. This is the "and nothing else" half. `Work` is named on- // its own below because it is the table the last four bumps moved; this- // loop covers all seventeen.- for name in liveSchema.entities.map(\.name) where name != "Site" {- let liveShapes = Self.propertyShapes(of: name, in: liveSchema)- let frozenShapes = Self.propertyShapes(of: name, in: frozenSchema)- #expect(- liveShapes == frozenShapes,- """- V15 -> V16 changed \(name), which this stage may not touch: \- \(Self.shapeDifferences(live: liveShapes, frozen: frozenShapes))- """)- }- // The control: the frozen snapshot is a real schema, not an empty read,- // and `Work` still carries every column the earlier stages supplied.- #expect(frozen.contains("modeRaw"))- #expect(- Self.properties(of: "Work", in: liveSchema)- .isSuperset(of: ["releaseDaysRaw", "thumbnailData", "workStatusRaw", "seriesID"])) } /// `releaseDaysRaw` as CloudKit will materialise it and as the store will@@ -338,7 +296,7 @@ struct ModelContractTests { work.releaseDays = [.sunday, .monday, .sunday] #expect(work.releaseDaysRaw == ["monday", "sunday"], "the setter writes canonical order") - let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.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 }@@ -363,8 +321,8 @@ struct ModelContractTests { /// *names* are identical, V13's two place tables included. @Test("V16 changes no entity, and the frozen V15 carries every table it inherited") func noTableChangesAtV16() {- let live = Set(Schema(versionedSchema: AsterismSchemaV16.self).entities.map(\.name))- let frozen = Set(Schema(versionedSchema: AsterismSchemaV15.self).entities.map(\.name))+ let live = Set(Schema(versionedSchema: AsterismSchemaV17.self).entities.map(\.name))+ let frozen = Set(Schema(versionedSchema: AsterismSchemaV16.self).entities.map(\.name)) #expect(live == frozen, "V15 -> V16 changed the entity list: \(live.symmetricDifference(frozen))") // The control: the frozen snapshot is a real schema, and it is V15's — // it carries every table the stages before it added.@@ -392,7 +350,7 @@ struct ModelContractTests { #expect(work.thumbnailShape == nil) #expect(work.thumbnailIdentity == nil) - let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.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@@ -418,7 +376,7 @@ struct ModelContractTests { #expect(byName["displayTitle"]?.options.contains(.externalStorage) == false) } - /// The same pin over the **frozen** `AsterismSchemaV15` snapshot.+ /// The same pin over the **frozen** `AsterismSchemaV16` snapshot. /// /// `docs/agent-notes/schema-migration.md` requires `@Attribute` options to be /// carried across verbatim when a version is frozen, and nothing else asserts@@ -428,7 +386,7 @@ struct ModelContractTests { /// only as a migration that rewrites every cover. @Test("The frozen V15 snapshot still carries `.externalStorage` on Work.thumbnailData") func frozenV15ThumbnailDataIsExternallyStored() throws {- let schema = Schema(versionedSchema: AsterismSchemaV15.self)+ let schema = Schema(versionedSchema: AsterismSchemaV16.self) let entity = try #require(schema.entities.first { $0.name == "Work" }) let attributes = entity.properties.compactMap { $0 as? Schema.Attribute } let byName = Dictionary(uniqueKeysWithValues: attributes.map { ($0.name, $0) })@@ -484,7 +442,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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.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")@@ -561,7 +519,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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.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")@@ -602,7 +560,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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.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")@@ -735,7 +693,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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) var propertiesByEntity: [String: Set<String>] = [:] for entity in schema.entities { propertiesByEntity[entity.name, default: []]@@ -756,7 +714,7 @@ struct ModelContractTests { #expect(propertiesByEntity["Work"]?.contains("siteMemberships") == true) } - /// **Every frozen snapshot is a stage's `from` side.** `AsterismSchemaV15`+ /// **Every frozen snapshot is a stage's `from` side.** `AsterismSchemaV16` /// is the one the plan names; V5 through V14 went with the stages that named /// them (Q2 of `drop-superseded-columns`, Q18 of `work-and-reading-status`, /// Q60 of `series-and-related-works`, Q15 of `work-creators`, Q48 of@@ -765,7 +723,7 @@ struct ModelContractTests { /// a file that starts declaring a snapshot without a stage to be the `from` /// side of is a store shape nothing can reach. ///- /// There are two declarations rather than one because `AsterismSchemaV16` is+ /// There are two declarations rather than one because `AsterismSchemaV17` is /// the live schema, and the count of *snapshots* is one: V14 went in this /// bump's freeze commit, the owner having confirmed every device on marker /// `"15"` before it ran (Q10).@@ -815,7 +773,7 @@ struct ModelContractTests { #expect( declaringSnapshots.sorted() == [- "AsterismSchemaV15.swift", "AsterismSchemaV16.swift",+ "AsterismSchemaV16.swift", "AsterismSchemaV17.swift", ], """ the package declares versioned schemas in \(declaringSnapshots.sorted()); \@@ -1132,7 +1090,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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swiftindex 9a35b41b..9fc0cedc 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift@@ -124,7 +124,7 @@ struct MultiSiteReadPathTests { // The frozen V15 snapshot **declares** the inverse array; it reads // nothing, and nothing reads it — a snapshot carries stored columns // and no accessors at all.- "AsterismSchemaV15.swift",+ "AsterismSchemaV16.swift", // The reconcilers and the scan, which are *about* the membership // graph and read it whole per pass rather than per row. "DuplicateReconciler.swift", "DuplicateScan.swift", "MembershipReconciler.swift",@@ -208,12 +208,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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swiftindex 3aec10f8..1dc11214 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swift@@ -259,7 +259,7 @@ struct MultiSiteReviewFixTests { @Test("An Entry citing another site's rule is refused before a file exists") func exportGateRefusesACrossSiteEntryCitation() throws { let ruleID = UUID()- let rule = BackupV15URLRule(+ let rule = BackupV16URLRule( id: ruleID, version: 1, isCurrent: true, createdAt: Self.epoch, origin: .readerTaught, definition: .work(locator: .query(name: ExactScalarString("identity"))),@@ -268,12 +268,12 @@ struct MultiSiteReviewFixTests { hostname: "a.example", citations: EntryCitations(chapterSequence: CitedRule(id: ruleID))) - #expect(throws: BackupV15ExportError.self) {+ #expect(throws: BackupV16ExportError.self) { try LibraryRepository.requireCitationsResolve( entries: [entry], memberships: [], titlePatterns: [], urlRules: [rule]) } // Same rule, taught for the Entry's own site: legal.- let sameSite = BackupV15URLRule(+ let sameSite = BackupV16URLRule( id: ruleID, version: 1, isCurrent: true, createdAt: Self.epoch, origin: .readerTaught, definition: .work(locator: .query(name: ExactScalarString("identity"))),@@ -285,7 +285,7 @@ struct MultiSiteReviewFixTests { @Test("A chapter rule taught for another site is refused too") func exportGateRefusesACrossSitePatternCitation() throws { let patternID = UUID()- let pattern = BackupV15TitlePattern(+ let pattern = BackupV16TitlePattern( id: patternID, siteHostname: "b.example", version: 1, isActive: true, createdAt: Self.epoch, definition: StoredPatternDefinition(definition: .wholeTitle))@@ -295,7 +295,7 @@ struct MultiSiteReviewFixTests { chapterTitle: try FieldProvenance( kind: .pattern, patternID: patternID))) - #expect(throws: BackupV15ExportError.self) {+ #expect(throws: BackupV16ExportError.self) { try LibraryRepository.requireCitationsResolve( entries: [entry], memberships: [], titlePatterns: [pattern], urlRules: []) }@@ -303,9 +303,9 @@ struct MultiSiteReviewFixTests { private static func wireEntry( hostname: String, citations: EntryCitations- ) -> BackupV15Entry {+ ) -> BackupV16Entry { let url = "https://\(hostname)/one"- return BackupV15Entry(+ return BackupV16Entry( id: UUID(), captureTitle: "Chapter", captureTitleSource: .host, rawURL: url, canonicalURL: nil, hostname: hostname, entryIdentityKey: url, conservativeIdentityKey: url, identityBasis: .conservative, urlWorkIdentity: nil,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swiftindex fc9458a9..2e1d0332 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift@@ -586,7 +586,7 @@ struct PendingCaptureDrainTests { draft: WorkMetadataDraft( displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],- membership: nil, thumbnail: .keep))+ membership: nil, thumbnail: .keep), calendar: .current) _ = try await fixture.preserve( "https://ex.com/read/1", sharedAt: DrainFixture.shareInstant)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swiftindex ed5eba23..d39eb196 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swift@@ -272,8 +272,8 @@ struct PlaceConvergenceTests { M5SeedPlace(id: Self.harbour, name: "Harbour", note: "quay", workID: Self.workID), ]) - await #expect(throws: BackupV15ExportError.self) {- _ = try await fixture.repository.backupV15Snapshot()+ await #expect(throws: BackupV16ExportError.self) {+ _ = try await fixture.repository.backupV16Snapshot() } withExtendedLifetime(fixture) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swiftindex f917f05a..5446a8fa 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift@@ -213,7 +213,7 @@ struct PostCollapseRedirectTests { displayTitle: "A Serial", typeAssignment: .none, genreTags: ["fantasy"], genericNotes: "reader prose", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) #expect(try library.workRows(id: survivor).map(\.genericNotes) == ["reader prose"])@@ -260,7 +260,7 @@ struct PostCollapseRedirectTests { displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "reader prose", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) #expect(try library.workRows(id: survivor).map(\.genericNotes) == ["reader prose"])@@ -298,7 +298,7 @@ struct PostCollapseRedirectTests { displayTitle: "The Reader's Rename", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) guard case .conflict(.survivorDiverged(_, let survivorID)) = outcome else { Issue.record("expected a diverged survivor, got \(outcome)")@@ -338,7 +338,7 @@ struct PostCollapseRedirectTests { displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "reader prose", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) guard case .conflict(.survivorDiverged(_, let survivorID)) = outcome else { Issue.record("expected a diverged survivor, got \(outcome)")@@ -383,7 +383,7 @@ struct PostCollapseRedirectTests { genericNotes: "", workStatus: .finished, readingStatus: .finished, verdict: "a fine ending", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) let rows = try library.workRows(id: survivor)@@ -414,7 +414,7 @@ struct PostCollapseRedirectTests { displayTitle: "The Reader's Rename", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) #expect(try library.workRows(id: survivor).map(\.displayTitle)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swiftindex 4a5bfd9c..99980334 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swift@@ -97,7 +97,7 @@ struct RecordRowTests { @Test("make(imported:) carries the record, and attach(to: nil) leaves ownership alone") func importedRecordAttaches() async throws { let fixture = try await seeded([])- let record = BackupV15Character(+ let record = BackupV16Character( id: Self.hanna, workID: Self.workID, name: "Hanna", nameKey: "hanna", aliases: ["Hanne"], note: "the lead", facts: [RecordFact(@@ -144,7 +144,7 @@ struct RecordRowTests { #expect(rows.first?.kindRaw == CharacterSuppressionKind.candidate.rawValue) #expect(rows.first?.statusRaw == CharacterSuppressionStatus.active.rawValue) - let imported = CharacterSuppression.make(imported: BackupV15Suppression(+ let imported = CharacterSuppression.make(imported: BackupV16Suppression( id: Self.absent, workID: Self.workID, kindRaw: "fact", nameKey: "bruce", sourceKindRaw: "genericNotes", sourceEntryID: nil, evidence: "he left", statusRaw: "cleared", actionAt: M5Fixture.epoch))
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swiftindex 8c4dc184..38df3527 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swift@@ -19,7 +19,7 @@ import Testing /// /// What that would actually re-enable is asserted here rather than assumed: /// capture would start applying an illegal Site's rules again-/// (`+ReparseCapture.swift:284`, `:396`), and `BackupV15Exporter.swift:41` would+/// (`+ReparseCapture.swift:284`, `:396`), and `BackupV16Exporter.swift:41` would /// stop gating. The four Req 3.4 write-path guards read /// `diagnostics.diagnoses` for `.duplicateSiteRows` (Q41), a class the scan does /// re-derive, so they are the weaker half of the assertion — pinned anyway,@@ -108,7 +108,7 @@ struct RefreshUnionInvariantTests { #expect(await repository.quarantineReason(hostname: tupleHost) != nil) for attempt in 0...2 { if attempt > 0 { try await repository.refreshDiagnostics() }- let payload = try await repository.backupV15Snapshot()+ let payload = try await repository.backupV16Snapshot() // One wire Site per hostname, including the duplicated one and the // rowless one (Q38, Q40). #expect(Set(payload.sites.map(\.hostname))
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swiftindex 2207e690..55b26a91 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift@@ -45,7 +45,7 @@ struct ReleaseDayWritePathTests { id: workID, basis: try library.workBasis(id: workID), // Toggled out of order and with a repeat, which is what a `Set` // iterated into an array can hand the draft.- draft: Self.draft(releaseDays: [.thursday, .monday, .thursday]))+ draft: Self.draft(releaseDays: [.thursday, .monday, .thursday]), calendar: .current) #expect(outcome == .committed) let rows = try library.workRows(id: workID)@@ -77,7 +77,7 @@ struct ReleaseDayWritePathTests { // there, so the draft carries Monday alone. let outcome = try await repository.updateWork( id: workID, basis: try library.workBasis(id: workID),- draft: Self.draft(releaseDays: [.monday]))+ draft: Self.draft(releaseDays: [.monday]), calendar: .current) #expect(outcome == .committed) #expect(try library.workRows(id: workID).allSatisfy { $0.releaseDaysRaw == ["monday"] })@@ -101,7 +101,7 @@ struct ReleaseDayWritePathTests { _ = try await repository.updateWork( id: workID, basis: try library.workBasis(id: workID),- draft: Self.draft(releaseDays: [.thursday, .monday]))+ draft: Self.draft(releaseDays: [.thursday, .monday]), calendar: .current) #expect(try library.workRows(id: workID).allSatisfy { $0.releaseDaysRaw == ["monday", "thursday"]@@ -130,7 +130,7 @@ struct ReleaseDayWritePathTests { // they were editing. _ = try await fixture.repository.updateWork( id: survivor, basis: WorkEditBasis(work: try await fixture.repository.work(id: survivor)),- draft: Self.draft(releaseDays: [.monday, .thursday]))+ draft: Self.draft(releaseDays: [.monday, .thursday]), calendar: .current) func basis(_ days: [ReleaseDay]) -> WorkEditBasis { WorkEditBasis(@@ -143,7 +143,7 @@ struct ReleaseDayWritePathTests { } let refused = try await fixture.repository.updateWork(- id: UUID(), basis: basis([]), draft: Self.draft(releaseDays: [.friday]))+ id: UUID(), basis: basis([]), draft: Self.draft(releaseDays: [.friday]), calendar: .current) #expect(refused.conflict?.survivorID == survivor) #expect(try await fixture.repository.work(id: survivor).releaseDays == [.monday, .thursday])@@ -153,7 +153,7 @@ struct ReleaseDayWritePathTests { // both sides canonicalise before they compare. let committed = try await fixture.repository.updateWork( id: UUID(), basis: basis([.thursday, .monday]),- draft: Self.draft(releaseDays: [.friday]))+ draft: Self.draft(releaseDays: [.friday]), calendar: .current) #expect(committed == .committed) #expect(try await fixture.repository.work(id: survivor).releaseDays == [.friday]) }@@ -193,7 +193,7 @@ struct ReleaseDayWritePathTests { basis: WorkEditBasis(work: try await fixture.repository.work(id: workID)), draft: Self.draft( title: try await fixture.repository.work(id: workID).displayTitle,- releaseDays: [.wednesday]))+ releaseDays: [.wednesday]), calendar: .current) #expect(try await fixture.repository.work(id: workID).releaseDays == [.wednesday]) // A second chapter into the same Work.
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swiftindex 903d0d34..1cbe8d35 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift@@ -176,7 +176,7 @@ struct RepositoryCaptureTests { displayTitle: work.displayTitle, typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .hiatus, readingStatus: .abandoned, verdict: "stopped at 12", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) _ = try await fixture.captureThroughRules( title: "A Serial", rawURL: "https://example.com/read?id=42&chapter=2")@@ -473,7 +473,7 @@ private struct CaptureRepositoryFixture { genreTags: work.genreTags, genericNotes: work.genericNotes, workStatus: work.workStatus, readingStatus: status, verdict: work.verdict, releaseDays: work.releaseDays, membership: work.membership,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swiftindex a1b33088..b87e251d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift@@ -230,7 +230,7 @@ struct RepositoryReShareTests { draft: WorkMetadataDraft( displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],- membership: nil, thumbnail: .keep))+ membership: nil, thumbnail: .keep), calendar: .current) let lookupResult = try await fixture.repository.captureLookup( rawURL: "https://example.com/chapter-1")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swiftindex 6766964d..947908e7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift@@ -347,7 +347,7 @@ struct RepositoryTeachingTests { typeAssignment: .configured(UUID(uuidString: "0E7A0000-0000-4000-8000-0000000000A1")!), genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) save.resetCount() let result = try await fixture.repository.commitTeaching(contract)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swiftindex b8453864..b51a9da1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift@@ -131,7 +131,7 @@ struct RepositoryWorksTests { workStatus: .hiatus, readingStatus: .reading, verdict: "" , releaseDays: [], membership: nil, thumbnail: .keep)- )+ , calendar: .current) let updated = try await fixture.repository.work(id: work.id) let entryAfter = try await fixture.repository.entry(id: entry.id) #expect(updated.displayTitle == "Renamed")@@ -360,7 +360,7 @@ struct RepositoryWorksTests { displayTitle: "Planned", typeAssignment: .none, genreTags: [], genericNotes: "a note the reader typed", workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) let after = try #require(@@ -389,7 +389,7 @@ struct RepositoryWorksTests { genericNotes: "", workStatus: .finished, readingStatus: .finished, verdict: "\n a fine ending\n", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) let updated = try await fixture.repository.work(id: work.id) #expect(updated.workStatus == .finished)@@ -415,7 +415,7 @@ struct RepositoryWorksTests { genreTags: ["x"], genericNotes: "changed", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil, thumbnail: .keep)- )+ , calendar: .current) } await #expect(throws: LibraryRepositoryError.self) { try await fixture.repository.moveEntry(entry.id, to: .newWork(displayTitle: "Should not exist"))@@ -513,7 +513,7 @@ private struct WorksRepositoryFixture { genreTags: work.genreTags, genericNotes: work.genericNotes, workStatus: work.workStatus, readingStatus: status, verdict: work.verdict, releaseDays: work.releaseDays, membership: work.membership,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWriteTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWriteTestSupport.swiftindex c060c245..934c8d7c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWriteTestSupport.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWriteTestSupport.swift@@ -38,9 +38,11 @@ extension LibraryRepository { id: id, basis: EntryEditBasis(entry: snapshot), disclosedVariants: nil)) } - func updateWork(id: UUID, draft: WorkMetadataDraft) async throws {+ func updateWork(+ id: UUID, draft: WorkMetadataDraft, calendar: Calendar = .current+ ) async throws { let basis = WorkEditBasis(work: try await work(id: id))- try Self.require(try await updateWork(id: id, basis: basis, draft: draft))+ try Self.require(try await updateWork(id: id, basis: basis, draft: draft, calendar: calendar)) } func moveEntry(_ entryID: UUID, to destination: WorkDestination) async throws {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swiftindex 97dee16c..7e952df4 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) return try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swiftindex 17f5ccea..28718680 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift@@ -504,7 +504,7 @@ struct SeriesRepositoryTests { genreTags: snapshot.genreTags, genericNotes: snapshot.genericNotes, workStatus: snapshot.workStatus, readingStatus: snapshot.readingStatus, verdict: snapshot.verdict, releaseDays: [], membership: nil,- thumbnail: .keep)) == .committed)+ thumbnail: .keep), calendar: .current) == .committed) #expect(try await fixture.repository.seriesList().map(\.memberCount) == [0]) #expect(try await fixture.repository.deleteSeries(id: seriesID) == .committed)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swiftindex b10dfb12..f3ce470e 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.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 5280bf6a..bcb2569c 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swiftindex 14fdecfc..22638cae 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift@@ -199,17 +199,17 @@ struct StoreMetadataTests { @Test("A conversion still in the write-ahead log is read from the log, not the main file") func uncommittedConversionIsReadFromTheLog() throws { let dir = try TempDir()- try V15RecordedStoreFixture.install(at: dir.storeURL)+ try V16RecordedStoreFixture.install(at: dir.storeURL) #expect(StoreMetadata.recordedVersion(at: dir.storeURL) == .atOrAboveV5, "the premise: the seed is a store the classifier admits")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["15.0.0"])+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["16.0.0"]) let container = try LibraryRepository.openContainer(at: dir.storeURL) _ = ModelContext(container) 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) == ["16.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["17.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")@@ -302,7 +302,7 @@ struct StoreMetadataTests { @Test("The fixture's version reader waits out a closing connection too") func theFixtureReaderWaitsOutAClosingConnection() async throws { let dir = try TempDir()- try V15RecordedStoreFixture.install(at: dir.storeURL)+ try V16RecordedStoreFixture.install(at: dir.storeURL) StoreSettling.foldWriteAheadLog(at: dir.storeURL) let lock = try HeldStoreLock(at: dir.storeURL) @@ -311,7 +311,7 @@ struct StoreMetadataTests { try await Task.sleep(for: Self.lockHold) lock.release() - #expect(try await versions == ["15.0.0"])+ #expect(try await versions == ["16.0.0"]) withExtendedLifetime(dir) {} } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swiftindex 949a3ad6..c64bc11e 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift@@ -30,7 +30,7 @@ struct ThumbnailBytesReachTests { /// The Core sources allowed to name it, and why each one may. /// /// * `Models.swift` — the declaration itself, plus the accessors beside it.- /// * `AsterismSchemaV15.swift` — the frozen snapshot, which **declares** the+ /// * `AsterismSchemaV16.swift` — the frozen snapshot, which **declares** the /// column with its `.externalStorage` attribute and reads nothing: a /// snapshot carries stored columns and no accessors at all. It is on the /// list because a freeze that dropped the attribute would change the@@ -77,7 +77,7 @@ struct ThumbnailBytesReachTests { /// the cost of *not* reading. private static let sanctioned: Set<String> = [ "Models.swift",- "AsterismSchemaV15.swift",+ "AsterismSchemaV16.swift", "GroupOrdering.swift", "Thumbnails/ThumbnailStoreProbe.swift", "LibraryRepository+Thumbnails.swift",
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailIdentityTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailIdentityTests.swiftindex 7a882a8d..40cdc7df 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailIdentityTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailIdentityTests.swift@@ -34,7 +34,7 @@ struct ThumbnailIdentityTests { #expect(ToleratedEnum.read("hexagon") as ThumbnailShape? == nil) } - /// The raw spellings are stored bytes, frozen at V14 (`AsterismSchemaV16`'s+ /// The raw spellings are stored bytes, frozen at V14 (`AsterismSchemaV17`'s /// header), and the pixel sizes are Req 1.2's hard invariant. @Test("ThumbnailShape's raw spellings and pixel sizes are the stored contract") func shapeContract() {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swiftindex ea11c886..63f69cd3 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift@@ -55,8 +55,8 @@ struct ThumbnailStoreProbeTests { let probeNames = Set(ThumbnailStoreProbe.schema.entities.map(\.name)) #expect(probeNames == ["ProbeExternalWork", "ProbeInlineWork"]) - let live = Set(Schema(versionedSchema: AsterismSchemaV16.self).entities.map(\.name))- let frozen = Set(Schema(versionedSchema: AsterismSchemaV15.self).entities.map(\.name))+ let live = Set(Schema(versionedSchema: AsterismSchemaV17.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 2e48a5b3..477cd798 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) container = try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swiftindex 8fe61fc4..3c3dcc85 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift@@ -49,7 +49,8 @@ struct TodayDayPlanTests { } private static func entry(- id: UUID = UUID(), sharedAt: Date, chapterTitle: String? = nil,+ id: UUID = UUID(), sharedAt: Date, capturedAt: Date? = nil,+ chapterTitle: String? = nil, chapterSequence: String? = nil ) -> EntrySnapshot { EntrySnapshot(@@ -57,7 +58,7 @@ struct TodayDayPlanTests { rawURLString: "https://example.test/1", canonicalURLString: nil, hostname: "example.test", entryIdentityKey: "k", identityKeyVersion: 1, chapterTitle: chapterTitle, chapterTitleProvenance: .absent, note: "",- rating: nil, firstCapturedAt: sharedAt, lastSharedAt: sharedAt,+ rating: nil, firstCapturedAt: capturedAt ?? sharedAt, lastSharedAt: sharedAt, modifiedAt: sharedAt, workID: nil, workAssignmentProvenance: .absent, intentionallyUnattached: false, chapterSequence: chapterSequence) }@@ -67,7 +68,7 @@ struct TodayDayPlanTests { hostname: String = "example.test", releaseDays: [ReleaseDay] = [.thursday], workStatus: WorkStatus = .ongoing, readingStatus: ReadingStatus = .reading,- entries: [EntrySnapshot] = []+ entries: [EntrySnapshot] = [], catchUp: CatchUpRecord = .pristine ) -> WorkSnapshot { WorkSnapshot( id: id, displayTitle: title, lastParsedTitle: nil,@@ -75,7 +76,7 @@ struct TodayDayPlanTests { genericNotes: "", genreTags: [], titleProvenance: .parsed, createdAt: .distantPast, modifiedAt: .distantPast, entries: entries, workStatus: workStatus, readingStatus: readingStatus,- releaseDays: releaseDays)+ releaseDays: releaseDays, catchUp: catchUp) } private static func presentationRow(id: UUID = UUID(), sharedAt: Date)@@ -483,7 +484,7 @@ struct TodayDayPlanTests { let schedule = TodaySchedule.build( works: [ Self.work(id: Self.id(1), title: "Behind", releaseDays: [.thursday],- readingStatus: .catchingUp)+ workStatus: .hiatus, readingStatus: .catchingUp) ], calendar: calendar) @@ -497,6 +498,7 @@ struct TodayDayPlanTests { #expect(plan.releases.isEmpty) #expect(plan.catchingUp.map(\.title) == ["Behind"])+ #expect(plan.catchingUp.first?.workStatus == .hiatus) } // MARK: - To read (`to-read` Req 4.1, 4.2)@@ -635,7 +637,7 @@ struct TodayDayPlanTests { /// Q13: the row shape and the second-line rule are the release row's, not a /// parallel copy — so all three arms of Req 5.2 read on a catch-up row /// exactly as they do on a release, measured against the selected day.- @Test("A catch-up row's second line reads as a release row's")+ @Test("A catch-up row with R uses the read day in its unknown line") func catchUpRowsTakeTheReleaseLine() { let calendar = Self.calendar() let schedule = TodaySchedule.build(@@ -665,8 +667,8 @@ struct TodayDayPlanTests { #expect(plan.catchingUp.map(\.title) == ["Never noted", "Noted before", "Noted today"]) #expect(plan.catchingUp.map(\.line) == [ .notNotedYet,- .lastNoted(chapterLine: "Ch. 40", when: .yesterday),- .notedOnDay(chapterLine: "Ch. 41"),+ .lastNoted(chapterLine: "40", when: .yesterday),+ .lastNoted(chapterLine: "41", when: .date(Self.thursday)), ]) } @@ -854,7 +856,7 @@ struct TodayDayPlanTests { #expect(plan.releases.first?.primaryURL == URL(string: "https://example.test/fiction/1")) } - @Test("A past day's release row takes its chapter from notes up to that day")+ @Test("A past row keeps its historical line but its badge uses the current R") func pastDayIgnoresLaterNotes() { let calendar = Self.calendar() // Noted chapter 30 on Wednesday 4 March and chapter 31 on Wednesday@@ -868,11 +870,80 @@ struct TodayDayPlanTests { schedule: TodaySchedule.build(works: [work], calendar: calendar), presentation: Self.presentation([], calendar: calendar), calendar: calendar) - #expect(plan.releases.first?.lastChapter == 30)- #expect(plan.releases.first?.nextChapter == 31)+ #expect(plan.releases.first?.lastChapter == 31)+ #expect(plan.releases.first?.nextChapter == 32) #expect(plan.releases.first?.lastNotedDay == Self.day(2026, 3, 4)) } + @Test("An override sets the badge's R and a re-share does not move its read day")+ func overrideDrivesTheBadge() {+ let calendar = Self.calendar()+ let yesterday = Self.instant(2026, 3, 11)+ let record = CatchUpRecord(+ confirmation: CatchUpConfirmation(+ latest: 12, confirmedAtMilliseconds: MillisecondInstant.milliseconds(yesterday),+ countsUp: false, isEstimate: false),+ override: .value(8, atMilliseconds: MillisecondInstant.milliseconds(yesterday)))+ let work = Self.work(readingStatus: .catchingUp, entries: [+ Self.entry(+ sharedAt: Self.instant(2026, 3, 12), capturedAt: yesterday,+ chapterSequence: "3"),+ ], catchUp: record)+ let plan = TodayDayPlan.build(+ day: Self.thursday, currentDay: Self.thursday,+ schedule: TodaySchedule.build(works: [work], calendar: calendar),+ presentation: Self.presentation([], calendar: calendar), calendar: calendar)++ #expect(plan.catchingUp.first?.progress.state == .exact)+ #expect(plan.catchingUp.first?.progress.lastRead == 8)+ #expect(plan.catchingUp.first?.progress.readDay == Self.day(2026, 3, 11))+ #expect(plan.catchingUp.first?.lastChapter == 8)+ #expect(plan.catchingUp.first?.nextChapter == 9)+ }++ @Test("Unknown catch-up wording uses R and its read day even without a note")+ func unknownLineUsesTheOverride() {+ let calendar = Self.calendar()+ let yesterday = Self.instant(2026, 3, 11)+ let record = CatchUpRecord(+ confirmation: nil,+ override: .value(7, atMilliseconds: MillisecondInstant.milliseconds(yesterday)))+ let work = Self.work(+ readingStatus: .catchingUp, entries: [], catchUp: record)+ let plan = TodayDayPlan.build(+ day: Self.thursday, currentDay: Self.thursday,+ schedule: TodaySchedule.build(works: [work], calendar: calendar),+ presentation: Self.presentation([], calendar: calendar), calendar: calendar)++ #expect(plan.catchingUp.first?.progress.state == .unknown)+ #expect(plan.catchingUp.first?.line == .lastNoted(chapterLine: "7", when: .yesterday))+ #expect(plan.catchingUp.first?.lastNotedDay == Self.day(2026, 3, 11))+ #expect(plan.catchingUp.first?.releasesSince == 1)+ }++ @Test("A future day's row derives its estimate for that day")+ func futureDayProgressCountsItsReleases() {+ let calendar = Self.calendar()+ let yesterday = Self.instant(2026, 3, 11)+ let record = CatchUpRecord(+ confirmation: CatchUpConfirmation(+ latest: 10, confirmedAtMilliseconds: MillisecondInstant.milliseconds(yesterday),+ countsUp: true, isEstimate: false),+ override: .value(4, atMilliseconds: MillisecondInstant.milliseconds(yesterday)))+ let work = Self.work(readingStatus: .catchingUp, entries: [], catchUp: record)+ let schedule = TodaySchedule.build(works: [work], calendar: calendar)+ func row(on day: CivilDay) -> ReleaseRow? {+ TodayDayPlan.build(+ day: day, currentDay: Self.thursday, schedule: schedule,+ presentation: Self.presentation([], calendar: calendar), calendar: calendar)+ .catchingUp.first+ }++ #expect(row(on: Self.thursday)?.progress.effectiveLatest == 11)+ #expect(row(on: Self.thursday.adding(days: 7, calendar: calendar))?.progress.effectiveLatest == 12)+ #expect(row(on: Self.thursday.adding(days: 7, calendar: calendar))?.progress.state == .estimated)+ }+ @Test("A release row carries no release count; only catch-up rows do") func releaseRowsCountNothing() { let calendar = Self.calendar()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayFixtureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayFixtureTests.swiftindex 864ce547..898831a1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayFixtureTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayFixtureTests.swift@@ -15,6 +15,34 @@ import Testing @Suite("The today fixture's backdating seam", .serialized) struct TodayFixtureTests { + @Test("The fixture writer seeds exact, estimated and caught-up values with past moments")+ func catchUpFixtureStates() async throws {+ let now = Date(timeIntervalSince1970: 1_800_000_000)+ let confirmedAt = now.addingTimeInterval(-86_400)+ let fixture = try await TodayFixtureLibrary(clock: FixedRepositoryClock(now))+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(identifier: "UTC")!+ let day = CivilDay(now, calendar: calendar)+ let cases: [(String, Int, Int, Bool, CatchUpProgress.State)] = [+ ("Frost Relay", 10, 6, false, .exact),+ ("Copper Atlas", 10, 6, true, .estimated),+ ("Harbor Signal", 8, 8, false, .caughtUp),+ ]+ for (title, latest, read, estimate, expected) in cases {+ let work = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: title, hostname: "today.test"))+ try await fixture.repository.seedCatchUpFixture(+ workID: work.id, latest: latest, confirmedAt: confirmedAt,+ isEstimate: estimate,+ override: .value(read, atMilliseconds: MillisecondInstant.milliseconds(confirmedAt)))+ let snapshot = try await fixture.repository.work(id: work.id)+ #expect(snapshot.catchUp.confirmation?.confirmedAtMilliseconds+ == MillisecondInstant.milliseconds(confirmedAt))+ #expect(snapshot.catchUp.override != nil)+ #expect(CatchUpProgress.build(work: snapshot, day: day, calendar: calendar).state == expected)+ }+ }+ /// Req 5.5 needs a noted day that is not the current one, and both of an /// Entry's reader-facing dates have to move together or the row breaks the /// `firstCapturedAt <= lastSharedAt` invariant every other fixture keeps.
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swiftindex 5b653551..5e229490 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift@@ -890,7 +890,7 @@ struct URLOptionalSequenceReconcilerTests { @Suite("Optional chapter sequence — archive") struct URLOptionalSequenceArchiveTests { - private static func combinedRule(of payload: BackupV15Payload) throws -> URLTwoFieldTemplate? {+ private static func combinedRule(of payload: BackupV16Payload) throws -> URLTwoFieldTemplate? { guard case .combined(_, let template) = try #require(payload.urlRules.first).definition else { return nil }@@ -903,12 +903,12 @@ struct URLOptionalSequenceArchiveTests { /// so this asserts the asymmetric `Codable` from the reading side. @Test("A pre-feature archive decodes, and its combined rule is still required") func preFeatureArchiveDecodes() throws {- let document = BackupV15Fixtures.sequencePresenceOmittedDocument()+ let document = BackupV16Fixtures.sequencePresenceOmittedDocument() #expect(!String(decoding: document, as: UTF8.self).contains("sequencePresence")) - let decoded = try BackupV15Codec.decode(document)+ let decoded = try BackupV16Codec.decode(document) - #expect(decoded.payload == BackupV15Fixtures.combinedRulePayload(presence: .required))+ #expect(decoded.payload == BackupV16Fixtures.combinedRulePayload(presence: .required)) #expect(try Self.combinedRule(of: decoded.payload)?.sequencePresence == .required) } @@ -917,17 +917,17 @@ struct URLOptionalSequenceArchiveTests { /// this feature would produce — which is what keeps it importable there. @Test("An archive with no declared-optional rule encodes the pre-feature bytes") func requiredArchiveIsByteIdenticalToPreFeature() throws {- let encoded = try BackupV15Codec.encode(- payload: BackupV15Fixtures.combinedRulePayload(presence: .required),- metadata: BackupV15Metadata(- appBuild: "pre-feature", exportedAt: BackupV15Fixtures.created))+ let encoded = try BackupV16Codec.encode(+ payload: BackupV16Fixtures.combinedRulePayload(presence: .required),+ metadata: BackupV16Metadata(+ appBuild: "pre-feature", exportedAt: BackupV16Fixtures.created)) let json = String(decoding: encoded, as: UTF8.self) #expect(!json.contains("sequencePresence")) #expect(- json.contains(BackupV15Fixtures.sequencePresenceOmittedPayloadJSON),+ json.contains(BackupV16Fixtures.sequencePresenceOmittedPayloadJSON), "the exported payload is no longer the pre-feature payload")- #expect(encoded == BackupV15Fixtures.sequencePresenceOmittedDocument())+ #expect(encoded == BackupV16Fixtures.sequencePresenceOmittedDocument()) } /// Req 5.4: a declared-optional rule survives export and import unchanged. The@@ -935,17 +935,17 @@ struct URLOptionalSequenceArchiveTests { /// `URLRulePattern` a reader would end up with, not merely a decoded value. @Test("A declared-optional rule round-trips through export and import") func optionalRuleRoundTripsThroughTheArchive() throws {- let payload = BackupV15Fixtures.combinedRulePayload(presence: .optional)- let encoded = try BackupV15Codec.encode(+ let payload = BackupV16Fixtures.combinedRulePayload(presence: .optional)+ let encoded = try BackupV16Codec.encode( payload: payload,- metadata: BackupV15Metadata(appBuild: "with-feature", exportedAt: BackupV15Fixtures.created))+ metadata: BackupV16Metadata(appBuild: "with-feature", exportedAt: BackupV16Fixtures.created)) #expect(String(decoding: encoded, as: UTF8.self).contains(#""sequencePresence":"optional""#)) - let decoded = try BackupV15Codec.decode(encoded)+ let decoded = try BackupV16Codec.decode(encoded) #expect(decoded.payload == payload) #expect(try Self.combinedRule(of: decoded.payload)?.sequencePresence == .optional) - let schema = Schema(versionedSchema: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swiftindex c4946a8a..2da3ebe0 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swift@@ -136,9 +136,9 @@ struct UnknownSiteModeTests { let repository = try await root.openForApp() do {- _ = try await repository.backupV15Snapshot()+ _ = try await repository.backupV16Snapshot() Issue.record("expected the export to refuse a Site whose mode has no case")- } catch let error as BackupV15ExportError {+ } catch let error as BackupV16ExportError { guard case .unrepresentableValue(let record, let field, let value) = error else { Issue.record("expected .unrepresentableValue, got \(error)") await repository.shutdown()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V15RecordedStoreFixture.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreFixture.swiftsimilarity index 79%rename from Packages/AsterismCore/Tests/AsterismCoreTests/V15RecordedStoreFixture.swiftrename to Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreFixture.swiftindex 7cc4f3aa..18b59360 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V15RecordedStoreFixture.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreFixture.swift@@ -3,85 +3,12 @@ import SwiftData @testable import AsterismCore -/// A store genuinely **recorded at 15.0.0**, seeded in-process through the-/// frozen `AsterismSchemaV15` snapshot — the library a device that ran the V15-/// build holds on the morning of the V16 update.-///-/// It succeeds `V5`/`V6`/…/`V14RecordedStoreFixture`, each of which went with-/// the stage that named it — V14's in this feature's freeze commit, once every-/// device was confirmed on marker `"15"` (`remove-article-mode` Q10, confirmed-/// 2026-09-21). It is now the only convertible-/// fixture in the package; anything older than V15 fails closed.-///-/// Seeding through the snapshot rather than committing a `.sqlite` is what the-/// nesting buys: a container over `AsterismSchemaV15` records 15.0.0 in the-/// store's own metadata, and the fixture cannot drift out of sync with the-/// snapshot it is built from.-///-/// **`Site.junkSuffixRule` is seeded non-nil, and it is the point of this-/// fixture at V16.** V16 is the first *removing* stage since V8 → V9, so what-/// has to be observed is a populated column disappearing without taking-/// anything else with it: the seeded rule is a real `JunkSuffixRule` with two-/// anchors, written through the frozen snapshot, and on the far side of the-/// stage the live `Site` has no such property to read at all. That the column-/// is gone from the schema rather than merely nil is `ModelContractTests`'-/// delta pin; what `V15RecordedStoreTests` adds is that every other row and-/// field came through the removal unchanged.-///-/// Every column V15 *does* have is seeded away from its default for the-/// converse reason, `Work.releaseDaysRaw` included — V15's own addition, seeded-/// with two days rather than left at `[]`, so a removing stage that disturbed a-/// neighbouring column would show here. The three thumbnail columns are seeded-/// too, one of them the schema's only external-storage attribute: the bytes-/// are a small opaque blob rather than a real JPEG — every thumbnail state is-/// tolerated (`work-thumbnails` Req 1.8, Req 9.4), and what is asserted on the-/// far side is that the three columns crossed unchanged, not that they decode.-///-/// V13's two tables are seeded for the same reason: one `Place` naming the Work-/// the fixture holds, and one `PlaceSuppression` in the candidate shape.-///-/// The rest of the inventory is the retired `V14RecordedStoreFixture`'s, carried-/// forward unchanged: one row per entity,-/// **except `Entry`, which gets three, and `TitlePattern`, which gets two**.-/// Entry A carries the v2 identity arm and the URL-rule work assignment, Entry B-/// the v3 arm and the pattern assignment, and **Entry C carries no citation blob-/// at all** — the row a share extension wrote before the blob existed, which-/// reads as the default and is *reported* rather than quarantined (Q6, Q25 of-/// `drop-superseded-columns`). The second title rule is the retired segment arm,-/// so the `definitionData` blob is exercised on both arms.-///-/// V7's and V8's tables ride through untouched, which is exactly why a-/// `Character` with a fact, a `CharacterSuppression` and a `WorkDistinctPair`-/// are seeded: a stage that lost a table nobody reads would otherwise be found-/// on the owner's phone.-///-/// ## Registry ordering: why seeding through a frozen snapshot is safe here-///-/// SwiftData keeps a **process-global, entity-name-keyed** registry, so a-/// container over this snapshot and a container over the live schema both claim-/// "Site", "Entry", … (`docs/agent-notes/schema-migration.md`; Q29 of-/// `drop-superseded-columns`, where a scratch container over the snapshot-/// aborted the whole test process with `NSUnknownKeyException` on `Site.works`).-///-/// What keeps this fixture out of that is **ordering, not luck**: `write(at:)`-/// **creates** the snapshot container, **seeds** through it, **saves** and-/// **releases** it before returning, and every caller opens the live container-/// only afterwards. The two are therefore never *in use* at the same time, which-/// is the condition that breaks — Q29's call site built its scratch container-/// while a live one was already open. `make test-core` passes `--no-parallel`,-/// which is what extends that guarantee across suites; dropping it would put-/// another suite's live container in use while this one holds the registration,-/// and the package would abort rather than fail a test.-///-/// **The ordering is still the thing holding it up**, even though V16 is the-/// first version since V9 whose live stored shape is a strict *subset* of the-/// frozen one — a removing stage leaves no live key a stale snapshot-/// registration could fail to answer. That subset relation is a second net, not-/// a replacement: the frozen registration can still answer `junkSuffixRule`,-/// which the live schema has no column for, and the next adding version loses-/// the subset again. The create-seed-save-release ordering below is what is-/// relied on.-enum V15RecordedStoreFixture {+/// Builds a populated store recorded at V16 through the frozen snapshot.+/// The seed saves and releases its container before any V17 open so SwiftData's+/// global entity registry does not mix the two versions. Existing fields are+/// seeded away from defaults to catch accidental migration changes; the two+/// new V17 blob columns are absent from this snapshot by construction.+enum V16RecordedStoreFixture { static let hostname = "frozen15.example" static let siteDisplayName = "Frozen Fifteen" static let patternID = UUID(uuidString: "22222222-2222-2222-2222-00000000000e")!@@ -271,21 +198,6 @@ enum V15RecordedStoreFixture { } } - /// The Site's `junkSuffixRule` — the column **V16 removes**, seeded non-nil- /// so the removal has something real to remove. It is the one composite- /// `Codable` value `Site` ever carried, and after the stage the live class- /// has no such property at all: `ModelContractTests` pins the column's- /// absence from the schema, and this suite pins that nothing else went with- /// it.- static var siteJunkSuffixRule: JunkSuffixRule {- get throws {- try JunkSuffixRule(- version: 3,- anchors: [try SegmentPositionSpec(origin: .end, offset: 1),- try SegmentPositionSpec(origin: .end, offset: 0)])- }- }- /// The URL rule the fixture seeds, as the live type sees it. static var urlRuleDefinition: URLRuleDefinition { .workAndSequence(@@ -335,7 +247,7 @@ enum V15RecordedStoreFixture { static func write(at storeURL: URL, seed: (ModelContext) throws -> Void) throws { try FileManager.default.createDirectory( at: storeURL.deletingLastPathComponent(), withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV15.self)+ let schema = Schema(versionedSchema: AsterismSchemaV16.self) let configuration = ModelConfiguration( // The same store-configuration name `openContainer` uses; a mismatch // here would make the reopen create a second store.@@ -386,15 +298,14 @@ enum V15RecordedStoreFixture { let v3Key = try entryBIdentityKey try write(at: storeURL) { context in- let site = AsterismSchemaV15.Site()+ let site = AsterismSchemaV16.Site() site.hostname = hostname site.displayName = siteDisplayName site.modeRaw = SiteMode.taught.rawValue- site.junkSuffixRule = try siteJunkSuffixRule context.insert(site) // The phrase arm, in the blob that has been its only home since V9.- let pattern = AsterismSchemaV15.TitlePattern()+ let pattern = AsterismSchemaV16.TitlePattern() pattern.id = patternID pattern.version = patternVersion pattern.isActive = true@@ -405,7 +316,7 @@ enum V15RecordedStoreFixture { // The retired segment arm. Inactive: a taught Site holds exactly one // active title rule.- let segmentPattern = AsterismSchemaV15.TitlePattern()+ let segmentPattern = AsterismSchemaV16.TitlePattern() segmentPattern.id = segmentPatternID segmentPattern.version = segmentPatternVersion segmentPattern.isActive = false@@ -414,7 +325,7 @@ enum V15RecordedStoreFixture { context.insert(segmentPattern) segmentPattern.site = site - let rule = AsterismSchemaV15.URLRulePattern()+ let rule = AsterismSchemaV16.URLRulePattern() rule.id = urlRuleID rule.version = urlRuleVersion rule.isCurrent = true@@ -426,7 +337,7 @@ enum V15RecordedStoreFixture { context.insert(rule) rule.site = site - let type = AsterismSchemaV15.WorkTypeEntity()+ let type = AsterismSchemaV16.WorkTypeEntity() type.id = workTypeID type.name = workTypeName type.stateRaw = WorkTypeState.active.rawValue@@ -440,7 +351,7 @@ enum V15RecordedStoreFixture { // default — the three thumbnail ones and V15's own // `releaseDaysRaw` included — so a removing stage that disturbed a // neighbouring column would show up rather than read as a pass.- let work = AsterismSchemaV15.Work()+ let work = AsterismSchemaV16.Work() work.id = workID work.displayTitle = workName work.lastParsedTitle = workName@@ -465,7 +376,7 @@ enum V15RecordedStoreFixture { // The Work's site presence: since V9 the membership row is the only // home it has. It cites its identity rule by UUID alone (Req 10.4, // Q28 of `multi-site-works`), which is why no version travels with it.- let membership = AsterismSchemaV15.WorkSiteMembership()+ let membership = AsterismSchemaV16.WorkSiteMembership() membership.id = membershipID membership.hostname = hostname membership.createdAt = timestamp@@ -479,7 +390,7 @@ enum V15RecordedStoreFixture { membership.site = site // Entry A: the v2 identity arm and URL-rule work assignment.- let entryA = AsterismSchemaV15.Entry()+ let entryA = AsterismSchemaV16.Entry() entryA.id = entryAID entryA.captureTitle = entryACaptureTitle entryA.captureTitleSourceRaw = CaptureTitleSource.host.rawValue@@ -504,7 +415,7 @@ enum V15RecordedStoreFixture { entryA.site = site // Entry B: the v3 identity arm and the pattern work assignment.- let entryB = AsterismSchemaV15.Entry()+ let entryB = AsterismSchemaV16.Entry() entryB.id = entryBID entryB.captureTitle = entryBCaptureTitle entryB.captureTitleSourceRaw = CaptureTitleSource.host.rawValue@@ -527,7 +438,7 @@ enum V15RecordedStoreFixture { // Entry C: **no citation blob**. It keeps its Work link — the // assignment provenance is what a V8 build never wrote, the // relationship is not (Q25 of `drop-superseded-columns`).- let entryC = AsterismSchemaV15.Entry()+ let entryC = AsterismSchemaV16.Entry() entryC.id = entryCID entryC.captureTitle = entryCCaptureTitle entryC.captureTitleSourceRaw = CaptureTitleSource.host.rawValue@@ -550,7 +461,7 @@ enum V15RecordedStoreFixture { // assert it: a stage that lost one would surface as duplicate Works // the reader has already told the app are distinct. let pairIDs = WorkDistinctPair.sortedIDs(workID, distinctPairOtherWorkID)- let pair = AsterismSchemaV15.WorkDistinctPair()+ let pair = AsterismSchemaV16.WorkDistinctPair() pair.id = distinctPairID pair.lowerWorkID = pairIDs.lower pair.higherWorkID = pairIDs.higher@@ -559,7 +470,7 @@ enum V15RecordedStoreFixture { // V11's two tables, carried forward from the retired fixture. The // series row is the one `Work.seriesID` names.- let series = AsterismSchemaV15.Series()+ let series = AsterismSchemaV16.Series() series.id = seriesID series.name = seriesName series.notes = seriesNotes@@ -568,7 +479,7 @@ enum V15RecordedStoreFixture { context.insert(series) let linkIDs = WorkDistinctPair.sortedIDs(workID, linkOtherWorkID)- let link = AsterismSchemaV15.WorkLink()+ let link = AsterismSchemaV16.WorkLink() link.id = linkID link.lowerWorkID = linkIDs.lower link.higherWorkID = linkIDs.higher@@ -580,7 +491,7 @@ enum V15RecordedStoreFixture { // V12's three tables, seeded so the stage has something to carry // across rather than three more empty tables that would pass either // way. The role is a fourth beside the three the app seeds.- let creator = AsterismSchemaV15.Creator()+ let creator = AsterismSchemaV16.Creator() creator.id = creatorID creator.name = creatorName creator.notes = creatorNotes@@ -592,7 +503,7 @@ enum V15RecordedStoreFixture { creator.stateModifiedAt = timestamp context.insert(creator) - let role = AsterismSchemaV15.CreatorRole()+ let role = AsterismSchemaV16.CreatorRole() role.id = creatorRoleID role.name = creatorRoleName role.position = creatorRolePosition@@ -604,7 +515,7 @@ enum V15RecordedStoreFixture { role.stateModifiedAt = timestamp context.insert(role) - let credit = AsterismSchemaV15.WorkCredit()+ let credit = AsterismSchemaV16.WorkCredit() credit.id = creditID credit.workID = workID credit.creatorID = creatorID@@ -613,7 +524,7 @@ enum V15RecordedStoreFixture { credit.modifiedAt = timestamp context.insert(credit) - let character = AsterismSchemaV15.Character()+ let character = AsterismSchemaV16.Character() character.id = characterID character.name = characterName character.nameKey = characterNameKey@@ -625,7 +536,7 @@ enum V15RecordedStoreFixture { context.insert(character) character.work = work - let suppression = AsterismSchemaV15.CharacterSuppression()+ let suppression = AsterismSchemaV16.CharacterSuppression() suppression.id = suppressionID suppression.kindRaw = CharacterSuppressionKind.candidate.rawValue suppression.nameKey = suppressionNameKey@@ -641,7 +552,7 @@ enum V15RecordedStoreFixture { // across rather than two more empty tables that would pass either // way. Both address their work by column, which is the shape every // table added since V7 has taken.- let place = AsterismSchemaV15.Place()+ let place = AsterismSchemaV16.Place() place.id = placeID place.name = placeName place.nameKey = placeNameKey@@ -653,7 +564,7 @@ enum V15RecordedStoreFixture { place.workID = workID context.insert(place) - let placeSuppression = AsterismSchemaV15.PlaceSuppression()+ let placeSuppression = AsterismSchemaV16.PlaceSuppression() placeSuppression.id = placeSuppressionID placeSuppression.workID = workID placeSuppression.kindRaw = CharacterSuppressionKind.candidate.rawValue
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V15RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swiftsimilarity index 90%rename from Packages/AsterismCore/Tests/AsterismCoreTests/V15RecordedStoreTests.swiftrename to Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swiftindex 5f95bee6..da95e96c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V15RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift@@ -4,51 +4,26 @@ import Testing @testable import AsterismCore -/// The V15 → V16 conversion, over a store genuinely **recorded at 15.0.0**.-///-/// This is the path every installed library takes on the update that ships-/// `remove-article-mode`: the store on disk was written by the V15 classes, and-/// `ModelContainer.init` runs the plan's one lightweight stage on the way in.-/// Every other store a test builds is born at 16.0.0, so a regression here would-/// otherwise only be visible on the owner's phone.-///-/// **This stage removes exactly one column**, `Site.junkSuffixRule`, and adds-/// nothing (Req 4.1). It is the first removing stage since V8 → V9, which-/// changes what there is to assert: a removed column has no attribute default-/// to land and no data pass behind it, so there is no "did the default arrive"-/// question at all. The fixture seeds the column with a real two-anchor-/// `JunkSuffixRule`, and on the far side the live `Site` has no such property-/// to read.-///-/// The assertions are therefore in two halves. The first is that the column is-/// gone from the **schema** rather than merely nil on the row — which is-/// `ModelContractTests`' delta pin, not this suite's, because a value read-/// through an absent property does not compile. The second is this suite's-/// whole job: that nothing else moved. The live library, field by field,-/// exactly as the retired `V14RecordedStoreTests` asserted it one generation-/// back — the status columns, the series columns, **V14's three thumbnail-/// columns**, **V15's `releaseDaysRaw`**, V12's creator, role and credit rows-/// and V13's place and place-suppression rows included, all of which this-/// fixture seeds away from their defaults precisely so a removing stage that-/// disturbed a neighbour would show.-@Suite("A 15.0.0-recorded store under the V16 plan", .serialized)-struct V15RecordedStoreTests {-- private typealias Fixture = V15RecordedStoreFixture+/// V16 → V17 over a populated V16-recorded store. The stage adds two+/// optional Work blobs and leaves all existing rows and fields intact.+@Suite("A 16.0.0-recorded store under the V17 plan", .serialized)+struct V16RecordedStoreTests {++ private typealias Fixture = V16RecordedStoreFixture /// A library exactly as a V15 build leaves it: the store recorded at- /// 15.0.0 with a populated junk-suffix rule, and the marker at `"15"`.+ /// 15.0.0 with a populated junk-suffix rule, and the marker at `"16"`. private final class Root { let url: URL let configuration: LibraryConfiguration init() throws { url = FileManager.default.temporaryDirectory.appending(- path: "V15Recorded-\(UUID())", directoryHint: .isDirectory)+ path: "V16Recorded-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) configuration = LibraryConfiguration(rootDirectory: url) try Fixture.install(at: configuration.storeURL)- try Data("15\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic)+ try Data("16\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic) } deinit { try? FileManager.default.removeItem(at: url) }@@ -63,20 +38,20 @@ struct V15RecordedStoreTests { } } - @Test("The seeded store really is recorded at 15.0.0, on the lagging marker")- func seedIsRecordedAtFifteenZeroZero() throws {+ @Test("The seeded store is recorded at 16.0.0 on the lagging marker")+ func seedIsRecordedAtSixteenZeroZero() throws { let root = try Root()- #expect(try root.recordedVersions() == ["15.0.0"])- #expect(try root.markerText() == "15")+ #expect(try root.recordedVersions() == ["16.0.0"])+ #expect(try root.markerText() == "16") #expect(try LibraryRepository.classify(root.configuration, fileManager: .default)- == .markerLagging(generation: "15"))+ == .markerLagging(generation: "16")) withExtendedLifetime(root) {} } /// The whole of it: `openForApp` runs the stage, validates, publishes- /// `"16"`, and every live row is still there afterwards with its value —+ /// `"17"`, and every live row is still there afterwards with its value — /// minus one column on the Site, which no longer exists to read.- @Test("openForApp converts to 16.0.0, dropping one Site column")+ @Test("openForApp converts to 17.0.0, adding two nil Work blobs") func convertsWithEveryLiveRowIntact() async throws { let root = try Root() let (result, repository) = try await LibraryRepository.openForApp(root.configuration)@@ -88,8 +63,8 @@ struct V15RecordedStoreTests { return } // The stage completed and the marker moved, in that order.- #expect(try root.recordedVersions() == ["16.0.0"])- #expect(try root.markerText() == "16")+ #expect(try root.recordedVersions() == ["17.0.0"])+ #expect(try root.markerText() == "17") #expect(counts.works == 1) #expect(counts.entries == 3) #expect(counts.sites == 1)@@ -98,24 +73,14 @@ struct V15RecordedStoreTests { let facts = try await repository.withLockedContext( mode: .shared, operation: "reading the converted library"- ) { context in try ConvertedV16Library(context: context) }+ ) { context in try ConvertedV17Library(context: context) } await repository.shutdown() - // MARK: what the stage removed — the point of the whole suite- //- // One column on `Site`, and nothing else. The fixture seeded it with a- // real two-anchor rule; there is deliberately no assertion here that it- // reads nil, because the live class has no `junkSuffixRule` property to- // read and an attempt would not compile. That *is* the assertion, and- // `ModelContractTests` states it over the schema — V16's `Site` is- // V15's minus exactly this column.- //- // What can be asserted here is the other half: that the removal took- // nothing with it. V15's own `releaseDaysRaw` is the nearest- // neighbour, seeded non-empty precisely so a disturbed column would- // show, and it is read **raw** as well as through the accessor.+ // Existing data survives, while the two arriving raw columns are nil. #expect(facts.releaseDaysRaw == Fixture.releaseDaysRaw) #expect(facts.releaseDays == Fixture.releaseDays)+ #expect(facts.catchUpConfirmationData == nil)+ #expect(facts.lastChapterOverrideData == nil) // MARK: V14's three columns, which this stage may not touch. The // fixture seeds all three away from nil — the bytes included, which@@ -390,7 +355,7 @@ struct V15RecordedStoreTests { } /// The extension is what the marker keeps out of the stage (Req 9.3): it- /// refuses `"15"`, and opens the same library once the app has moved it.+ /// refuses `"16"`, and opens the same library once the app has moved it. @Test("The extension refuses the store until the app has converted it") func extensionOpensOnlyAfterTheApp() async throws { let root = try Root()@@ -400,7 +365,7 @@ struct V15RecordedStoreTests { reason: "Open Asterism to finish updating the library")) { try await LibraryRepository.openForExtension(root.configuration) }- #expect(try root.recordedVersions() == ["15.0.0"],+ #expect(try root.recordedVersions() == ["16.0.0"], "the refusal has to land before ModelContainer.init converts the store") let (_, app) = try await LibraryRepository.openForApp(root.configuration)@@ -427,8 +392,8 @@ struct V15RecordedStoreTests { #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready) let (_, second) = try await LibraryRepository.openForApp(root.configuration) await second.shutdown()- #expect(try root.markerText() == "16")- #expect(try root.recordedVersions() == ["16.0.0"])+ #expect(try root.markerText() == "17")+ #expect(try root.recordedVersions() == ["17.0.0"]) withExtendedLifetime(root) {} } }@@ -438,7 +403,7 @@ struct V15RecordedStoreTests { /// Everything the converted store holds, read once inside the locked context. /// Model classes are not `Sendable` and may not leave the actor, so the whole /// comparison is done against copies.-private struct ConvertedV16Library: Sendable {+private struct ConvertedV17Library: Sendable { struct EntryFacts: Sendable { let captureTitle: String let captureTitleSource: CaptureTitleSource@@ -610,6 +575,8 @@ private struct ConvertedV16Library: Sendable { /// the accessor is read beside it only to show the two agree. let releaseDaysRaw: [String] let releaseDays: [ReleaseDay]+ let catchUpConfirmationData: Data?+ let lastChapterOverrideData: Data? let memberships: [MembershipFacts] let entries: [UUID: EntryFacts]@@ -680,6 +647,8 @@ private struct ConvertedV16Library: Sendable { thumbnailIdentity = work.thumbnailIdentity releaseDaysRaw = work.releaseDaysRaw releaseDays = work.releaseDays+ catchUpConfirmationData = work.catchUpConfirmationData+ lastChapterOverrideData = work.lastChapterOverrideData series = try context.fetch(FetchDescriptor<Series>()) .sorted { $0.id.uuidString < $1.id.uuidString } .map {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V4RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V4RecordedStoreTests.swiftindex 426da851..9b79507a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V4RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V4RecordedStoreTests.swift@@ -9,13 +9,13 @@ import Testing /// /// Nothing on this branch can write one any more: the live classes are V16's, so /// every store a test creates today is recorded at 16.0.0 (or at 15.0.0, through-/// the frozen snapshot — see `V15RecordedStoreFixture`). It is the only input+/// the frozen snapshot — see `V16RecordedStoreFixture`). It is the only input /// that positively reads *below* V5, which is what `StoreMetadataTests`, /// `BootstrapClassifierTests` and `BootstrapActionTests` need it for. /// /// It is no longer a *convertible* store: since the plan declares real stages, a /// model version the plan does not declare is refused rather than raised-/// implicitly. Under `AsterismV16MigrationPlan` = `[V15, V16]` the floor has+/// implicitly. Under `AsterismV17MigrationPlan` = `[V15, V16]` the floor has /// risen nine versions since that first became true, so 4.0.0 is refused with /// more room to spare than ever. What can still be asserted about it is the /// refusal.@@ -56,7 +56,7 @@ enum V4RecordedStoreFixture { /// The schema versions Core Data recorded into the store's own metadata — /// `["4.0.0"]` for this fixture (nothing converts a 4.0.0 store any more;- /// `V15RecordedStoreTests` uses this helper to observe `"15.0.0"` before the+ /// `V16RecordedStoreTests` uses this helper to observe `"15.0.0"` before the /// stage and `"16.0.0"` after it). /// Read straight out of `Z_METADATA` rather than through SwiftData, so /// asking the question cannot itself perform the conversion.@@ -109,14 +109,14 @@ enum V4RecordedStoreFixture { /// stage ended that — a staged migration refuses a model version the plan does /// not declare — so the conversion those tests asserted, and the 5.0.0 end state /// they pinned, no longer exist to assert. The 432-Entry scale fixture went with-/// them: nothing can open it. `AsterismV16MigrationPlan` is `[V15, V16]`, so the+/// them: nothing can open it. `AsterismV17MigrationPlan` is `[V15, V16]`, so the /// floor has since risen nine more versions and 4.0.0 is refused by a wider /// margin than when this suite was written. /// /// Nothing shipped changes. `classify` already refuses a below-V5 store before /// any container is constructed (Req 2.9, Decision 1 of /// `retire-migration-chain`), and the recovery for one remains the 4/4 backup-/// archive. The conversion coverage is `V15RecordedStoreTests`, which seeds its+/// archive. The conversion coverage is `V16RecordedStoreTests`, which seeds its /// input through the frozen V15 snapshot — the version installed libraries /// actually hold, and under `[V15, V16]` the only one that converts at all. @Suite("A 4.0.0-recorded store under the V16 plan", .serialized)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swiftindex 02db7903..d50e8b33 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift@@ -117,7 +117,7 @@ struct WorkEditCreditsTests { let outcome = try await harness.repository.updateWork( id: work, basis: WorkEditBasis(work: snapshot),- draft: draft(from: snapshot, notes: "reader prose", credits: nil))+ draft: draft(from: snapshot, notes: "reader prose", credits: nil), calendar: .current) #expect(outcome == .committed) #expect(try await harness.repository.creditRows().map(\.id) == [row])@@ -146,7 +146,7 @@ struct WorkEditCreditsTests { id: work, basis: WorkEditBasis(work: snapshot), draft: draft( from: snapshot,- credits: CreditsDraft(seenRowIDs: [seenRow], credits: [])))+ credits: CreditsDraft(seenRowIDs: [seenRow], credits: [])), calendar: .current) #expect(outcome == .committed) #expect(@@ -172,7 +172,7 @@ struct WorkEditCreditsTests { CreditDraft( creatorID: deletedCreator, roleIDs: [], creatorAddedInDraft: false)- ])))+ ])), calendar: .current) #expect(outcome == .committed) let rows = try await harness.repository.creditRows()@@ -210,7 +210,7 @@ struct WorkEditCreditsTests { from: snapshot, credits: CreditsDraft( seenRowIDs: [seenRow],- credits: [CreditDraft(creatorID: creator, roleIDs: [author.uuidString])])))+ credits: [CreditDraft(creatorID: creator, roleIDs: [author.uuidString])])), calendar: .current) #expect(outcome == .committed) let rows = try await harness.repository.creditRows()@@ -251,7 +251,7 @@ struct WorkEditCreditsTests { from: snapshot, credits: CreditsDraft( seenRowIDs: [aliasRow, survivorRow],- credits: [CreditDraft(creatorID: survivor, roleIDs: [author.uuidString])])))+ credits: [CreditDraft(creatorID: survivor, roleIDs: [author.uuidString])])), calendar: .current) #expect(outcome == .committed) let rows = try await harness.repository.creditRows()@@ -280,7 +280,7 @@ struct WorkEditCreditsTests { credits: [ CreditDraft( creatorID: absentCreator, roleIDs: [], creatorAddedInDraft: true)- ])))+ ])), calendar: .current) #expect( refusedCreator == .conflict( .creatorMissing(recordID: work, creatorID: absentCreator)))@@ -298,7 +298,7 @@ struct WorkEditCreditsTests { CreditDraft( creatorID: present, roleIDs: [absentRole.uuidString], roleIDsAddedInDraft: [absentRole.uuidString])- ])))+ ])), calendar: .current) #expect( refusedRole == .conflict(.roleMissing(recordID: work, roleID: absentRole))) #expect(try await harness.repository.creditRows().isEmpty)@@ -313,7 +313,7 @@ struct WorkEditCreditsTests { seenRowIDs: [], credits: [ CreditDraft(creatorID: absentCreator, roleIDs: [absentRole.uuidString])- ])))+ ])), calendar: .current) #expect(committed == .committed) let rows = try await harness.repository.creditRows() #expect(rows.map(\.creatorID) == [absentCreator])@@ -356,7 +356,7 @@ struct WorkEditCreditsTests { CreditDraft( creatorID: creator, roleIDs: [author.uuidString, artist.uuidString])- ])))+ ])), calendar: .current) #expect(outcome == .committed) let rows = try await harness.repository.creditRows()@@ -393,7 +393,7 @@ struct WorkEditCreditsTests { seenRowIDs: [row], credits: [ CreditDraft(creatorID: creator, roleIDs: [author.uuidString])- ])))+ ])), calendar: .current) #expect(outcome == .committed) #expect(try await harness.repository.work(id: work).genericNotes == "reader prose")@@ -451,7 +451,7 @@ struct WorkEditCreditsTests { creatorID: creator, roleIDs: [author.uuidString, letterer.uuidString], roleIDsAddedInDraft: [letterer.uuidString])- ])))+ ])), calendar: .current) #expect(outcome == .committed, "a removed role is resolved, so nothing is invalidated") let rows = try await harness.repository.creditRows()@@ -513,7 +513,7 @@ struct WorkEditCreditsTests { from: snapshot, credits: CreditsDraft( seenRowIDs: credit.rowIDs,- credits: [CreditDraft(creatorID: creator, roleIDs: kept)])))+ credits: [CreditDraft(creatorID: creator, roleIDs: kept)])), calendar: .current) #expect(outcome == .committed) let rows = try await harness.repository.creditRows()@@ -541,7 +541,7 @@ struct WorkEditCreditsTests { id: work, basis: WorkEditBasis(work: snapshot), draft: draft( from: snapshot,- credits: CreditsDraft(seenRowIDs: [row], credits: [])))+ credits: CreditsDraft(seenRowIDs: [row], credits: [])), calendar: .current) guard case .conflict(.torn) = outcome else { Issue.record("expected the torn refusal, got \(outcome)")@@ -568,7 +568,7 @@ struct WorkEditCreditsTests { id: work, basis: WorkEditBasis(work: snapshot), draft: self.draft( from: snapshot, notes: "reader prose",- credits: CreditsDraft(seenRowIDs: [row], credits: [])))+ credits: CreditsDraft(seenRowIDs: [row], credits: [])), calendar: .current) } saves.shouldFail = false
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swiftindex 1fb28b1f..993b987b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift@@ -68,7 +68,7 @@ struct WorkEditTests { displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "reader prose", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(refused.conflict?.survivorID == survivor) #expect(try await fixture.repository.membershipColumns(of: survivor) == [SeriesColumns(seriesID: seriesID, position: 1)])@@ -90,7 +90,7 @@ struct WorkEditTests { verdict: "", releaseDays: [], membership: SeriesMembership(seriesID: seriesID, position: 1),- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(committed == .committed) #expect(try await fixture.repository.membershipColumns(of: survivor) == [SeriesColumns(seriesID: seriesID, position: 1)])@@ -109,7 +109,7 @@ struct WorkEditTests { id: work.id, basis: WorkEditBasis(work: work), draft: draft( from: work, notes: "reader prose",- membership: SeriesMembership(seriesID: ghost, position: 1)))+ membership: SeriesMembership(seriesID: ghost, position: 1)), calendar: .current) #expect(outcome == .conflict(.seriesMissing(recordID: work.id, seriesID: ghost))) // Nothing was written: not the pair, and not the notes beside it. #expect(try await fixture.repository.membershipColumns(of: work.id) == [.none])@@ -135,7 +135,7 @@ struct WorkEditTests { let outcome = try await fixture.repository.updateWork( id: work.id, basis: WorkEditBasis(work: work),- draft: draft(from: work, notes: "reader prose", membership: work.membership))+ draft: draft(from: work, notes: "reader prose", membership: work.membership), calendar: .current) #expect(outcome == .committed) #expect(try await fixture.repository.membershipColumns(of: work.id) == [SeriesColumns(seriesID: ghost, position: 2.5)])@@ -144,7 +144,7 @@ struct WorkEditTests { #expect( try await fixture.repository.updateWork( id: work.id, basis: WorkEditBasis(work: reloaded),- draft: draft(from: reloaded, membership: nil)) == .committed)+ draft: draft(from: reloaded, membership: nil), calendar: .current) == .committed) #expect(try await fixture.repository.membershipColumns(of: work.id) == [.none]) } @@ -170,7 +170,7 @@ struct WorkEditTests { let outcome = try await fixture.repository.updateWork( id: workID, basis: WorkEditBasis(work: work), draft: draft(- from: work, membership: SeriesMembership(seriesID: seriesID, position: 2.5)))+ from: work, membership: SeriesMembership(seriesID: seriesID, position: 2.5)), calendar: .current) #expect(outcome == .committed) #expect(try await fixture.repository.membershipColumns(of: workID)@@ -199,7 +199,7 @@ struct WorkEditTests { id: work.id, basis: WorkEditBasis(work: work), draft: draft( from: work,- membership: SeriesMembership(seriesID: seriesID, position: position)))+ membership: SeriesMembership(seriesID: seriesID, position: position)), calendar: .current) } } #expect(try await fixture.repository.membershipColumns(of: work.id) == [.none])@@ -210,7 +210,7 @@ struct WorkEditTests { id: work.id, basis: WorkEditBasis(work: work), draft: draft( from: work,- membership: SeriesMembership(seriesID: seriesID, position: 1.3)))+ membership: SeriesMembership(seriesID: seriesID, position: 1.3)), calendar: .current) == .committed) } @@ -236,7 +236,7 @@ struct WorkEditTests { let outcome = try await fixture.repository.updateWork( id: work.id, basis: WorkEditBasis(work: work),- draft: draft(from: work, notes: "reader prose", membership: nil))+ draft: draft(from: work, notes: "reader prose", membership: nil), calendar: .current) #expect(outcome == .committed) #expect(try await fixture.repository.membershipColumns(of: work.id) == [.none]) @@ -248,7 +248,7 @@ struct WorkEditTests { #expect( try await fixture.repository.updateWork( id: second.id, basis: WorkEditBasis(work: second),- draft: draft(from: second, membership: nil)) == .committed)+ draft: draft(from: second, membership: nil), calendar: .current) == .committed) #expect(try await fixture.repository.membershipColumns(of: work.id) == [.none]) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swiftindex 8e09876e..4e4e6775 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift@@ -61,7 +61,7 @@ struct WorkMergeRepositoryTests { displayTitle: "Target Work", typeAssignment: .none, genreTags: [], genericNotes: "target notes", workStatus: .finished, readingStatus: .finished, verdict: "a fine ending", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) try await fixture.repository.updateWork( id: sourceID, draft: WorkMetadataDraft(@@ -69,7 +69,7 @@ struct WorkMergeRepositoryTests { genericNotes: "", workStatus: .hiatus, readingStatus: .abandoned, verdict: "gave up in book two", releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) let contract = try await fixture.repository.projectMerge( sourceWorkID: sourceID, targetWorkID: targetID)@@ -107,7 +107,7 @@ struct WorkMergeRepositoryTests { displayTitle: "Source Work", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],- membership: nil, thumbnail: .keep))+ membership: nil, thumbnail: .keep), calendar: .current) let contract = try await fixture.repository.projectMerge( sourceWorkID: sourceID, targetWorkID: targetID)@@ -139,7 +139,7 @@ struct WorkMergeRepositoryTests { displayTitle: "Target Work", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],- membership: nil, thumbnail: .keep))+ membership: nil, thumbnail: .keep), calendar: .current) let contract = try await fixture.repository.projectMerge( sourceWorkID: sourceID, targetWorkID: targetID)@@ -173,7 +173,7 @@ struct WorkMergeRepositoryTests { displayTitle: "Source Work", typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [],- membership: nil, thumbnail: .set(cover)))+ membership: nil, thumbnail: .set(cover)), calendar: .current) let contract = try await fixture.repository.projectMerge( sourceWorkID: sourceID, targetWorkID: targetID)@@ -208,7 +208,7 @@ struct WorkMergeRepositoryTests { draft: WorkMetadataDraft( displayTitle: title, typeAssignment: .none, genreTags: [], genericNotes: "", workStatus: .ongoing, readingStatus: .reading,- verdict: "", releaseDays: [], membership: nil, thumbnail: .set(cover)))+ verdict: "", releaseDays: [], membership: nil, thumbnail: .set(cover)), calendar: .current) } let contract = try await fixture.repository.projectMerge(@@ -341,7 +341,7 @@ struct WorkMergeRepositoryTests { workStatus: .ongoing, readingStatus: .reading, verdict: "" , releaseDays: [], membership: nil, thumbnail: .keep)- )+ , calendar: .current) fixture.save.resetCounts() let result = try await fixture.repository.commitMerge(staleContract)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swiftindex 673474ff..44d59c69 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift@@ -81,7 +81,7 @@ struct WorkThumbnailRepositoryTests { let outcome = try await repository.updateWork( id: workID, basis: try await repository.thumbnailBasis(of: workID),- draft: Self.metadata(notes: "reader prose", thumbnail: .keep))+ draft: Self.metadata(notes: "reader prose", thumbnail: .keep), calendar: .current) #expect(outcome == .committed) let columns = try library.thumbnailColumns(of: workID)@@ -118,7 +118,7 @@ struct WorkThumbnailRepositoryTests { let outcome = try await repository.updateWork( id: workID, basis: try await repository.thumbnailBasis(of: workID),- draft: Self.metadata(thumbnail: .set(picked)))+ draft: Self.metadata(thumbnail: .set(picked)), calendar: .current) #expect(outcome == .committed) let columns = try library.thumbnailColumns(of: workID)@@ -161,7 +161,7 @@ struct WorkThumbnailRepositoryTests { let outcome = try await repository.updateWork( id: workID, basis: try await repository.thumbnailBasis(of: workID),- draft: Self.metadata(thumbnail: .set(picked)))+ draft: Self.metadata(thumbnail: .set(picked)), calendar: .current) #expect(outcome == .committed) #expect(try library.thumbnailColumns(of: workID) == [ThumbnailColumns(@@ -190,7 +190,7 @@ struct WorkThumbnailRepositoryTests { let outcome = try await repository.updateWork( id: workID, basis: try await repository.thumbnailBasis(of: workID),- draft: Self.metadata(thumbnail: .clear))+ draft: Self.metadata(thumbnail: .clear), calendar: .current) #expect(outcome == .committed) #expect(try library.thumbnailColumns(of: workID)@@ -219,7 +219,7 @@ struct WorkThumbnailRepositoryTests { _ = try await repository.updateWork( id: workID, basis: try await repository.thumbnailBasis(of: workID),- draft: Self.metadata(thumbnail: .set(Self.cover(.portrait, red: 10))))+ draft: Self.metadata(thumbnail: .set(Self.cover(.portrait, red: 10))), calendar: .current) let stamps = Set(try library.workRows(id: workID).map(\.modifiedAt)) #expect(stamps.count == 1)@@ -257,7 +257,7 @@ struct WorkThumbnailRepositoryTests { displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "", memberships: [WorkMembershipBasis(hostname: Self.hostname, urlIdentity: nil)], lastParsedTitle: "A Serial", titleProvenance: .parsed, thumbnail: mine.identity),- draft: Self.metadata(thumbnail: .clear))+ draft: Self.metadata(thumbnail: .clear), calendar: .current) guard case .conflict(.torn(let recordID, let variants)) = outcome else { Issue.record("expected a torn conflict, got \(outcome)")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swiftindex 3375fcac..94b4c9c2 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swiftindex f7be6321..1ac4dad6 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swiftindex 994087f6..f4542353 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swiftindex bf19a7dc..d1306ccb 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift@@ -201,7 +201,7 @@ struct WorkTypeWritePathTests { genreTags: work.genreTags, genericNotes: work.genericNotes, workStatus: work.workStatus, readingStatus: work.readingStatus, verdict: work.verdict, releaseDays: [], membership: nil,- thumbnail: .keep))+ thumbnail: .keep), calendar: .current) #expect(outcome == .committed) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swiftindex dc6e0554..507c01b6 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let container = try ModelContainer( for: schema, configurations: [ModelConfiguration(@@ -418,7 +418,7 @@ struct WriteSiteRelationshipTests { let context = ModelContext(container) try LibraryRepository.materializeArchive(- BackupImportPayload(BackupV15Fixtures.minimalTaughtPayload()), into: context)+ BackupImportPayload(BackupV16Fixtures.minimalTaughtPayload()), into: context) let site = try #require(try context.fetch(FetchDescriptor<Site>()).first) let entry = try #require(try context.fetch(FetchDescriptor<Entry>()).first)@@ -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) == "16",+ #expect(try markerContent(cfg) == "17", "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) == "16", "the import republishes nothing")+ #expect(try markerContent(cfg) == "17", "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) == "16")+ #expect(try markerContent(cfg) == "17") try expectEveryRelationshipPopulated(cfg) withExtendedLifetime(dir) {} }@@ -553,7 +553,7 @@ struct WriteSiteRelationshipTests { } private func importPlan() throws -> BackupImportPlan {- let payload = BackupImportPayload(BackupV15Fixtures.minimalTaughtPayload())+ let payload = BackupImportPayload(BackupV16Fixtures.minimalTaughtPayload()) return BackupImportPlan( metadata: BackupImportMetadata( formatVersion: 8, schemaVersion: 9, appBuild: "test",@@ -580,7 +580,7 @@ struct WriteSiteRelationshipTests { entry.site = site context.insert(entry) try context.save()- try Data("15\n".utf8).write(to: cfg.readinessMarkerURL, options: .atomic)+ try Data("17\n".utf8).write(to: cfg.readinessMarkerURL, options: .atomic) withExtendedLifetime(container) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swiftindex 4122aa7f..15bad60d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift@@ -43,11 +43,9 @@ struct WrongHostWorkURLCompatibilityTests { @Test("The heal leaves the archive's version pair where the schema put it") func archiveVersionIsUnchanged() {- // The file: format 15 over schema 16, the pair every archive since- // `remove-article-mode` carries. The heal did not move it; dropping- // `Site.junkSuffixRule` did (`remove-article-mode` Req 5.1).- #expect(BackupV15Document.formatVersion == 15)- #expect(BackupV15Document.schemaVersion == 16)+ // The heal leaves the live archive generation alone.+ #expect(BackupV16Document.formatVersion == 16)+ #expect(BackupV16Document.schemaVersion == 17) } @Test("A healed library's archive uses only the membership keys 9/10 declared")@@ -85,7 +83,7 @@ struct WrongHostWorkURLCompatibilityTests { // The archive: the minted row is there, and so is the untaught wire Site // the projection synthesised for its hostname — without which the // reference checks would refuse a membership naming no Site.- let decoded = try BackupV15Codec.decode(archive)+ let decoded = try BackupV16Codec.decode(archive) let minted = try #require( decoded.payload.memberships.first { $0.hostname == Self.destination }) #expect(minted.workID == workID)@@ -151,10 +149,10 @@ private struct CompatibilityRoot { let outcome = try await repository.reconcileAfterSync() #expect(outcome.memberships.movedWorkURLs == 1) - let exporter = BackupV15Exporter(+ let exporter = BackupV16Exporter( repository: repository, stagingDirectory: directory.appending(path: "staging")) let result = try await exporter.export(- metadata: BackupV15Metadata(+ metadata: BackupV16Metadata( appBuild: "test-1.0", exportedAt: WrongHostWorkURLCompatibilityTests.epoch)) let data = try Data(contentsOf: result.fileURL)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swiftindex 2cb40159..c4770f96 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swift@@ -311,7 +311,7 @@ struct WrongHostWorkURLImportTests { // A legacy identity state with no identity value: an illegal // membership tuple that has nothing to do with the Work URL. [- BackupV15Membership(+ BackupV16Membership( id: work, workID: work, hostname: siteHostname, createdAt: epoch, urlIdentity: nil, urlIdentityState: .legacyUnverified, urlIdentityRuleID: nil, workURLString: nil)@@ -401,14 +401,14 @@ private let epoch = Date(timeIntervalSince1970: 1_800_000_000) private func record( id: UUID = UUID(), work: UUID?, hostname: String, workURL: String?-) -> BackupV15Membership {- BackupV15Membership(+) -> BackupV16Membership {+ BackupV16Membership( id: id, workID: work, hostname: hostname, createdAt: epoch, urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: workURL) } -private func url(of records: [BackupV15Membership], _ id: UUID) -> String? {+private func url(of records: [BackupV16Membership], _ id: UUID) -> String? { records.first { $0.id == id }?.workURLString ?? nil } @@ -418,14 +418,14 @@ private func url(of records: [BackupV15Membership], _ id: UUID) -> String? { /// a test can address them. private func makePlan( activePattern: Bool = true,- memberships: (_ workID: UUID, _ otherMembershipID: UUID) -> [BackupV15Membership]+ memberships: (_ workID: UUID, _ otherMembershipID: UUID) -> [BackupV16Membership] ) -> BackupImportPlan { let workID = UUID() let otherMembershipID = UUID() let patternID = UUID() let rawURL = "https://\(siteHostname)/chapter/1" - let entry = BackupV15Entry(+ let entry = BackupV16Entry( id: UUID(), captureTitle: "Chapter 1", captureTitleSource: .host, rawURL: rawURL, canonicalURL: nil, hostname: siteHostname, entryIdentityKey: rawURL, conservativeIdentityKey: rawURL,@@ -435,7 +435,7 @@ private func makePlan( intentionallyUnattached: false, citations: EntryCitations( workAssignment: .pattern(CitedRule(id: patternID))))- let work = BackupV15Work(+ let work = BackupV16Work( id: workID, displayTitle: "Imported Work", lastParsedTitle: "Imported Work", genericNotes: "", genreTags: [], titleProvenance: .parsed, workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], workTypeID: nil,@@ -444,13 +444,13 @@ private func makePlan( // `activePattern` varies is whether it is *active*, which is what makes the // taught Site's tuple legal or not. let patterns = [- BackupV15TitlePattern(+ BackupV16TitlePattern( id: patternID, siteHostname: siteHostname, version: 1, isActive: activePattern, createdAt: epoch, definition: StoredPatternDefinition(definition: .wholeTitle)) ] let sites = [siteHostname, otherHostname].map {- BackupV15Site(hostname: $0, displayName: $0, mode: $0 == siteHostname ? .taught : .untaught)+ BackupV16Site(hostname: $0, displayName: $0, mode: $0 == siteHostname ? .taught : .untaught) } let payload = BackupImportPayload( entries: [entry], works: [work], sites: sites, titlePatterns: patterns,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swiftindex 34248143..5cc990e4 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: AsterismSchemaV16.self)+ let schema = Schema(versionedSchema: AsterismSchemaV17.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV16MigrationPlan.self,+ for: schema, migrationPlan: AsterismV17MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/specs/retire-migration-chain/library-graph-baseline.txt b/specs/retire-migration-chain/library-graph-baseline.txtindex eb21cf43..db55358c 100644--- a/specs/retire-migration-chain/library-graph-baseline.txt+++ b/specs/retire-migration-chain/library-graph-baseline.txt@@ -83,7 +83,11 @@ # it. Hand-edited by deleting that one field from each site line # and reviewing the diff line by line (Req 7.4), not by # regenerating the file.-format 13+# format 14 is schema V17 (catch-up-progress): every work line gains+# catchUpConfirmationData and lastChapterOverrideData after releaseDaysRaw.+# Both optional blobs are nil on a converted V16 row; no entity or+# relationship changes. Hand-edited into the recorded work line.+format 14 counts entries=4 works=1 sites=2 titlePatterns=1 urlRulePatterns=1 workTypes=2 memberships=1 distinctPairs=0 series=0 links=0 creators=0 creatorRoles=3 credits=0 places=0 placeSuppressions=0 site hostname="alpha.test" displayName="Alpha Reader" modeRaw="untaught" site hostname="beta.test" displayName="Beta Serials" modeRaw="taught"@@ -91,7 +95,7 @@ titlePattern id=A1000000-0000-4000-8000-000000000001 site="beta.test" version=1 urlRulePattern id=A2000000-0000-4000-8000-000000000002 site="beta.test" version=1 isCurrent=true createdAt=1800000000.000 originRaw="readerTaught" definition="{\"work\":{\"locator\":{\"query\":{\"name\":\"sid\"}}}}" workType id=D0000001-0000-4000-8000-000000000001 name="novel" nameModifiedAt=0.000 stateRaw="active" stateModifiedAt=0.000 canonicalID=nil createdAt=0.000 modifiedAt=0.000 workType id=D0000002-0000-4000-8000-000000000002 name="webtoon" nameModifiedAt=0.000 stateRaw="active" stateModifiedAt=0.000 canonicalID=nil createdAt=0.000 modifiedAt=0.000-work id=A3000000-0000-4000-8000-000000000003 displayTitle="Beta Serial" lastParsedTitle="Beta Serial" genericNotes="notes on the serial" workTypeID=A4000000-0000-4000-8000-000000000004 genreTags=["action","drama"] titleProvenanceRaw="parsed" workStatusRaw="ongoing" readingStatusRaw="reading" verdict="" releaseDaysRaw=[] seriesID=nil seriesPosition=nil thumbnailShapeRaw=nil thumbnailDigest=nil createdAt=1800000000.000 modifiedAt=1800000000.000+work id=A3000000-0000-4000-8000-000000000003 displayTitle="Beta Serial" lastParsedTitle="Beta Serial" genericNotes="notes on the serial" workTypeID=A4000000-0000-4000-8000-000000000004 genreTags=["action","drama"] titleProvenanceRaw="parsed" workStatusRaw="ongoing" readingStatusRaw="reading" verdict="" releaseDaysRaw=[] catchUpConfirmationData=nil lastChapterOverrideData=nil seriesID=nil seriesPosition=nil thumbnailShapeRaw=nil thumbnailDigest=nil createdAt=1800000000.000 modifiedAt=1800000000.000 entry id=B1000000-0000-4000-8000-000000000011 site="alpha.test" work=nil hostname="alpha.test" captureTitle="An Alpha Capture" captureTitleSourceRaw="host" rawURLString="https://alpha.test/read/1" canonicalURLString=nil entryIdentityKey="https://alpha.test/read/1" conservativeIdentityKey="https://alpha.test/read/1" identityBasisRaw="conservative" urlWorkIdentity=nil chapterSequence=nil chapterTitle=nil note="" ratingRaw=nil firstCapturedAt=1800000000.000 lastSharedAt=1800000000.000 modifiedAt=1800000000.000 intentionallyUnattached=false citationsData="{\"chapterTitle\":{\"kind\":\"none\"},\"identity\":{\"rawURL\":{}},\"workAssignment\":{\"none\":{}}}" entry id=B2000000-0000-4000-8000-000000000012 site="beta.test" work=A3000000-0000-4000-8000-000000000003 hostname="beta.test" captureTitle="The Beta Serial :: Chapter One" captureTitleSourceRaw="host" rawURLString="https://beta.test/read/1" canonicalURLString=nil entryIdentityKey="https://beta.test/read/1" conservativeIdentityKey="https://beta.test/read/1" identityBasisRaw="conservative" urlWorkIdentity=nil chapterSequence=nil chapterTitle="Chapter One" note="a reader's note" ratingRaw="up" firstCapturedAt=1800000000.000 lastSharedAt=1800000000.000 modifiedAt=1800000000.000 intentionallyUnattached=false citationsData="{\"chapterTitle\":{\"kind\":\"manual\"},\"identity\":{\"rawURL\":{}},\"workAssignment\":{\"manual\":{}}}" entry id=B3000000-0000-4000-8000-000000000013 site="beta.test" work=A3000000-0000-4000-8000-000000000003 hostname="beta.test" captureTitle="The Beta Serial :: Chapter Two" captureTitleSourceRaw="host" rawURLString="https://beta.test/read/2" canonicalURLString=nil entryIdentityKey="https://beta.test/read/2" conservativeIdentityKey="https://beta.test/read/2" identityBasisRaw="conservative" urlWorkIdentity=nil chapterSequence=nil chapterTitle="Chapter Two" note="" ratingRaw=nil firstCapturedAt=1800000000.000 lastSharedAt=1800000000.000 modifiedAt=1800000000.000 intentionallyUnattached=false citationsData="{\"chapterTitle\":{\"kind\":\"pattern\",\"patternID\":\"A1000000-0000-4000-8000-000000000001\"},\"identity\":{\"rawURL\":{}},\"workAssignment\":{\"manual\":{}}}"
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cbb5d54e..978f84c7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,38 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Changed +- **Catch-up progress — Verification phase:** record Today publication at+ 0.843 s median against the 0.880 s baseline, within its 2 s budget, and+ document automated results and the remaining signing and manual checks.++- **Catch-up progress — App phase:** show exact and estimated progress, caught-up+ banners and current-day actions; add the Set latest sheet and work-page row,+ preserving drafts on refusal and refreshing the page after a successful save.++- **Catch-up progress — Today derivation phase:** carry progress on Today rows,+ use the last-read chapter for badges, and seed exact, estimated, caught-up+ and unknown fixture examples alongside the covered performance fixture.++- **Catch-up progress — Convergence and archive phase:** preserve elected+ progress through reconciliation, collapse, merge and import; advance backups+ to archive 16/17 with progress fields and strict invalid-value checks.++- **Catch-up progress — Repository writes phase:** add fresh sheet reads,+ conflict-checked progress and reading-status saves, and atomic rebasing when+ the work editor changes release days or crosses ongoing status.++- **Catch-up progress — Schema V17 phase:** freeze V16 and migrate Work with+ two optional progress blobs, retire V15, advance readiness markers, and+ elect progress independently across duplicate-row snapshots.++- **Catch-up progress — Core values phase:** add the timestamped confirmation+ and last-chapter override records, deterministic election, and pure progress+ calculation with calendar-day counting and shared whole-chapter parsing.++- **Catch-up progress — Baseline phase:** record three host release measurements+ of Today publication (0.880 s median) and allow the performance Makefile target+ to select an individual arm while preserving its default suite.+ - **Today redesign:** the header names the selected day as a serif title that returns to today, with the Settings gear beside it; the week strip loses its release dots and range pill; releases are a horizontal cover shelf (unread
diff --git a/CLAUDE.md b/CLAUDE.mdindex 90ef7e0e..a897b90b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -85,15 +85,10 @@ bar. `make verify-identity` (a `test-core` prerequisite) is an identity lint, not a style one: it checks the App Group / CloudKit identifier declarations without building anything — see `specs/configuration-identity/`. -**The live store schema is V16** (`specs/remove-article-mode/`), the readiness-marker generation is `"16"`, `AsterismSchemaV15` is the one frozen snapshot left,-and the archive generation is **15/16**. All four have moved for that feature,-the archive one commit behind the other three by design;-`BackupV15ArchiveTests.envelopeVersionsFollowTheLiveSchema` ties the envelope to-the live schema, so the archive is the one of the four that cannot be forgotten-silently — between a schema bump and its archive phase that tie is held open by-a self-clearing `withKnownIssue`, which the archive commit must remove. There is-no such window open now: `make test-core` expects **zero** known issues.+**The live store schema is V17** (`specs/catch-up-progress/`), the readiness+marker generation is `"17"`, `AsterismSchemaV16` is the one frozen snapshot left,+and the archive generation is **16/17**. 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. `Development` builds carry a **Run background export** button in Settings,@@ -188,7 +183,7 @@ 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 `AsterismSchemaV16`. One frozen snapshot is kept beside+are typealiases onto `AsterismSchemaV17`. One frozen snapshot is kept beside it, and the migration plan is always `[V(n-1), V(n)]` with one lightweight stage. A custom migration stage is forbidden: it never fires between structurally identical models and it would run inside the share extension,@@ -433,6 +428,11 @@ and never regresses a newer local record (Decisions 2 and 8). One named divergence is unaddressed by design: two devices independently capturing the same serial mint two Works, and no UUID-keyed pass will find them. +Catch-up confirmation and last-chapter override are timestamped values, folded+independently across Work copies. Backup import folds them before the torn-group+and whole-record `modifiedAt` guards, without changing `modifiedAt` or treating+a progress-only fold as an applied Work record. The fold never reads the clock.+ **Arrivals.** `SyncMonitor` observes the container's event notification and the store's remote-change notification, debounced 2 s because one local save arrives as dozens of transactions (45 for 3,000 records, with most of them
diff --git a/docs/agent-notes/schema-migration.md b/docs/agent-notes/schema-migration.mdindex 4aedbc2e..8fe08a5e 100644--- a/docs/agent-notes/schema-migration.md+++ b/docs/agent-notes/schema-migration.md@@ -1,17 +1,34 @@ # Schema migration -Schema **V16** is live (since `specs/remove-article-mode/`), with **V15**-frozen beside it as the `from` side of one lightweight stage. The readiness-marker set is `["15", "16"]`, and the archive generation is **15/16** — moved by-that feature's archive commit, one commit after the schema. The app opens-`openForApp`; the share extension and the app's intent broker (`app-intents`,-a cold intent step) open `openForExtension` — one opener per role,-both over the same schema and the same file layout (`retire-migration-chain`'s-Req 4). Read the "Current state" section; everything under "History" is-background for the *next* schema bump and describes states that no longer exist.+Schema **V17** is live (`specs/catch-up-progress/`), with **V16** frozen+beside it as the `from` side of one lightweight stage. The app accepts readiness+markers `"16"` and `"17"`; the extension accepts `"17"` only. V17 adds two optional+`Work` Data columns, `catchUpConfirmationData` and `lastChapterOverrideData`.+Converted V16 rows carry nil in both. The archive is **16/17** and the envelope+contract again asserts the live schema version directly.++The app and extension still open through `openForApp` and `openForExtension`+respectively, over the same fixed file layout. The detailed V16 account below+is retained as the worked example for the next freeze. ## Current state +- The live classes are nested in `extension AsterismSchemaV17` in `Models.swift`+ and reached through top-level typealiases. `AsterismSchemaV16.swift` holds the+ one frozen snapshot: stored fields, relationship macros and defaults only.+ Its `Work.thumbnailData` keeps `.externalStorage`, and its referenced raw+ spellings and value types stay frozen by reference.+- `AsterismV17MigrationPlan` is `[V16, V17]` with one lightweight stage. The+ V16 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 conversion test checks the new raw blobs are nil.+- 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 16/17 archive exports that elected+ record and imports it before authored-content recency guards.++## V16 worked example (historical)+ - **Every `@Model` is nested; there are zero top-level `@Model` types.** The live classes live in `extension AsterismSchemaV16 { @Model final class Entry … }` (`Models.swift`) and are reached by top-level typealiases
diff --git a/docs/agent-notes/testing.md b/docs/agent-notes/testing.mdindex b48ce8fe..a70797f7 100644--- a/docs/agent-notes/testing.md+++ b/docs/agent-notes/testing.md@@ -1191,7 +1191,34 @@ the fold is rather than what the screen holds. Reach editor rows through suite's own reveal helper — never a bare `waitFor`, unless the target is in the header or the toolbar. -## A locked screen fails the pending-capture suites and every UI runner+## UI failure collection can delay the command exit++During catch-up-progress (2026-09-28), some failing UI runs printed their+XCTest totals, then left `xcodebuild` waiting after the runner disappeared.+Passing focused runs completed normally. Running the same Makefile targets with+`XCODE_TEST_FLAGS='-collect-test-diagnostics never' PIPE_PRETTY=` and captured+raw output let failing runs return promptly. This narrows the delay to test+finalization; no live stack sample established that every stall had that cause.++The optional Makefile flag preserves defaults when unset. It does not disable+assertions or skip cases, but automatic failure attachments can be absent;+include an explicit hierarchy in a failing assertion when one is needed.+Check the command exit, not only per-test pass lines. Capture long runs to a+file rather than relying on a wrapper that may time out before finalization.++## Protected-file reads can fail while the screen or keychain is locked++**A keychain unlock alone is not always enough (2026-09-27, catch-up-progress).**+After the owner unlocked the login keychain, the same three pending-capture+suites still failed with 123 issues and Cocoa 257 / POSIX 1. A standalone+Foundation probe outside the repo isolated the cause: creating a directory with+`.completeUnlessOpen`, writing and closing a file, then reopening it failed;+the identical operations in an unprotected directory passed. Both Foundation+and POSIX writes reproduced it. `CGSSessionScreenIsLocked` was `Yes`. After+the owner unlocked the screen, the unchanged probe passed every read, with+the protection attribute still present. Check protected-file access directly+before spending another full-suite run; the September 19 keychain observation+below does not establish that keychain unlock is sufficient on every host state. **Check the login keychain before the screen (2026-09-19, T-2317).** One observation, but a clean one: overnight, `make test-core` failed 131 issues (the
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 3cd13aa9..a74641a7 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -55,7 +55,7 @@ | [New Work URL Field](#new-work-url-field) | 2026-09-22 | Done | Smolspec (T-2365). The New Work form's site field accepts a bare hostname or an HTTP(S) URL with the scheme optional; a URL reduces to the host capture derives and is stored as that site's Work URL after the validator's on-host check. The field is relabelled with the URL keyboard, and `LibraryRepositoryError` becomes `LocalizedError` so every form shows a readable message. No schema change. The confirm-same-story dedup prompt is T-2366. | | [To-Read Capture Match](#to-read-capture-match) | 2026-09-23 | Done | Full spec (T-2366). Pairs a to-read work with another work on a shared site whose Work URL or normalised title matches, derived in Today's publication, and asks the reader on a card sheet from the duplicate review surfaces. Confirming opens the merge preview with a `.toReadMatch` request that keeps the to-read UUID and takes the captured work's titles and statuses; declining records every listed pair as a synced `WorkDistinctPair`. No schema change. | | [App Intents](#app-intents) | 2026-09-23 | Done | Full spec (T-2367). Siri and Shortcuts answer which chapters release today and which notes were made today, add a web page as a to-read work, and open Today or a work. Intents run in the app process; a cold step opens the library as the share extension does and leaves an `ExportOwed` marker after a write. `Development` is renamed Devsterism so the two apps' phrases differ. No schema change. |-| [Catch-up Progress](#catch-up-progress) | 2026-09-25 | Planned | Reader-set latest released chapter with a derived estimate, exact/estimated/unknown/caught-up states on Today's Catching up card, a Set latest sheet and a caught-up banner. Schema V16 → V17 (two blob columns on `Work`), archive 16/17, V15 retired. |+| [Catch-up Progress](#catch-up-progress) | 2026-09-25 | Done — implementation complete; signing, remaining UI failures and the owner sync check are recorded in verification-run.md | Reader-set latest released chapter with a derived estimate, exact/estimated/unknown/caught-up states on Today's Catching up card, a Set latest sheet and a caught-up banner. Schema V16 → V17 (two blob columns on `Work`), archive 16/17, V15 retired. | --- @@ -910,9 +910,9 @@ Full spec (T-2367). Five App Intents, a `WorkEntity` with a Find Works action, a ## Catch-up Progress -**Created:** 2026-09-25 · **Status:** Planned — 25 tasks in eight phases and three streams. Decisions 1–5 and Q1–Q33 in the log; one owner step, the two-device check in `runbook.md`.+**Created:** 2026-09-25 · **Status:** Done — all 25 implementation tasks completed in eight phases and three streams. Decisions 1–6 and Q1–Q33 in the log. Core, App unit and catch-up UI checks passed; the broader UI results and Mac signing failure are recorded in `verification-run.md`. The owner’s two-device check in `runbook.md` remains before merge. -Full spec for §6 and §7 of `docs/Asterism-Today-v2.md`. The reader sets a work's latest released chapter in a Set latest sheet (from Today's catch-up rows, the caught-up banner and the work page); Today derives exact, estimated, unknown and caught-up states from it, the work's release days and its notes, with nothing written on read, capture or reconcile. The confirmed set and the last-chapter override are two Codable blob columns so a concurrent edit keeps each tuple whole (Decision 5); copies converge on the newest confirmation through one fold on every multi-copy path (Decisions 2, 4). The work editor rebases the estimate when a work's status crosses ongoing or its release days change. Schema V16 → V17, marker "17", archive 16/17, V15 retired.+Full spec for §6 and §7 of `docs/Asterism-Today-v2.md`. The reader sets a work's latest released chapter in a Set latest sheet (from Today's catch-up rows, the caught-up banner and the work page); Today derives exact, estimated, unknown and caught-up states from it, the work's release days and its notes, with estimates advancing without writes. The confirmed set and the last-chapter override are two Codable blob columns so a concurrent edit keeps each tuple whole (Decision 5); copies converge on the newest confirmation through one fold on every multi-copy path (Decisions 2, 4). The work editor rebases the estimate when a work's status crosses ongoing or its release days change. Schema V16 → V17, marker "17", archive 16/17, V15 retired. - [requirements.md](catch-up-progress/requirements.md) - [design.md](catch-up-progress/design.md)@@ -920,3 +920,5 @@ Full spec for §6 and §7 of `docs/Asterism-Today-v2.md`. The reader sets a work - [decision_log.md](catch-up-progress/decision_log.md) - [prerequisites.md](catch-up-progress/prerequisites.md) - [runbook.md](catch-up-progress/runbook.md)+- [verification-run.md](catch-up-progress/verification-run.md)+- [implementation.md](catch-up-progress/implementation.md)
diff --git a/specs/catch-up-progress/decision_log.md b/specs/catch-up-progress/decision_log.mdindex de2d0c52..d8d6dc79 100644--- a/specs/catch-up-progress/decision_log.md+++ b/specs/catch-up-progress/decision_log.md@@ -213,3 +213,49 @@ A `Data` attribute is one mirrored property, so each tuple arrives whole whateve - On one row, the later arrival wins even when it carries the older confirmation. ---++## Decision 6: Narrow progress writes require the addressed work++**Date**: 2026-09-27+**Status**: accepted++### Context++The specified progress and reading-status APIs carry a progress record or an+expected status, not a `WorkEditBasis`. The existing basis-aware+`resolveWorkWriteTarget` needs the old authored content to redirect a work+that was collapsed after the UI loaded. That basis cannot be reconstructed+from a deleted row.++### Decision++Keep the public APIs as designed. Add an exact-ID overload of+`resolveWorkWriteTarget(id:context:)` for these two narrow writes. It resolves+the current UUID group or throws `recordNotFound`; callers retain the torn-group+and expected-value checks. The editor's basis-aware resolver is unchanged.++### Rationale++A missing target should leave the sheet open with its draft and an error,+rather than infer permission to write a different work. The feature does not+promise redirection of these narrow actions after a collapse.++### Alternatives Considered++- **Add an authored basis to both APIs:** would support existing redirection,+ but expands the public contracts and ties progress-only actions to content+ they do not edit.+- **Redirect by the in-memory survivor ledger alone:** cannot apply the existing+ authored-basis guard and can act on a survivor the reader did not see.++### Consequences++**Positive:**+- No invented basis or change to the existing editor's conflict rules.+- Deleted or collapsed targets fail without writing another work.++**Negative:**+- After a collapse, the reader must reopen the surviving work before saving+ progress or changing its reading status through these actions.++---
diff --git a/specs/catch-up-progress/design.md b/specs/catch-up-progress/design.mdindex 508b1b25..2dd0f866 100644--- a/specs/catch-up-progress/design.md+++ b/specs/catch-up-progress/design.md@@ -154,7 +154,7 @@ public func setReadingStatus(id: UUID, expected: ReadingStatus, to: ReadingStatu ``` - `catchUpSheetState` is a fresh locked read at sheet open; its `record` is the conflict basis and its `progress` the prefill (Req 4.3, 4.6).-- `commitCatchUpProgress` and `setReadingStatus` resolve the target through `resolveWorkWriteTarget` and refuse a torn group with `tornRefusal`, as `updateWork` does (:1370–1375).+- `commitCatchUpProgress` and `setReadingStatus` resolve the exact UUID through the `resolveWorkWriteTarget(id:context:)` overload and refuse a torn group with `tornRefusal`. A missing or collapsed target throws `recordNotFound`, keeping the sheet draft intact; the existing editor resolver still uses its authored basis for redirection (Decision 6). - `commitCatchUpProgress`: refuses `.conflict` when `elect(rows) != basis`; validates 0…9,999; writes a new confirmation (`confirmedAtMilliseconds = MillisecondInstant.milliseconds(clock.now())`, `isEstimate = false`) and, unless `.unchanged`, the override with the same moment, to every row of the group; bumps `modifiedAt`; one `saveStrategy.save`. - `setReadingStatus`: refuses `.conflict` when the group's reading status is not `expected`; writes `readingStatusRaw` and `modifiedAt`. - `updateWork(id:basis:draft:calendar:)`: when the elected record has a latest, and the representative row's tolerant `workStatus` and the draft's are on opposite sides of `.ongoing`, or its canonical `releaseDays` differs from `draft.releaseDays`, it builds the work's entry snapshots with the same bucketing `todaySchedule` uses (entries whose `work?.id` is the group's id, through `entryGroups(canonicalWorkIDs:)`), computes `rebased` under the stored settings, and writes it with `CatchUpWriter` in the same save. A refused save rolls it back (Req 5.3). The entry fetch is one predicate fetch on the work's id, paid only when the trigger fires.
diff --git a/specs/catch-up-progress/tasks.md b/specs/catch-up-progress/tasks.mdindex 84a448fd..69f18292 100644--- a/specs/catch-up-progress/tasks.md+++ b/specs/catch-up-progress/tasks.md@@ -8,7 +8,7 @@ references: ## Baseline -- [ ] 1. Record the before measurement of the todayPublication arm <!-- id:9jd85vl -->+- [x] 1. Record the before measurement of the todayPublication arm <!-- id:9jd85vl --> - Run `make test-performance-m4` filtered to `M4ToleratedScalePerformanceTests` todayPublication, at least three runs, on this branch before any Core change lands - Record medians and spread in `specs/catch-up-progress/verification-run.md`, not in this file - Host only: no device, no Personal build@@ -18,7 +18,7 @@ references: ## Core values -- [ ] 2. Write tests for millisecond conversion, the progress record codec and the fold <!-- id:9jd85vm -->+- [x] 2. Write tests for millisecond conversion, the progress record codec and the fold <!-- id:9jd85vm --> - `CatchUpRecordTests`: `MillisecondInstant.milliseconds` and `date(fromMilliseconds:)` agree with `quantize` at floating-point edges - Codec round-trip through `JSONBlob`; `LastChapterOverride` wire keys `kind`, `number`, `atMilliseconds` pinned by golden bytes; unknown `kind` and garbage decode to nil - Fold: every permutation of 2 to 4 generated records elects the same result; `elect([elect(x)]) == elect(x)`; nil confirmation loses; newer clear beats older value; tie direction per design@@ -26,7 +26,7 @@ references: - Requirements: [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.7](requirements.md#7.7), [8.4](requirements.md#8.4) - References: specs/catch-up-progress/design.md -- [ ] 3. Implement MillisecondInstant helpers and CatchUpRecord with its codec and fold <!-- id:9jd85vn -->+- [x] 3. Implement MillisecondInstant helpers and CatchUpRecord with its codec and fold <!-- id:9jd85vn --> - `RepositoryClock.swift`: `milliseconds(_:)` and `date(fromMilliseconds:)` with `quantize`'s snap-then-floor rule, the only conversion anywhere - New `CatchUpRecord.swift`: `CatchUpConfirmation`, `LastChapterOverride` with hand-written coding, `CatchUpRecord` with `pristine`, `CatchUpFold.elect` - Encode and decode through `JSONBlob` in `Models.swift`@@ -35,7 +35,7 @@ references: - Requirements: [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.7](requirements.md#7.7) - References: Packages/AsterismCore/Sources/AsterismCore/RepositoryClock.swift, Packages/AsterismCore/Sources/AsterismCore/Models.swift -- [ ] 4. Write tests for ChapterNumber, NumberedNote and CatchUpProgress <!-- id:9jd85vo -->+- [x] 4. Write tests for ChapterNumber, NumberedNote and CatchUpProgress <!-- id:9jd85vo --> - `CatchUpProgressTests` table: each state; override value, cleared and none; re-share moves `lastSharedAt` but not R; note above R after the override; latest below R - Decision 3 stall case and the save-45-sees-75 case; clock ahead; count-up off; status not ongoing; no release days; cap at 9,999; read-day ties per Q24 - DST weeks in Europe/Amsterdam and Australia/Sydney; `rebased` returns nil without a latest and sets the estimate flag otherwise@@ -45,7 +45,7 @@ references: - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [1.7](requirements.md#1.7) - References: Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift -- [ ] 5. Implement ChapterNumber, NumberedNote and CatchUpProgress <!-- id:9jd85vp -->+- [x] 5. Implement ChapterNumber, NumberedNote and CatchUpProgress <!-- id:9jd85vp --> - New `ChapterNumber.swift`; delete `TodayDayPlan`'s private `chapterNumber(of:)` and call the new one - New `CatchUpProgress.swift`: `NumberedNote.from([EntrySnapshot])` carrying the source title, `build(record:notes:releaseDays:workStatus:day:calendar:)`, `build(work:day:calendar:)`, `rebased` - Reuse `TodayDayPlan.releaseCount`, widening its access if needed@@ -56,7 +56,7 @@ references: ## Schema V17 -- [ ] 6. Freeze V16, add V17 with the two blob columns and retire V15 <!-- id:9jd85vq -->+- [x] 6. Freeze V16, add V17 with the two blob columns and retire V15 <!-- id:9jd85vq --> - One commit, every commit compiling: freeze `AsterismSchemaV16` verbatim with its frozen referents; add `AsterismSchemaV17.swift` and `AsterismV17MigrationPlan` `[V16, V17]`; point the `Models.swift` extension and typealiases at V17 - `Work` adds `catchUpConfirmationData: Data? = nil` and `lastChapterOverrideData: Data? = nil` after `releaseDaysRaw` - Delete `AsterismSchemaV15.swift`, `V15RecordedStoreFixture`, `V15RecordedStoreTests`; add `V16RecordedStoreFixture/Tests` asserting the raw columns are nil after conversion; rename every test `Schema(versionedSchema:)` reference and grep-gate the rest@@ -68,7 +68,7 @@ references: - Requirements: [9.1](requirements.md#9.1), [9.2](requirements.md#9.2), [9.3](requirements.md#9.3) - References: docs/agent-notes/schema-migration.md, specs/retire-migration-chain/library-graph-baseline.txt -- [ ] 7. Write tests for CatchUpWriter and the elected snapshot record <!-- id:9jd85vr -->+- [x] 7. Write tests for CatchUpWriter and the elected snapshot record <!-- id:9jd85vr --> - `CatchUpWriter.apply` writes only where the decoded value differs and reports whether it wrote; a second apply writes nothing - A split same-UUID group presents the elected record, not the carrier's; `snapshot(_:)` decodes the row's blobs; an undecodable blob reads as pristine - `WorkAuthoredContent` and variant IDs are unchanged by progress-only differences@@ -76,7 +76,7 @@ references: - Stream: 1 - Requirements: [7.1](requirements.md#7.1), [7.5](requirements.md#7.5), [7.6](requirements.md#7.6) -- [ ] 8. Implement CatchUpWriter, WorkSnapshot.catchUp and elected group rebuilds <!-- id:9jd85vs -->+- [x] 8. Implement CatchUpWriter, WorkSnapshot.catchUp and elected group rebuilds <!-- id:9jd85vs --> - `WorkSnapshot.catchUp` as a defaulted init parameter - `LibraryRepository.snapshot(_:)` near :2032; both rebuilds in `LibraryRepository+Groups.swift` near :414 and :433 elect over the group's rows - Blocked-by: 9jd85vr (Write tests for CatchUpWriter and the elected snapshot record)@@ -86,7 +86,7 @@ references: ## Repository writes -- [ ] 9. Write tests for catchUpSheetState, commitCatchUpProgress and setReadingStatus <!-- id:9jd85vt -->+- [x] 9. Write tests for catchUpSheetState, commitCatchUpProgress and setReadingStatus <!-- id:9jd85vt --> - Sheet state is a fresh read: record, progress for the given day, R's source title - Commit writes the confirmation with the clock's milliseconds and the flag off, the override only when edited, to every row; bumps `modifiedAt`; refuses `.conflict` on a changed record, torn groups, and numbers outside 0 to 9,999; `.clear` stores a cleared override - `setReadingStatus` refuses when the status is not the expected one and on torn groups; writes nothing else@@ -94,7 +94,7 @@ references: - Stream: 1 - Requirements: [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [4.3](requirements.md#4.3), [4.6](requirements.md#4.6), [4.8](requirements.md#4.8), [4.9](requirements.md#4.9), [4.10](requirements.md#4.10) -- [ ] 10. Implement the catch-up repository calls <!-- id:9jd85vu -->+- [x] 10. Implement the catch-up repository calls <!-- id:9jd85vu --> - New `LibraryRepository+CatchUpProgress.swift`; resolve targets through `resolveWorkWriteTarget` and `tornRefusal` as `updateWork` does - One locked context and one `saveStrategy.save` per call - Blocked-by: 9jd85vt (Write tests for catchUpSheetState, commitCatchUpProgress and setReadingStatus)@@ -102,7 +102,7 @@ references: - Requirements: [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [4.3](requirements.md#4.3), [4.6](requirements.md#4.6), [4.8](requirements.md#4.8), [4.9](requirements.md#4.9), [4.10](requirements.md#4.10) - References: Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift -- [ ] 11. Write tests for the rebase in updateWork <!-- id:9jd85vv -->+- [x] 11. Write tests for the rebase in updateWork <!-- id:9jd85vv --> - Fires when status crosses ongoing in either direction and when canonical release days change; not on raw-only spelling differences, not without a latest - Stores E under the pre-save settings for the calendar's current day, confirmation now, estimate flag on - A refused metadata commit leaves the record unchanged@@ -110,7 +110,7 @@ references: - Stream: 1 - Requirements: [5.3](requirements.md#5.3) -- [ ] 12. Implement the rebase and the required calendar parameter on updateWork <!-- id:9jd85vw -->+- [x] 12. Implement the rebase and the required calendar parameter on updateWork <!-- id:9jd85vw --> - `updateWork(id:basis:draft:calendar:)`; update every call site in Core, the app and both test targets - Entry snapshots built with the same bucketing `todaySchedule` uses; the fetch runs only when the trigger fires; write with `CatchUpWriter` in the same save - `AppLibraryModel` passes its published calendar@@ -121,7 +121,7 @@ references: ## Convergence and archive -- [ ] 13. Write tests for the fold on convergence, collapse, resolution and merge <!-- id:9jd85vx -->+- [x] 13. Write tests for the fold on convergence, collapse, resolution and merge <!-- id:9jd85vx --> - Progress-only divergence in a same-UUID group converges and a second pass writes nothing - Collapse carries the elected record; a confirmation written to a loser and one written to the survivor between the write phase and deletion both survive; equal timestamps - `resolveWorkSet` and the work-merge commit carry the elected record whatever variant the reader chose@@ -129,7 +129,7 @@ references: - Stream: 2 - Requirements: [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5), [7.6](requirements.md#7.6) -- [ ] 14. Implement the fold in the Work pass, the deletion commit, resolveWorkSet and the merge commit <!-- id:9jd85vy -->+- [x] 14. Implement the fold in the Work pass, the deletion commit, resolveWorkSet and the merge commit <!-- id:9jd85vy --> - `DuplicateReconciler` beside `apply(carrier, to: survivor, types:)` near :568, and `carryCatchUp` beside `carrySeries`/`carryThumbnail` near :1305 - `LibraryRepository+DuplicateResolution.resolveWorkSet` and `LibraryRepository+WorkMerge` commit - Blocked-by: 9jd85vx (Write tests for the fold on convergence, collapse, resolution and merge)@@ -137,7 +137,7 @@ references: - Requirements: [7.1](requirements.md#7.1), [7.2](requirements.md#7.2), [7.3](requirements.md#7.3), [7.4](requirements.md#7.4), [7.5](requirements.md#7.5), [7.6](requirements.md#7.6) - References: Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift -- [ ] 15. Write tests for the 16/17 archive <!-- id:9jd85vz -->+- [x] 15. Write tests for the 16/17 archive <!-- id:9jd85vz --> - Round-trip of all six flat fields; mapping of cleared override, missing confirmation time, missing override moment - Import older, newer, equal and torn: the fold runs before both guards, bumps no `modifiedAt`, does not enter `applied`; importing twice changes nothing - A 15/16 archive is refused before any write; golden `backup-16-17-golden.json`; undecodable blob refuses export by name@@ -146,7 +146,7 @@ references: - Requirements: [7.4](requirements.md#7.4), [8.1](requirements.md#8.1), [8.2](requirements.md#8.2), [8.3](requirements.md#8.3), [8.4](requirements.md#8.4) - References: Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift -- [ ] 16. Implement BackupV16 and the import fold, and close the envelope window <!-- id:9jd85w0 -->+- [x] 16. Implement BackupV16 and the import fold, and close the envelope window <!-- id:9jd85w0 --> - Replace the `BackupV15` types, codec and exporter with `BackupV16`; `formatVersion 16`, `schemaVersion 17`; `supportedVersions (16, 17)` - Fold in `ConfirmImport.commitWorks` before the torn and `modifiedAt` guards; `ArchiveRecordBuilders.makeWork` sets the blobs - Re-record the golden with `ASTERISM_RECORD_GOLDEN=1`; remove the envelope `withKnownIssue`; add the import-fold line to CLAUDE.md Sync and the 16/17 archive generation@@ -157,7 +157,7 @@ references: ## Today derivation -- [ ] 17. Write tests for progress on release and catch-up rows <!-- id:9jd85w1 -->+- [x] 17. Write tests for progress on release and catch-up rows <!-- id:9jd85w1 --> - `ReleaseRow.progress` for the selected day; `lastChapter` is R so the shelf badge follows the override and ignores re-shares - The unknown line's chapter and day come from R and r where R is known - Future days compute estimates for that day@@ -166,20 +166,20 @@ references: - Requirements: [1.2](requirements.md#1.2), [2.3](requirements.md#2.3), [2.5](requirements.md#2.5) - References: Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift -- [ ] 18. Implement progress in todaySchedule, ScheduledWork and ReleaseRow <!-- id:9jd85w2 -->+- [x] 18. Implement progress in todaySchedule, ScheduledWork and ReleaseRow <!-- id:9jd85w2 --> - `ScheduledWork` gains `catchUp`, `numberedNotes`, `workStatus`, built in the same walk as `notedDays` inside the locked read - Blocked-by: 9jd85w1 (Write tests for progress on release and catch-up rows) - Stream: 1 - Requirements: [1.2](requirements.md#1.2), [2.3](requirements.md#2.3), [2.5](requirements.md#2.5) -- [ ] 19. Write tests for the catch-up fixture writer and the seeded fixtures <!-- id:9jd85w3 -->+- [x] 19. Write tests for the catch-up fixture writer and the seeded fixtures <!-- id:9jd85w3 --> - `TodayFixtureTests`: one exact, one estimated and one caught-up catch-up work with past confirmation times - `M4ScaleFixtureTests`: every catch-up work in the schedule layer carries a latest and an override - Blocked-by: 9jd85w2 (Implement progress in todaySchedule, ScheduledWork and ReleaseRow) - Stream: 1 - Requirements: [10.1](requirements.md#10.1) -- [ ] 20. Implement CatchUpFixtureWriter and seed TodayFixture and the M4 schedule layer <!-- id:9jd85w4 -->+- [x] 20. Implement CatchUpFixtureWriter and seed TodayFixture and the M4 schedule layer <!-- id:9jd85w4 --> - `#if DEBUG || ASTERISM_PERFORMANCE_TESTING`; writes a record with a caller-given confirmation time - `AppLibraryModel.seedTodayWork` and `seedM4ScheduleLayer` - Blocked-by: 9jd85w3 (Write tests for the catch-up fixture writer and the seeded fixtures)@@ -189,7 +189,7 @@ references: ## App -- [ ] 21. Write tests for CatchUpText states, plurals, labels and ordering <!-- id:9jd85w5 -->+- [x] 21. Write tests for CatchUpText states, plurals, labels and ordering <!-- id:9jd85w5 --> - Singular and plural chapter words; the `as of` suffix only after 7 days; exact, estimated, caught-up and unknown labels - Ordering: exact and estimated by behind, then caught up, then unknown by read day, ties in title order - Banner text and primary button label per work status@@ -198,7 +198,7 @@ references: - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [2.7](requirements.md#2.7), [3.1](requirements.md#3.1) - References: Asterism/AsterismTests/TodayShelfTextTests.swift -- [ ] 22. Implement the card rows, row menu and caught-up banner <!-- id:9jd85w6 -->+- [x] 22. Implement the card rows, row menu and caught-up banner <!-- id:9jd85w6 --> - `TodayText.swift` and `TodaySections.swift`; 4 pt bar hidden from VoiceOver; menu and banner on the current day only - Banner uses `constellationCard` with secondary and tertiary button styles; Move to Reading and Mark Finished go through `AppLibraryModel.setReadingStatus` - Blocked-by: 9jd85w5 (Write tests for CatchUpText states, plurals, labels and ordering), 9jd85vu (Implement the catch-up repository calls)@@ -206,7 +206,7 @@ references: - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [2.6](requirements.md#2.6), [2.7](requirements.md#2.7), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [6.1](requirements.md#6.1), [6.3](requirements.md#6.3) - References: Asterism/Asterism/Views/TodaySections.swift -- [ ] 23. Write SetLatestModel unit tests and the Today and work page UI tests <!-- id:9jd85w7 -->+- [x] 23. Write SetLatestModel unit tests and the Today and work page UI tests <!-- id:9jd85w7 --> - Model: prefill E, R or empty; estimated mark while E differs from L or the flag is on and untouched; behind caption including equal and below; switch hidden without release days; override edit maps to set or clear; conflict keeps drafts - UI on the seeded Today fixture: exact, estimated and unknown rows; banner Move to Reading and Not yet; sheet Save and Cancel; work page row and its absence in edit mode; no banner on another day; accessibility text size - Identifiers: `today-set-latest-sheet`, `today-catchup-banner-<id>`, `work-detail-latest-released`@@ -215,7 +215,7 @@ references: - Requirements: [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [4.7](requirements.md#4.7), [4.8](requirements.md#4.8), [4.9](requirements.md#4.9), [4.10](requirements.md#4.10), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3) - References: Asterism/AsterismUITests/TodayUITests.swift -- [ ] 24. Implement SetLatestModel, SetLatestSheet, its route, the work page row and the AppLibraryModel calls <!-- id:9jd85w8 -->+- [x] 24. Implement SetLatestModel, SetLatestSheet, its route, the work page row and the AppLibraryModel calls <!-- id:9jd85w8 --> - `ViewModels/SetLatestModel.swift`, `Views/SetLatestSheet.swift`; `presentedSetLatest` on `AppNavigation`, presented on `ContentView` beside `presentedAnnouncement` - Work page row in the status line near `WorkDetailView.swift:712`, hidden in edit mode - `AppLibraryModel.commitCatchUpProgress` and `setReadingStatus` refresh Today like the existing write helpers@@ -226,7 +226,7 @@ references: ## Verification -- [ ] 25. Record the after measurement and compare it with the baseline <!-- id:9jd85w9 -->+- [x] 25. Record the after measurement and compare it with the baseline <!-- id:9jd85w9 --> - Same filter and host conditions as task 1, at least three runs, with the seeded M4 layer - The arm stays under its 2 s budget; record both sets and the delta in `verification-run.md` - If the delta is material, apply the design's suffix-maximum fallback and re-measure
diff --git a/specs/catch-up-progress/verification-run.md b/specs/catch-up-progress/verification-run.mdnew file mode 100644index 00000000..e6c2126d--- /dev/null+++ b/specs/catch-up-progress/verification-run.md@@ -0,0 +1,189 @@+# Verification Run: Catch-up Progress++## Before measurement (task 1)++**Date:** 2026-09-27 AEST. **Branch:** `feature/catch-up-progress` at+`5d51ce90`, before any Core change for this feature. **Host:** `Mac13,1`+(Apple M1 Max, 10 cores), macOS 27.0 (26A428). This was a host-only release+`swift test` run through the Makefile; no device or `Personal` target ran.++```sh+make test-performance-m4 \+ PERFORMANCE_FILTER='M4ToleratedScalePerformanceTests/todayPublication' \+ RUNS=3 PERFORMANCE_LOG=/tmp/catch-up-progress-before.log+```++Each run executed exactly one test in one suite and passed (`EXIT=0`). The+release test bundle took 482.21 s to build on the first run; later builds took+under a second. Build time is outside the measured arm. `CONTROLLED` was unset,+so the test asserted its 2 s median budget and reported p95 without asserting+it. Each run measured 20 samples over the existing M4 schedule fixture.++| Run | Median | p95 | Min | Max | Sample spread |+|---|---:|---:|---:|---:|---:|+| 1 | 0.886154 s | 0.894972 s | 0.874084 s | 0.899475 s | 1.03× |+| 2 | 0.877965 s | 0.895705 s | 0.858525 s | 0.904544 s | 1.05× |+| 3 | 0.880109 s | 0.892700 s | 0.866952 s | 0.900300 s | 1.04× |++The median of the three run medians is **0.880109 s**. Their range is+**0.877965–0.886154 s** (0.008189 s; 1.009× between the extremes). All three+are below the arm's 2 s budget. These are host measurements, comparable with a+later run of the same filtered command on this host. The after measurement and+before/after delta follow.++## After measurement (task 25)++**Date:** 2026-09-27 AEST. **Branch:** `stream/catch-up-progress-7-1` at+`dc9cf1f7`, including the Today release-row Work-status prerequisite. **Host:**+the same `Mac13,1` (Apple M1 Max, 10 cores), macOS 27.0 (26A428). This was a+host-only release test through the Makefile; no device or `Personal` target ran.++```sh+make test-performance-m4 \+ PERFORMANCE_FILTER='M4ToleratedScalePerformanceTests/todayPublication' \+ RUNS=3 PERFORMANCE_LOG=/private/tmp/catch-up-progress-after-final.log+```++The fresh final log has exactly three records, each over 20 samples. The command+exited 0, and each run executed exactly one test in one suite and passed.+`CONTROLLED` was unset, as in the before measurement, so the test asserted its+2 s median budget and reported p95 without asserting it. The release bundle was+already built before this final pass; build time is outside the measured arm.++| Run | Median | p95 | Min | Max | Sample spread |+|---|---:|---:|---:|---:|---:|+| 1 | 0.846152 s | 0.881856 s | 0.842230 s | 0.896479 s | 1.06× |+| 2 | 0.843118 s | 0.864008 s | 0.837350 s | 0.870294 s | 1.04× |+| 3 | 0.842446 s | 0.861390 s | 0.837390 s | 0.871851 s | 1.04× |++The median of the after run medians is **0.843118 s**, with a range of+**0.842446–0.846152 s** (0.003706 s; 1.004× between extremes). Against the+before median of **0.880109 s**, the observed change is **−0.036991 s+(−4.20%)**. Every after run is below the 2 s budget. There is no measured+regression, so the design's suffix-maximum fallback was not needed. This is a+same-host comparison of the full Today publication arm, not an isolated timing+of catch-up derivation.++An earlier three-run pass recorded passing samples but its `run_silent` wrapper+timed out immediately after the third test's pass output. Those samples were+discarded; the table above comes only from the fresh pass whose Makefile command+exited 0.++## Core values verification environment++The first full Core runs, including a run after login-keychain unlock, failed+only in Pending-capture drain (57 issues), Pending-capture spool (46) and+Preserve-first share flow (20). The error was Cocoa 257 / POSIX 1 on protected+temporary spool files. A standalone Foundation/POSIX write-close-reopen probe+reproduced the failure outside the repository only with `completeUnlessOpen`+protection. After the owner unlocked the screen, the unchanged probe passed.+The focused catch-up and existing JSON-blob consumer suites passed throughout.+The full `make test-core` rerun after screen unlock exited 0, including all+three previously failing suites. The Core values review corrected the Sydney+DST interval and added fixed millisecond expectations and tie-break checks.++## Schema V17 verification++The focused recorded-store, marker, model-contract, graph-baseline, writer and+group-election tests passed. After updating stale marker expectations in test+fixtures, full `make test-core` exited 0 with no compiler warnings. Review+checked the two-column schema delta, nil values after conversion, independent+group election and writer idempotence.++`make build-mac` compiled the changed sources but failed signing the Mac share+extension with `errSecInternalComponent`, confirmed with `PIPE_PRETTY=`.+No signing settings were changed. A successful signed Mac build remains owed.++## Repository writes and convergence/archive verification++Streams 1 and 2 ran in isolated worktrees and each passed full `make test-core`.+Focused simulator suites passed: `WorkDetailModelTests`,+`EntryDetailModelTests` and `SettingsBackupModelTests`. The 16/17 golden archive+was recorded and then verified normally. Both branches merged without conflicts.++The integrated `make test-core CORE_TEST='CatchUp|BackupV16ArchiveTests'`+exited 0. The rebuild reported existing Foundation Models deprecations in+untouched Intelligence sources. Review added the presented-status duplicate+regression, explicit archive bounds, torn/equal/older import coverage and+corrupt-blob/old-envelope refusal checks. The schema/archive envelope window+is closed; the signed Mac build remains the outstanding host gate.++## Today derivation verification++Full `make test-core` exited 0 after the Today row and fixture changes.+Focused `TodayDayPlanTests`, `TodayFixtureTests`, `M4ScaleFixtureTests`, and+simulator `TodayFixtureSeedingTests` and `TodayShelfTextTests` passed.+No warnings were reported from edited Today/fixture sources. The expanded+Today fixture has seven works and four entries, preserving Recent ordering;+all 66 M4 catch-up works carry confirmation and override records.++## App and final integration verification (2026-09-28)++All 25 implementation tasks are complete. The results below distinguish a full+command's exit from later focused rechecks; the full phone UI gate is not green.++| Check | Result |+|---|---|+| Final `make test-core` | Exit 0, no compiler warnings or protected-file failures; includes `ReleaseRow.workStatus`. |+| `make test-quick SKIP_MAC=1` | Exit 0, all 1,952 App unit tests passed after updating the expanded fixture's Work count. |+| Focused App tests | Text, SetLatest model, WorkDetail model, and new catch-up journeys passed. |+| Initial full phone `make test-ui` | Xcode exit 65 / make exit 2: 199 tests, 176 passed, 2 skipped, 21 failed, 6,198 s. All new catch-up journeys passed. |+| Bounded phone recheck | 20 explicit selectors: 16 passed, 4 failed. CharacterExtraction passed on retry. Creator and merge Back assertions were corrected after this bundle compiled and both passed in a final 2-case run. The corrected current-day Today case also passed. |+| Initial iPad `make test-ui-ipad` | Exit 65: 33 tests, 27 passed, 6 failed. |+| iPad rerun | Exit 65: 32 of 33 passed; only a stale Places assertion remained. After correction, the isolated Places case passed (1/1). There was no subsequent all-green 33-case command. |+| Final `make build-mac` | Changed App source compiled, then Mac share-extension signing failed with `errSecInternalComponent` (Xcode exit 65 / make exit 2). No changed-App compiler warnings. |++Review fixed an invalid-input caption, refreshed the retained Work page after a+sheet Save, deferred refresh while an editor is active, and fenced edit entry+while loading. The largest-text journey verifies custom control targets;+standard toolbar controls use the existing system-control operability check+because UIKit supplies hit slop outside their visual frames. Save/Cancel,+background draft retention, all-caught-up layout, future-day restrictions and+the Work-page row were exercised in the simulator.++The inherited UI corrections are in a separate commit from the feature. They+enter All works from the Library hub, reveal lazy rows before querying them,+and scope wide-layout gestures to the correct pane. The merge Back expectation+was checked against the identical pre-feature callback: it returns to the Works+root (now the Library hub), then the test explicitly opens All works to inspect+the surviving row. No production routing was changed for those tests.++### Remaining verification limits++- `AccessibilityJourneyUITests.testTheEntryTitleCardsWorkNameOpensTheWorkAtLargestDynamicType`+ failed in the full phone run. The exact failure is documented on an untouched+ pre-feature commit in `docs/agent-notes/testing.md`; it was not included in the+ bounded recheck.+- `WorkCoverUITests.testSeededCoveredWorkScenarioReachesRecent` and+ `WorkCoverUITests.testTheCoverIsDrawnWhereTheWorkHasOneAndNowhereElse` failed in+ both the broad and focused runs. Those tests were not changed. Their failures+ remain unresolved; unchanged source alone is not proof that they passed or+ failed previously.+- A successful signed Mac build remains owed. The final attempt was build-only;+ no app was installed or launched and no signing/security settings changed.+- The owner's two-device `Development` check in `runbook.md` remains required+ before merge. Host and simulator tests cannot verify CloudKit delivery.++### Integration and evidence++The App feature and inherited test corrections landed as `334bdcac` and+`b591ef7b`. The performance stream includes the same required Work-status+projection prerequisite. Integration resolved the duplicate test-helper change+by taking the tested App version. Before final documentation, production and+test files matched `b591ef7b` exactly; only task completion and performance+notes differed. All stream branches were merged and their worktrees removed.++Captured logs remain under `/private/tmp/`:++- `asterism-catchup-core-final.log`+- `asterism-stream3-test-quick.log`+- `asterism-stream3-test-ui.log`+- `asterism-stream3-focused-recheck.log`+- `asterism-stream3-final-navigation.log`+- `asterism-catchup-ipad-final-recheck.log`+- `asterism-catchup-mac-final.log`++UI runs that stalled without a command exit were not counted as successful.+Later runs used `XCODE_TEST_FLAGS='-collect-test-diagnostics never' PIPE_PRETTY=`+with captured raw output. Assertions and result reporting stayed enabled;+automatic failure attachments were unavailable in that mode.
diff --git a/specs/catch-up-progress/implementation.md b/specs/catch-up-progress/implementation.mdnew file mode 100644index 00000000..d6e14229--- /dev/null+++ b/specs/catch-up-progress/implementation.md@@ -0,0 +1,47 @@+# Catch-up Progress Implementation++## Beginner Level++### What changed++You can record the latest released chapter and, when needed, correct the last chapter you read. Today shows whether the latest number is confirmed, estimated, unknown, or already reached. The same Set latest sheet is available from Today and the work page.++### Why it matters++A release schedule can advance the estimate without repeated edits. Reopening an older chapter does not move your progress backwards. Reaching the latest chapter offers an action; your reading status changes only when you tap it.++### Key concepts++A confirmation records what you believe is available at a particular time. An estimate counts scheduled releases after that point. An override corrects reading progress until later captured chapter notes supersede it.++## Intermediate Level++### Changes overview++CatchUpRecord stores the confirmation and override as two independently timestamped values. CatchUpProgress derives display state from these values, eligible whole-number chapter notes, work status, release days and an explicitly supplied calendar. Schema V17 adds two optional Data blobs; V16 remains the migration source and V15 is retired.++### Implementation approach++The effective latest chapter is the larger of two lower bounds: the confirmed latest plus eligible releases, and reading progress plus eligible releases. SetLatestModel keeps a draft until Save; repository writes compare the expected values before committing. Work metadata edits rebase progress under the old schedule inside the same transaction. Root-owned sheet presentation survives layout changes.++### Trade-offs++Two blobs preserve each tuple as a value while allowing confirmation and override to converge independently. Progress stays outside authored metadata and variant identity. Archives 16/17 use six flat fields. Estimates remain derived instead of creating background writes; duplicate reconciliation and import never invent a new confirmation time.++## Expert Level++### Technical deep dive++The fold deterministically elects confirmation and override independently, including timestamped override clears. Narrow writes require the addressed work and reject stale bases. Import folds progress before authored-content and modifiedAt guards, without bumping modifiedAt or adding progress-only work to applied membership changes. Metadata rebasing reads current entries under the write lock and uses the caller’s calendar.++### Architecture impact++Progress is replicated reader state rather than authored work content. The same derived last-read value also feeds release-shelf badges. Work-page refresh after sheet save is deferred during metadata editing to protect the draft. Forecast days avoid present-day action banners. Counts are capped at 9999 and fractional chapter labels are excluded instead of rounded.++### Potential issues++Watch real-device convergence and schedule/status transitions while trialling the feature. Reconciliation deliberately does not rebase, so a mismatch can remain until a later explicit Save. Previously recorded performance samples show no regression, but the outstanding signed Mac build, unresolved broader UI failures and owner two-device check still limit verification.++## Completeness Assessment++All 25 implementation tasks are complete. The review and three-level explanation identified no missing implementation requirement or undocumented design divergence. Verification remains incomplete: a signed Mac build is required before push; the recorded broader UI runs are not wholly green; the owner’s two-device Development sync check remains before merge. See verification-run.md for exact historical results. This review ran make verify-identity successfully, but launched no fresh test suite because the prescribed runner catalog did not detect this Xcode project at the repository root. Design preference remains subject to the owner’s trial.