Per-date release dismissal, synced action history, Today and Shortcuts integration.
Needs verification
The full Core gate now passes: 3,293 passed, 55 skipped, and zero failed tests. The two live model calls and both plain-text provider cases passed. A signed Mac build and real two-device CloudKit delivery check remain open.
02d82a64 T-2374: Document the no-episode-today specification 8c6a9d91 T-2374: Implement no-episode core storage and behavior b1ccb275 T-2374: Align no-episode clears with logical note dates 9f2bb76a T-2374: changelog for phase 1 24d21bc9 T-2374: Record core phase progress and scan cache decision 7f07bb3b T-2374: integrate no-episode actions into Today and shortcuts bf12d4aa T-2374: correct selected-date release actions and prepared intent failures e10ff1d7 T-2374: changelog for phase 2 adf556ec T-2374: Mark no-episode implementation complete 8bfb9f41 T-2374: Fix per-release carousel menu targeting working-tree Pre-push review fixes and implementation explanation Readers can mark a scheduled release as having no episode for the day they are viewing, then undo it from the same menu. It stays on the shelf with a minus badge and stops increasing expected unread counts.
Today and the Chapters Releasing Today shortcut agree that a known non-release needs no attention. A real note replaces the mark and keeps it cleared even if the note later moves.
A civil day is a calendar date, so traveling across time zones does not move the mark.
V18 stores immutable per-work actions. A pure history fold resolves mark and clear evidence; repository commands save under the exclusive lock, and note mutation hooks write clears in their existing transactions. Today, catch-up counts, backups, and the intent answer consume the same history.
Actions are retained until work deletion so older offline devices and backups cannot resurrect cleared marks. A history-token checkpoint avoids repeated note scans on unchanged publications.
A mark is active only when its observed clear-key set covers every explicit or referenced clear for that work and civil date. This set-union rule is delivery-order independent. Stable note keys plus fresh arrival/overlap clears prevent mark resurrection after note reassignment. Targeted index reads validate only the requested work; whole-library operations still validate every action.
Specified app, Core, backup, and shortcut behavior is implemented. Real CloudKit delivery remains unverified, and the broad Core gate passes after the two unrelated host compatibility fixes.
Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift
Why it matters. An unseen undo defeats a mark regardless of CloudKit arrival order.
What to look at. NoEpisodeHistory.swift:8-156
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift
Why it matters. The selected date, eligibility checks, and save outcome stay inside one locked write.
What to look at. LibraryRepository+NoEpisode.swift:54-120
Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift
Why it matters. Moving or deleting a note cannot bring an old no-episode mark back.
What to look at. NoEpisodeWriter.swift:59-160
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift
Why it matters. Marks and clears survive restart, sync, and supported backup restore.
What to look at. AsterismSchemaV18.swift:4-40
Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift
Why it matters. The shelf and expected unread counts reflect known non-releases without changing confirmed progress.
What to look at. TodayDayPlan.swift:499-555
Asterism/Asterism/Views/TodayView.swift
Why it matters. A selection change while a save is in flight cannot redirect the user’s action.
What to look at. TodayView.swift:590-622
Packages/AsterismCore/Sources/AsterismCore/NoEpisodeIndex.swift
Why it matters. A damaged action for another work no longer breaks a targeted work read.
What to look at. NoEpisodeIndex.swift:6-36
An unseen clear defeats a mark; a new mark after observing that clear may succeed. This is independent of delivery order.
Old devices and supported backups can return later, so actions are retained until the work is deleted.
The latest transaction token and time-zone identifier certify an unchanged scan, avoiding an observed performance regression without widening the budget.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | NoEpisodeIndex targeted reads | A corrupt action for one work caused unrelated targeted work reads to fail. | Grouped raw rows by work and delayed validation to history(for:); allActions still validates the full table. Added a regression. |
| major | NoEpisodeHistory note keys | Validation accepted malformed note clear keys from a checksum-valid archive. | Require canonical entry/work UUIDs, integer milliseconds, and the action day; preserve historical work UUIDs after work merge. Added key-shape regressions. |
| major | NSItemProvider text bridge | Concrete public.plain-text providers were ignored on macOS 27 because this host reports that plain text does not conform to public.text. | Recognize standard plain-text identifiers explicitly; both concrete provider regressions pass. |
| major | Foundation Models live test classification | Two host model requests returned nested service error 1008 outside the typed GenerationError known-issue matcher. | Match only the observed FoundationModels wrapper and nested service code 1008; synthetic regressions keep decoding errors fatal. Both live calls passed in the final run. |
Source: local run at 2026-09-29T17:10:24.815783+10:00 · snapshot 8bfb9f419757c5126128f491550b2856e4fdb7de (dirty working tree)
Baseline: none
Execution: passed · JUnit: 1 file · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 3293 passed · 0 failed · 55 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 7619e63ac4995d8f4eeb22af3a90ba8bf34d91ef.
174 files: 164 code · 10 docs. Click to expand.
diff --git a/Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swift b/Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swiftindex c781e4b4..ebfb5adb 100644--- a/Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swift+++ b/Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swift@@ -34,7 +34,7 @@ struct ChaptersReleasingTodayIntent: AppIntent { // One step, so a cold library is opened once for both reads: the // Today read, and the summaries the returned work values carry. guard let answer = try await IntentOutcome.read(- model.intentBroker, intent: "chapters releasing today",+ model.intentBroker, intent: "chapters releasing today", preparing: calendar, { library -> (releases: [ReleaseAnswer], works: [WorkSummary]) in let presentation = try await library.todayPresentation(calendar: calendar) let releases = IntentAnswers.releasingToday(
diff --git a/Asterism/Asterism/Intents/IntentLibraryBroker.swift b/Asterism/Asterism/Intents/IntentLibraryBroker.swiftindex 2be9f0a8..4802275c 100644--- a/Asterism/Asterism/Intents/IntentLibraryBroker.swift+++ b/Asterism/Asterism/Intents/IntentLibraryBroker.swift@@ -64,6 +64,12 @@ final class IntentLibraryBroker { /// The snapshot refresh the last resident write started, kept so a test can /// await it. It runs outside the turn: the answer does not wait for it. private(set) var pendingWriteRefresh: Task<Void, Never>?+ /// Test seam for a preparation failure on a cold repository; production+ /// always calls the repository operation through this closure.+ var prepareToday: @Sendable (any LibraryProviding, Calendar) async throws -> Void = {+ library, calendar in+ try await library.prepareNoEpisodeNotes(calendar: calendar)+ } init(model: AppLibraryModel) { self.model = model@@ -100,6 +106,23 @@ final class IntentLibraryBroker { try await withLibrary(wroteIf: { _ in writes }, step) } + /// Prepare note clears in the captured calendar before a cold or resident+ /// Today read. Preparation may save actions, so a cold session leaves an+ /// export-owed marker even when the caller's result is read-only.+ func withPreparedToday<T: Sendable>(+ calendar: Calendar,+ _ step: @escaping @Sendable (any LibraryProviding) async throws -> T+ ) async throws(IntentLibraryError) -> T {+ let prepare = prepareToday+ let answer: Result<T, IntentLibraryError> = try await withLibrary(writes: true) { library in+ try await prepare(library, calendar)+ // Preparation can commit clears. Return the later read's failure as+ // a value so the broker still records the cold export obligation.+ return await self.outcome(of: step, on: library)+ }+ return try answer.get()+ }+ /// The same, for a step whose answer says whether it wrote — the add /// intent's `createWorkUnlessPresent`, which writes nothing when it answers /// `.present`. What follows a write follows only when `wrote` says so.@@ -232,7 +255,8 @@ final class IntentLibraryBroker { let repository: LibraryRepository do { repository = try await LibraryRepository.openForExtension(- configuration, capabilities: model.capabilities+ configuration, capabilities: model.capabilities,+ noteCalendar: { Calendar.current } ).repository } catch { // No marker, a marker this build cannot open, a store that fails
diff --git a/Asterism/Asterism/Intents/IntentOutcome.swift b/Asterism/Asterism/Intents/IntentOutcome.swiftindex ae6e14f9..c1402f1f 100644--- a/Asterism/Asterism/Intents/IntentOutcome.swift+++ b/Asterism/Asterism/Intents/IntentOutcome.swift@@ -46,9 +46,13 @@ nonisolated enum IntentOutcome { @MainActor static func read<T: Sendable>( _ broker: IntentLibraryBroker, intent: String,+ preparing calendar: Calendar? = nil, _ step: @escaping @Sendable (any LibraryProviding) async throws -> T ) async throws -> T? { do {+ if let calendar {+ return try await broker.withPreparedToday(calendar: calendar, step)+ } return try await broker.withLibrary(writes: false, step) } catch { switch refusal(error, intent: intent) {
diff --git a/Asterism/Asterism/Intents/NotesFromTodayIntent.swift b/Asterism/Asterism/Intents/NotesFromTodayIntent.swiftindex df09cff8..a27659e3 100644--- a/Asterism/Asterism/Intents/NotesFromTodayIntent.swift+++ b/Asterism/Asterism/Intents/NotesFromTodayIntent.swift@@ -32,7 +32,7 @@ struct NotesFromTodayIntent: AppIntent { let calendar = model.intentCalendar let currentDay = CivilDay(Date(), calendar: calendar) guard let notes = try await IntentOutcome.read(- model.intentBroker, intent: "notes from today",+ model.intentBroker, intent: "notes from today", preparing: calendar, { library in IntentAnswers.notesToday( try await library.todayPresentation(calendar: calendar),
diff --git a/Asterism/Asterism/Layout/AppScreens.swift b/Asterism/Asterism/Layout/AppScreens.swiftindex 701619ed..0d9970c8 100644--- a/Asterism/Asterism/Layout/AppScreens.swift+++ b/Asterism/Asterism/Layout/AppScreens.swift@@ -124,6 +124,9 @@ struct AppScreens { onSetReadingStatus: { id, status in try await model.setReadingStatus(id: id, to: status) },+ onSetNoEpisode: { id, day, marked in+ try await model.setNoEpisode(workID: id, day: day, marked: marked)+ }, // 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).
diff --git a/Asterism/Asterism/Localizable.xcstrings b/Asterism/Asterism/Localizable.xcstringsindex 2d416398..552793d5 100644--- a/Asterism/Asterism/Localizable.xcstrings+++ b/Asterism/Asterism/Localizable.xcstrings@@ -585,6 +585,10 @@ "comment" : "A title for an alert that displays when a reading status update fails.", "isCommentAutoGenerated" : true },+ "Couldn’t update release" : {+ "comment" : "A title for an alert that a release couldn't be updated.",+ "isCommentAutoGenerated" : true+ }, "Count up on release days" : { "comment" : "A toggle that allows users to count up on release days.", "isCommentAutoGenerated" : true@@ -1823,6 +1827,10 @@ "comment" : "The title of the review screen.", "isCommentAutoGenerated" : true },+ "Undo no episode" : {+ "comment" : "A button that undoes the action of marking a release as not having an episode.",+ "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
diff --git a/Asterism/Asterism/UITestLaunchSupport.swift b/Asterism/Asterism/UITestLaunchSupport.swiftindex aa5f745f..9d855845 100644--- a/Asterism/Asterism/UITestLaunchSupport.swift+++ b/Asterism/Asterism/UITestLaunchSupport.swift@@ -105,6 +105,8 @@ enum UITestFixtureKind: Equatable { /// from a launch. `seeded-works-options` and the rest are left alone: their /// suites assert exact orders that a fourth work would move. case today+ /// Two scheduled releases for the no-episode menu journey.+ case noEpisode /// Whether the seeded shape needs a second open before its diagnoses are /// complete. `.invalidSiteTuple` is produced only by the full@@ -167,6 +169,7 @@ enum UITestLaunchSupport { /// The three scheduled works and the two dated days the Today journeys run /// over. static let seededTodayScenario = "seeded-today"+ static let seededNoEpisodeScenario = "seeded-no-episode" /// One scenario per tolerated state, plus the illegal-tuple state that /// carries the re-teach route and the empty-library shape Q15 hoists the /// banner for. Keyed by the fixture's own raw value so a new shape needs no@@ -442,6 +445,8 @@ enum UITestLaunchSupport { fixture = .coveredWorkMissingBytes case seededTodayScenario: fixture = .today+ case seededNoEpisodeScenario:+ fixture = .noEpisode case let scenario where scenario.hasPrefix(seededScaleM4ToleratedPrefix): guard let state = M4ToleratedFixtureState( rawValue: String(scenario.dropFirst(seededScaleM4ToleratedPrefix.count)))
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex 6fe48b73..d0bbc197 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -28,6 +28,12 @@ nonisolated private struct CalendarKey: Equatable, Sendable { } } +private struct NoEpisodeRefreshFailure: LocalizedError {+ var errorDescription: String? {+ "The no-episode change was saved, but Asterism could not refresh Today. Try reopening the screen."+ }+}+ /// Root app state driving the loading/ready/unavailable lifecycle. @MainActor @Observable public final class AppLibraryModel {@@ -323,8 +329,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 BackupV16SnapshotProviding).- private var backupRepository: (any BackupV16SnapshotProviding)?+ /// Retains the concrete repository for backup export (conforms to BackupV17SnapshotProviding).+ private var backupRepository: (any BackupV17SnapshotProviding)? /// 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.@@ -597,6 +603,7 @@ public final class AppLibraryModel { var repo = try await LibraryRepository.openForApp( configuration, capabilities: capabilities,+ noteCalendar: { Calendar.current }, mirroring: mirroringOpenHooks ).repository // Ends before the seeding below, which belongs to no phase: a@@ -622,6 +629,7 @@ public final class AppLibraryModel { repo = try await LibraryRepository.openForApp( configuration, capabilities: capabilities,+ noteCalendar: { Calendar.current }, mirroring: mirroringOpenHooks ).repository }@@ -1247,6 +1255,7 @@ public final class AppLibraryModel { guard let repo = repository else { return nil } let cycle = enterCycle() do {+ try await repo.prepareNoEpisodeNotes(calendar: cycle.calendar) let presentation = try await repo.todayPresentation(calendar: cycle.calendar) // Beside the presentation for `refreshAll`'s reason: the name a // reader sees belongs to the same cycle as the rows it names.@@ -1301,6 +1310,7 @@ public final class AppLibraryModel { // and which generation this cycle entered against. let cycle = enterCycle() do {+ try await repo.prepareNoEpisodeNotes(calendar: cycle.calendar) let presentation = try await repo.todayPresentation(calendar: cycle.calendar) // Q17's injection point, immediately before the read it stands for. // Production passes nil; a UI-test launch and `AppLibraryModelTests`@@ -1574,6 +1584,26 @@ public final class AppLibraryModel { return outcome } + /// The menu supplies its captured day; changing the visible selection while+ /// the repository saves cannot redirect the action to a different date.+ func setNoEpisode(+ workID: UUID, day: CivilDay, marked: Bool+ ) async throws -> LibraryWriteOutcome {+ guard let repo = repository else { throw LibraryNotOpen() }+ let outcome: LibraryWriteOutcome+ if marked {+ outcome = try await repo.markNoEpisode(+ workID: workID, day: day, calendar: calendar)+ } else {+ outcome = try await repo.undoNoEpisode(workID: workID, day: day)+ }+ guard outcome == .committed else { return outcome }+ guard await refreshDiagnosesAndSnapshots() != nil else {+ throw NoEpisodeRefreshFailure()+ }+ return outcome+ }+ /// The banner's expected status is always Catching up, its visible basis. func setReadingStatus( id: UUID, to status: ReadingStatus@@ -2251,6 +2281,7 @@ public final class AppLibraryModel { opened = try await LibraryRepository.openForApp( configuration, capabilities: capabilities,+ noteCalendar: { Calendar.current }, mirroring: mirroringOpenHooks ).repository } catch is CancellationError {@@ -2834,11 +2865,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() -> BackupV16Exporter? {+ private func backupExporter() -> BackupV17Exporter? { guard let repo = backupRepository, let config = resolvedConfiguration else { return nil } let stagingDir = config.rootDirectory .appending(path: "Library/Caches/BackupExports")- return BackupV16Exporter(repository: repo, stagingDirectory: stagingDir)+ return BackupV17Exporter(repository: repo, stagingDirectory: stagingDir) } /// The per-entry markdown export model (Req 1.5), staged beside the backup@@ -3376,6 +3407,32 @@ public final class AppLibraryModel { Self.logger.debug("Seeded the today UI test fixture") } + /// Two due works with no notes: one pending and one already marked, so UI+ /// tests can exercise both menu directions without changing seeded-today.+ private func seedNoEpisodeFixture(in repo: LibraryRepository) async throws {+ let calendar = calendarSource()+ let day = CivilDay(Date(), calendar: calendar)+ guard let weekday = ReleaseDay(calendarWeekday: calendar.component(.weekday, from: Date()))+ else { return }+ for (title, marked) in [("Amber Signal", false), ("Blue Signal", true)] {+ let slug = title.lowercased().replacingOccurrences(of: " ", with: "-")+ let work = try await repo.createWork(NewWorkDraft(+ displayTitle: title, hostname: "https://release.test/\(slug)"))+ let current = try await repo.work(id: work.id)+ _ = try await repo.updateWork(+ id: work.id, basis: WorkEditBasis(work: current),+ draft: WorkMetadataDraft(+ displayTitle: title, typeAssignment: current.typeDisplay.assignment,+ genreTags: current.genreTags, genericNotes: "",+ workStatus: .ongoing, readingStatus: .reading, verdict: "",+ releaseDays: [weekday], membership: current.membership,+ thumbnail: .keep), calendar: calendar)+ if marked {+ _ = try await repo.markNoEpisode(workID: work.id, day: day, calendar: calendar)+ }+ }+ }+ #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.@@ -3894,6 +3951,11 @@ public final class AppLibraryModel { return } + if fixture == .noEpisode {+ try await seedNoEpisodeFixture(in: repository)+ return+ }+ if fixture == .composed { // Production opens through the app-role opener, so the composed // fixture seeds through the ordinary bootstrap, which creates and
diff --git a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift b/Asterism/Asterism/ViewModels/SettingsBackupModel.swiftindex c958acfd..86340e9a 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 `BackupV16Exporter` to this protocol via extension below.+/// surface. Conforms `BackupV17Exporter` 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: BackupV16Metadata) async throws -> BackupExportResult+ func export(metadata: BackupV17Metadata) async throws -> BackupExportResult func cleanup(_ result: BackupExportResult) func scavengeStaleFiles() } -extension BackupV16Exporter: BackupExporting {}+extension BackupV17Exporter: BackupExporting {} // MARK: - Export Stage @@ -87,7 +87,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable { stagedFileURL = nil do {- let metadata = BackupV16Metadata(+ let metadata = BackupV17Metadata( 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? BackupV16ExportError,+ guard let exportError = error as? BackupV17ExportError, 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 BackupV16ExportError:+ case let error as BackupV17ExportError: 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: BackupV16ExportError) -> String {+ private static func exportMessage(for error: BackupV17ExportError) -> 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 == BackupV16ExportError.thumbnailField:+ where field == BackupV17ExportError.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 BackupV16ExportError:+ case let e as BackupV17ExportError: 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. ///- /// `BackupV16ExportError.description` is written for the reader and names+ /// `BackupV17ExportError.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: BackupV16ExportError) -> String {+ private static func exportDiagnosticCategory(_ error: BackupV17ExportError) -> String { switch error { case .unrepresentableValue(_, let field, _): "export: unrepresentable \(field)"
diff --git a/Asterism/Asterism/Views/TodaySections.swift b/Asterism/Asterism/Views/TodaySections.swiftindex 0e3ca197..0a6aae98 100644--- a/Asterism/Asterism/Views/TodaySections.swift+++ b/Asterism/Asterism/Views/TodaySections.swift@@ -128,13 +128,22 @@ struct TodayCover: View { struct ReleaseShelf: View { /// Already in shelf order (`ReleaseShelfText.ordered`). let rows: [ReleaseRow]+ let selectedDay: CivilDay+ let currentDay: CivilDay+ let calendar: Calendar let onSelect: (UUID) -> Void+ let onSetNoEpisode: (UUID, Bool) -> Void+ let isActionInFlight: (UUID) -> Bool var body: some View { ScrollView(.horizontal, showsIndicators: false) { LazyHStack(alignment: .top, spacing: 14) { ForEach(rows) { row in- ReleaseShelfItem(row: row, onSelect: onSelect)+ ReleaseShelfItem(+ row: row, onSelect: onSelect,+ selectedDay: selectedDay, currentDay: currentDay, calendar: calendar,+ onSetNoEpisode: onSetNoEpisode,+ isActionInFlight: isActionInFlight(row.id)) } } .scrollTargetLayout()@@ -154,6 +163,11 @@ struct ReleaseShelfItem: View { let row: ReleaseRow let onSelect: (UUID) -> Void+ let selectedDay: CivilDay+ let currentDay: CivilDay+ let calendar: Calendar+ let onSetNoEpisode: (UUID, Bool) -> Void+ let isActionInFlight: Bool @Environment(\.openURL) private var openURL @Environment(\.displayScale) private var displayScale@@ -169,8 +183,24 @@ struct ReleaseShelfItem: View { } var body: some View {- Button {- onSelect(row.id)+ Menu {+ if row.releaseState == .pending {+ Button(ReleaseShelfText.markActionTitle(+ selectedDay: selectedDay, currentDay: currentDay, calendar: calendar),+ systemImage: "minus") {+ onSetNoEpisode(row.id, true)+ }+ .disabled(isActionInFlight)+ } else if row.releaseState == .noEpisode {+ Button("Undo no episode", systemImage: "arrow.uturn.backward") {+ onSetNoEpisode(row.id, false)+ }+ .disabled(isActionInFlight)+ }+ if let url = row.primaryURL {+ Button("Open Work Page", systemImage: "safari") { openURL(url) }+ }+ Button("Go to Work", systemImage: "book") { onSelect(row.id) } } label: { VStack(alignment: .leading, spacing: 8) { cover@@ -182,21 +212,17 @@ struct ReleaseShelfItem: View { .frame(width: width, alignment: .leading) } .contentShape(Rectangle())+ } primaryAction: {+ onSelect(row.id) } .buttonStyle(.plain)- .contextMenu {- if let url = row.primaryURL {- Button("Open Work Page", systemImage: "safari") { openURL(url) }- }- Button("Go to Work", systemImage: "book") { onSelect(row.id) }- } .accessibilityLabel(ReleaseShelfText.label(row)) .accessibilityIdentifier(ReleaseShelfText.itemIdentifier(row.id)) } private var cover: some View { let shape = RoundedRectangle(cornerRadius: Self.coverRadius, style: .continuous)- let isRead = row.isNotedOnDay+ let isRead = row.isCompleted return TodayCover( workID: row.id, thumbnail: row.thumbnail, hostname: row.primaryHostname, baseSize: Self.coverSize, cornerRadius: Self.coverRadius@@ -212,8 +238,8 @@ struct ReleaseShelfItem: View { // multiplier, as a SwiftUI radius. .shadow(color: isRead ? .clear : AsterismColors.cyan.opacity(0.35), radius: 14) .overlay(alignment: .topTrailing) {- if isRead {- Image(systemName: "checkmark")+ if let symbol = ReleaseShelfText.completedSymbol(row) {+ Image(systemName: symbol) .font(.caption.weight(.bold)) .foregroundStyle(AsterismColors.cyan) .frame(width: 24, height: 24)
diff --git a/Asterism/Asterism/Views/TodayText.swift b/Asterism/Asterism/Views/TodayText.swiftindex 0bee5def..ad44f249 100644--- a/Asterism/Asterism/Views/TodayText.swift+++ b/Asterism/Asterism/Views/TodayText.swift@@ -276,23 +276,35 @@ nonisolated enum ChapterNumberText { nonisolated enum ReleaseShelfText { static let shelfIdentifier = "today-releases-shelf" + static func markActionTitle(+ selectedDay: CivilDay, currentDay: CivilDay, calendar: Calendar+ ) -> String {+ selectedDay == currentDay+ ? "No episode today"+ : "No episode on \(TodayDateText.abbreviated(selectedDay, calendar: calendar))"+ }+ static func itemIdentifier(_ id: UUID) -> String { "today-release-shelf-item-\(id.uuidString)" } /// The section header's trailing summary: `2 of 5 read`. static func summary(_ rows: [ReleaseRow]) -> String {- "\(rows.count(where: \.isNotedOnDay)) of \(rows.count) read"+ let read = rows.count(where: \.isNotedOnDay)+ let skipped = rows.count { $0.releaseState == .noEpisode }+ let base = "\(read) of \(rows.count) read"+ return skipped == 0 ? base : "\(base) · \(skipped) no episode" } /// The badge on an unread cover: the next chapter, where there is a whole /// number to add one to. Never guessed otherwise. static func badge(_ row: ReleaseRow) -> String? {- guard !row.isNotedOnDay, let next = row.nextChapter else { return nil }+ guard !row.isCompleted, let next = row.nextChapter else { return nil } return ChapterNumberText.short(next, type: row.typeDisplay) } static func label(_ row: ReleaseRow) -> String {+ if row.releaseState == .noEpisode { return "\(row.title), No episode" } if row.isNotedOnDay { return "\(row.title), read" } if let next = row.nextChapter { return "\(row.title), \(ChapterNumberText.spoken(next, type: row.typeDisplay)), not read yet"@@ -303,7 +315,19 @@ nonisolated enum ReleaseShelfText { /// Unread first, then read; each half keeps the order it arrived in, which /// is `titleOrder`. static func ordered(_ rows: [ReleaseRow]) -> [ReleaseRow] {- rows.filter { !$0.isNotedOnDay } + rows.filter(\.isNotedOnDay)+ rows.filter { !$0.isCompleted } + rows.filter(\.isCompleted)+ }++ static func completedSymbol(_ row: ReleaseRow) -> String? {+ switch row.releaseState {+ case .pending: nil+ case .noted: "checkmark"+ case .noEpisode: "minus"+ }+ }++ static func verticalDetail(_ row: ReleaseRow, line: String) -> String {+ row.releaseState == .noEpisode ? "No episode" : line } }
diff --git a/Asterism/Asterism/Views/TodayView.swift b/Asterism/Asterism/Views/TodayView.swiftindex 015e41fe..c095ff16 100644--- a/Asterism/Asterism/Views/TodayView.swift+++ b/Asterism/Asterism/Views/TodayView.swift@@ -81,6 +81,7 @@ struct TodayView: View { let onSelectWork: (UUID) -> Void let onSetLatest: (UUID) -> Void let onSetReadingStatus: (UUID, ReadingStatus) async throws -> LibraryWriteOutcome+ let onSetNoEpisode: (UUID, CivilDay, Bool) 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.@@ -129,6 +130,9 @@ struct TodayView: View { @State private var showingDuplicatesOnly = false @State private var catchUpActionError: String? @State private var showingCatchUpActionError = false+ @State private var noEpisodeActionsInFlight: Set<UUID> = []+ @State private var noEpisodeActionError: String?+ @State private var showingNoEpisodeActionError = false init( presentation: TodayPresentation,@@ -162,6 +166,7 @@ struct TodayView: View { onSelectWork: @escaping (UUID) -> Void = { _ in }, onSetLatest: @escaping (UUID) -> Void = { _ in }, onSetReadingStatus: @escaping (UUID, ReadingStatus) async throws -> LibraryWriteOutcome = { _, _ in .committed },+ onSetNoEpisode: @escaping (UUID, CivilDay, Bool) async throws -> LibraryWriteOutcome = { _, _, _ in .committed }, onPruneSelection: ((TodayVisibility) -> Void)? = nil, onShowSettings: (() -> Void)? = nil ) {@@ -192,6 +197,7 @@ struct TodayView: View { self.onSelectWork = onSelectWork self.onSetLatest = onSetLatest self.onSetReadingStatus = onSetReadingStatus+ self.onSetNoEpisode = onSetNoEpisode self.onPruneSelection = onPruneSelection self.onShowSettings = onShowSettings }@@ -261,6 +267,11 @@ struct TodayView: View { } message: { Text(catchUpActionError ?? "") }+ .alert("Couldn’t update release", isPresented: $showingNoEpisodeActionError) {+ Button("OK", role: .cancel) { noEpisodeActionError = nil }+ } message: {+ Text(noEpisodeActionError ?? "")+ } // 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@@ -476,11 +487,16 @@ struct TodayView: View { } else if dynamicTypeSize.isAccessibilitySize { // Today v2 §4: a 98 pt cover cannot hold an accessibility-size // title, so the shelf falls back to the vertical rows.- releaseRows(plan.day.releases, selectedDay: plan.day.day)+ releaseRows(ReleaseShelfText.ordered(plan.day.releases), selectedDay: plan.day.day) } else { ReleaseShelf( rows: ReleaseShelfText.ordered(plan.day.releases),- onSelect: onSelectWork)+ selectedDay: plan.day.day, currentDay: currentDay, calendar: calendar,+ onSelect: onSelectWork,+ onSetNoEpisode: { id, marked in+ handleNoEpisode(id, day: plan.day.day, marked: marked)+ },+ isActionInFlight: { noEpisodeActionsInFlight.contains($0) }) .constellationListRow(insets: Self.zeroRowInsets) } } header: {@@ -571,6 +587,23 @@ struct TodayView: View { } } + private func handleNoEpisode(_ id: UUID, day: CivilDay, marked: Bool) {+ guard noEpisodeActionsInFlight.insert(id).inserted else { return }+ Task {+ defer { noEpisodeActionsInFlight.remove(id) }+ do {+ let outcome = try await onSetNoEpisode(id, day, marked)+ if case .conflict(let conflict) = outcome {+ noEpisodeActionError = EntryDetailModel.conflictMessage(conflict)+ showingNoEpisodeActionError = true+ }+ } catch {+ noEpisodeActionError = error.localizedDescription+ showingNoEpisodeActionError = 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@@ -581,7 +614,11 @@ struct TodayView: View { selectedDay: selectedDay, currentDay: currentDay, calendar: calendar,- onSelect: onSelectWork)+ onSelect: onSelectWork,+ onSetNoEpisode: { id, marked in+ handleNoEpisode(id, day: selectedDay, marked: marked)+ },+ isActionInFlight: noEpisodeActionsInFlight.contains(row.id)) .constellationListRow() } }@@ -1632,6 +1669,7 @@ struct ReleaseRowView: View { /// `site-display-names` Q16: VoiceOver hears the site the way a sighted /// reader reads it. The row draws no site text of its own. @Environment(\.siteNames) private var siteNames+ @Environment(\.openURL) private var openURL /// What the releases section's rows are addressed by. Drawn at the /// accessibility sizes only since Today v2 §4, where the shelf falls back@@ -1644,6 +1682,8 @@ struct ReleaseRowView: View { let currentDay: CivilDay let calendar: Calendar let onSelect: (UUID) -> Void+ let onSetNoEpisode: (UUID, Bool) -> Void+ let isActionInFlight: Bool private var line: String { ReleaseLineText.line(@@ -1653,7 +1693,7 @@ struct ReleaseRowView: View { var body: some View { // Once per draw: the row shows this sentence and VoiceOver hears it, and // building it walks the relative-day table either way.- let line = line+ let line = ReleaseShelfText.verticalDetail(row, line: line) return Button { onSelect(row.id) } label: {@@ -1664,9 +1704,21 @@ struct ReleaseRowView: View { titleLabel: row.title, primaryHostname: row.primaryHostname, typeDisplay: row.typeDisplay,- isKnockedDown: false,+ isKnockedDown: row.isCompleted, meta: { EmptyView() },- trailing: { Spacer() },+ trailing: {+ Spacer(minLength: 0)+ if let symbol = ReleaseShelfText.completedSymbol(row) {+ Image(systemName: symbol)+ .foregroundStyle(AsterismColors.cyan)+ .accessibilityHidden(true)+ } else if let badge = ReleaseShelfText.badge(row) {+ Text(badge)+ .font(.caption2.weight(.semibold))+ .foregroundStyle(AsterismColors.cyan)+ .accessibilityHidden(true)+ }+ }, detail: { Text(line) .font(.caption)@@ -1681,6 +1733,25 @@ struct ReleaseRowView: View { .contentShape(Rectangle()) } .buttonStyle(.plain)+ .contextMenu {+ if row.releaseState == .pending {+ Button(ReleaseShelfText.markActionTitle(+ selectedDay: selectedDay, currentDay: currentDay, calendar: calendar),+ systemImage: "minus") {+ onSetNoEpisode(row.id, true)+ }+ .disabled(isActionInFlight)+ } else if row.releaseState == .noEpisode {+ Button("Undo no episode", systemImage: "arrow.uturn.backward") {+ onSetNoEpisode(row.id, false)+ }+ .disabled(isActionInFlight)+ }+ if let url = row.primaryURL {+ Button("Open Work Page", systemImage: "safari") { openURL(url) }+ }+ Button("Go to Work", systemImage: "book") { onSelect(row.id) }+ } .padding(.vertical, 10) .padding(.horizontal, 12) .constellationCard()
diff --git a/Asterism/AsterismShareExtension/ShareCaptureSession.swift b/Asterism/AsterismShareExtension/ShareCaptureSession.swiftindex 954624f1..742b5507 100644--- a/Asterism/AsterismShareExtension/ShareCaptureSession.swift+++ b/Asterism/AsterismShareExtension/ShareCaptureSession.swift@@ -162,7 +162,8 @@ final class ShareCaptureSession { throw ShareCaptureStop.message("Library unavailable. Please try again later.") } return try await LibraryRepository.openForExtension(- configuration, capabilities: .current+ configuration, capabilities: .current,+ noteCalendar: { Calendar.current } ).repository })
diff --git a/Asterism/AsterismTests/AppLibraryModelTests.swift b/Asterism/AsterismTests/AppLibraryModelTests.swiftindex 6492fd21..7813c407 100644--- a/Asterism/AsterismTests/AppLibraryModelTests.swift+++ b/Asterism/AsterismTests/AppLibraryModelTests.swift@@ -315,7 +315,7 @@ struct AppLibraryModelDiagnosisRefreshTests { /// The expected call sequence of one `refreshDiagnosesAndSnapshots`. private static let refreshSequence =- ["refreshDiagnostics", "todayPresentation", "works", "siteNames"]+ ["refreshDiagnostics", "prepareNoEpisodeNotes", "todayPresentation", "works", "siteNames"] @Test("Activation re-derives the diagnoses before it rebuilds the snapshots (Req 1.5)") func activationRefreshesDiagnosesFirst() async {@@ -408,7 +408,7 @@ struct AppLibraryModelSyncArrivalTests { /// The call sequence one arrival must produce: reconcile first, then the /// existing diagnosis-before-snapshots refresh. private static let arrivalSequence =- ["reconcileAfterSync", "refreshDiagnostics", "todayPresentation", "works", "siteNames"]+ ["reconcileAfterSync", "refreshDiagnostics", "prepareNoEpisodeNotes", "todayPresentation", "works", "siteNames"] private static func mirroringConfiguration() -> LibraryConfiguration { LibraryConfiguration(@@ -845,6 +845,101 @@ private final class CalendarInForce: @unchecked Sendable { @MainActor struct AppLibraryModelSnapshotPublicationTests { + @Test("No-episode command keeps the selected day and refreshes only after a save")+ func noEpisodeCommandRefreshesAfterSave() async throws {+ let mock = MockLibraryProvider()+ let model = AppLibraryModel(readyRepository: mock)+ let id = UUID()+ let selectedDay = CivilDay(Date(timeIntervalSince1970: 1_700_000_000), calendar: .current)++ let result = try await model.setNoEpisode(workID: id, day: selectedDay, marked: true)++ #expect(result == .committed)+ #expect(mock.noEpisodeCommands.count == 1)+ #expect(mock.noEpisodeCommands.first?.workID == id)+ #expect(mock.noEpisodeCommands.first?.day == selectedDay)+ #expect(mock.noEpisodeCommands.first?.isMark == true)+ #expect(mock.callLog.first == "markNoEpisode")+ #expect(model.snapshotGeneration == 1)+ }++ @Test("A failed no-episode save leaves the last publication in place")+ func noEpisodeSaveFailureDoesNotRefresh() async {+ let mock = MockLibraryProvider()+ let model = AppLibraryModel(readyRepository: mock)+ mock.markNoEpisodeResult = .failure(MockLibraryProvider.MockError.simulatedFailure("save failed"))+ let selectedDay = CivilDay(Date(), calendar: .current)++ do {+ _ = try await model.setNoEpisode(workID: UUID(), day: selectedDay, marked: true)+ Issue.record("Expected the save failure")+ } catch {}++ #expect(mock.todayPresentationCallCount == 0)+ #expect(model.snapshotGeneration == 0)+ }++ @Test("A saved no-episode action reports a failed refresh as stale presentation")+ func noEpisodeRefreshFailureFollowsSuccessfulSave() async {+ let mock = MockLibraryProvider()+ let model = AppLibraryModel(readyRepository: mock)+ mock.todayPresentationResult = .failure(MockLibraryProvider.MockError.simulatedFailure("read failed"))++ do {+ _ = try await model.setNoEpisode(+ workID: UUID(), day: CivilDay(Date(), calendar: .current), marked: true)+ Issue.record("Expected a refresh failure")+ } catch {+ #expect(error.localizedDescription.contains("was saved"))+ }++ #expect(mock.noEpisodeCommands.count == 1)+ #expect(mock.todayPresentationCallCount == 1)+ #expect(model.snapshotGeneration == 0)+ }++ @Test("Undo uses the captured day and publishes the refreshed estimate")+ func noEpisodeUndoRefreshes() async throws {+ let mock = MockLibraryProvider()+ let model = AppLibraryModel(readyRepository: mock)+ let day = CivilDay(Date(timeIntervalSince1970: 1_700_000_000), calendar: .current)++ _ = try await model.setNoEpisode(workID: UUID(), day: day, marked: false)++ #expect(mock.noEpisodeCommands.first?.day == day)+ #expect(mock.noEpisodeCommands.first?.isMark == false)+ #expect(model.snapshotGeneration == 1)+ }++ @Test("A refresh prepares note clears before reading Today with its captured calendar")+ func refreshPreparesBeforeRead() async {+ let mock = MockLibraryProvider()+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(identifier: "Pacific/Auckland")!+ let model = AppLibraryModel(readyRepository: mock, calendarSource: { calendar })++ await model.refreshAll()++ #expect(mock.callLog.prefix(2) == ["prepareNoEpisodeNotes", "todayPresentation"])+ #expect(mock.preparedCalendars.map(\.timeZone.identifier) == ["Pacific/Auckland"])+ #expect(model.snapshotGeneration == 1)+ }++ @Test("Failed note preparation preserves the last published snapshots")+ func failedPreparationPreservesPublication() async {+ let mock = MockLibraryProvider()+ let model = AppLibraryModel(readyRepository: mock)+ await model.refreshAll()+ let published = model.todayPresentation+ mock.prepareNoEpisodeNotesResult = .failure(MockLibraryProvider.MockError.simulatedFailure("save failed"))++ await model.refreshAll()++ #expect(mock.todayPresentationCallCount == 1)+ #expect(model.snapshotGeneration == 1)+ #expect(model.todayPresentation == published)+ }+ /// A works snapshot distinguishable from the empty default. private static func seededWorks(title: String) -> WorksSnapshot { WorksSnapshot(@@ -1470,7 +1565,9 @@ struct AppLibraryModelLaunchTests { // Order, not merely occurrence: the reader can be waiting on Works and // the reconcile's worst case is a 5,000-record re-pin under the // exclusive lock.- #expect(mock.callLog == ["todayPresentation", "works", "siteNames", "reconcileAfterSync"])+ #expect(mock.callLog == [+ "prepareNoEpisodeNotes", "todayPresentation", "works", "siteNames", "reconcileAfterSync",+ ]) #expect(model.worksLoad == .loaded) #expect(model.launchReconcileCompleted) }@@ -1496,8 +1593,8 @@ struct AppLibraryModelLaunchTests { #expect( mock.callLog == [- "todayPresentation", "works", "siteNames",- "todayPresentation", "works", "siteNames",+ "prepareNoEpisodeNotes", "todayPresentation", "works", "siteNames",+ "prepareNoEpisodeNotes", "todayPresentation", "works", "siteNames", "reconcileAfterSync", ]) #expect(model.worksLoad == .loaded)
diff --git a/Asterism/AsterismTests/BackupExportStageTests.swift b/Asterism/AsterismTests/BackupExportStageTests.swiftindex 140e718a..c8ddcb09 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(- BackupV16ExportError.tornGroups(+ BackupV17ExportError.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: [- BackupV16ExportError.referencesStillArriving(detail: "rule 1"),- BackupV16ExportError.unrepresentableValue(+ BackupV17ExportError.referencesStillArriving(detail: "rule 1"),+ BackupV17ExportError.unrepresentableValue( record: "Character", field: "factsData", value: "…"),- BackupV16ExportError.snapshotFailed(reason: "read"),- BackupV16ExportError.encodingFailed(reason: "encode"),- BackupV16ExportError.stagingFailed(reason: "stage"),+ BackupV17ExportError.snapshotFailed(reason: "read"),+ BackupV17ExportError.encodingFailed(reason: "encode"),+ BackupV17ExportError.stagingFailed(reason: "stage"), ])- @MainActor func otherRefusalsOfferNoRoute(error: BackupV16ExportError) async {+ @MainActor func otherRefusalsOfferNoRoute(error: BackupV17ExportError) 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(- BackupV16ExportError.unrepresentableValue(+ BackupV17ExportError.unrepresentableValue( record: "Work “Actual Title”",- field: BackupV16ExportError.thumbnailField,+ field: BackupV17ExportError.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: BackupV16ExportError.unrepresentableValue(+ for: BackupV17ExportError.unrepresentableValue( record: "Work “Actual Title”",- field: BackupV16ExportError.thumbnailField,+ field: BackupV17ExportError.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: BackupV16ExportError.unrepresentableValue(+ for: BackupV17ExportError.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: BackupV16ExportError.tornGroups(+ for: BackupV17ExportError.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 `BackupV16Exporter` does.+/// mock — removes the staged file on cleanup, as `BackupV17Exporter` 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(- BackupV16ExportError.snapshotFailed(reason: "not configured"))+ BackupV17ExportError.snapshotFailed(reason: "not configured")) - func export(metadata: BackupV16Metadata) async throws -> BackupExportResult {+ func export(metadata: BackupV17Metadata) async throws -> BackupExportResult { exportCallCount += 1 return try exportResult.get() }
diff --git a/Asterism/AsterismTests/EmptyLibraryModelTests.swift b/Asterism/AsterismTests/EmptyLibraryModelTests.swiftindex 089d48be..6b54ff4e 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(- BackupV16ExportError.tornGroups(TornGroupsPayload(count: 3, blockingWorkSet: nil)))+ BackupV17ExportError.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(- BackupV16ExportError.referencesStillArriving(detail: "rule 1"))+ BackupV17ExportError.referencesStillArriving(detail: "rule 1")) await harness.confirm() @@ -397,7 +397,7 @@ struct EmptyLibraryModelTests { harness.model.cancelConfirmation() harness.exporter.exportResult = .failure(- BackupV16ExportError.encodingFailed(reason: "encode"))+ BackupV17ExportError.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 `BackupV16Exporter` does.+/// cleanup as `BackupV17Exporter` does. private final class RecordingBackupExporter: BackupExporting, @unchecked Sendable { var exportCallCount = 0 var cleanupCallCount = 0 var exportResult: Result<BackupExportResult, Error> = .failure(- BackupV16ExportError.snapshotFailed(reason: "not configured"))+ BackupV17ExportError.snapshotFailed(reason: "not configured")) - func export(metadata: BackupV16Metadata) async throws -> BackupExportResult {+ func export(metadata: BackupV17Metadata) async throws -> BackupExportResult { exportCallCount += 1 return try exportResult.get() }
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex f1c08bb9..4a749d95 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -11,6 +11,12 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { var callLog: [String] = [] var todayPresentationCallCount = 0+ var prepareNoEpisodeNotesCallCount = 0+ var preparedCalendars: [Calendar] = []+ var prepareNoEpisodeNotesResult: Result<Void, Error> = .success(())+ var markNoEpisodeResult: Result<LibraryWriteOutcome, Error> = .success(.committed)+ var undoNoEpisodeResult: Result<LibraryWriteOutcome, Error> = .success(.committed)+ var noEpisodeCommands: [(workID: UUID, day: CivilDay, isMark: Bool)] = [] var worksCallCount = 0 var entryCallCount = 0 var workCallCount = 0@@ -100,6 +106,27 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { return presentation } + func prepareNoEpisodeNotes(calendar: Calendar) async throws {+ prepareNoEpisodeNotesCallCount += 1+ preparedCalendars.append(calendar)+ callLog.append("prepareNoEpisodeNotes")+ try prepareNoEpisodeNotesResult.get()+ }++ func markNoEpisode(+ workID: UUID, day: CivilDay, calendar: Calendar+ ) async throws -> LibraryWriteOutcome {+ noEpisodeCommands.append((workID, day, true))+ callLog.append("markNoEpisode")+ return try markNoEpisodeResult.get()+ }++ func undoNoEpisode(workID: UUID, day: CivilDay) async throws -> LibraryWriteOutcome {+ noEpisodeCommands.append((workID, day, false))+ callLog.append("undoNoEpisode")+ return try undoNoEpisodeResult.get()+ }+ func works() async throws -> WorksSnapshot { worksCallCount += 1 callLog.append("works")
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex aecfacfb..1851ed20 100644--- a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift+++ b/Asterism/AsterismTests/IntegrationSafetyNetTests.swift@@ -155,10 +155,10 @@ struct IntegrationSafetyNetTests { , calendar: .current) let stagingDirectory = fixture.baseDirectory.appending(path: "validated-backups")- let exporter = BackupV16Exporter(repository: repository, stagingDirectory: stagingDirectory)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: stagingDirectory) let exportedAt = Date(timeIntervalSince1970: 1_784_246_400) let result = try await exporter.export(- metadata: BackupV16Metadata(+ metadata: BackupV17Metadata( 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 BackupV16Codec.decode(encoded)- let source = try await repository.backupV16Snapshot()+ let decoded = try BackupV17Codec.decode(encoded)+ let source = try await repository.backupV17Snapshot() #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 BackupV16Codec.decode(Data(contentsOf: backupURL))+ let document = try BackupV17Codec.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 = BackupV16Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+ let exporter = BackupV17Exporter(repository: sourceRepo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "fill-test", exportedAt: Date())+ metadata: BackupV17Metadata(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 = BackupV16Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+ let exporter = BackupV17Exporter(repository: sourceRepo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "restore-test", exportedAt: Date())+ metadata: BackupV17Metadata(appBuild: "restore-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } let plan = try BackupImporter.plan(from: try Data(contentsOf: exportResult.fileURL))@@ -842,15 +842,15 @@ struct IntegrationSafetyNetTests { ) let stagingDir = fixture.baseDirectory.appending(path: "corrupt-stage")- let exporter = BackupV16Exporter(repository: repo, stagingDirectory: stagingDir)+ let exporter = BackupV17Exporter(repository: repo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "corrupt-test", exportedAt: Date())+ metadata: BackupV17Metadata(appBuild: "corrupt-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } // Verify good backup decodes let goodData = try Data(contentsOf: exportResult.fileURL)- let decoded = try BackupV16Codec.decode(goodData)+ let decoded = try BackupV17Codec.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 BackupV16Codec.decode(corruptData)+ _ = try BackupV17Codec.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 = BackupV16Exporter(repository: repo, stagingDirectory: stagingDir)+ let exporter = BackupV17Exporter(repository: repo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "url-backup-test", exportedAt: Date())+ metadata: BackupV17Metadata(appBuild: "url-backup-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } let backupData = try Data(contentsOf: exportResult.fileURL)- let decoded = try BackupV16Codec.decode(backupData)+ let decoded = try BackupV17Codec.decode(backupData) // Site should be present in the payload. let site = decoded.payload.sites.first { $0.hostname == "backupurl.test" }
diff --git a/Asterism/AsterismTests/IntentLibraryBrokerTests.swift b/Asterism/AsterismTests/IntentLibraryBrokerTests.swiftindex 27e5b3a8..d42ddce7 100644--- a/Asterism/AsterismTests/IntentLibraryBrokerTests.swift+++ b/Asterism/AsterismTests/IntentLibraryBrokerTests.swift@@ -98,6 +98,21 @@ struct IntentLibraryBrokerTests { // MARK: - The resident library + @Test("A prepared Today read reconciles before its first presentation")+ func preparedTodayReadOrdersPreparationBeforePresentation() async throws {+ let mock = MockLibraryProvider()+ let model = AppLibraryModel(readyRepository: mock)+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(identifier: "Pacific/Auckland")!++ _ = try await model.intentBroker.withPreparedToday(calendar: calendar) { library in+ try await library.todayPresentation(calendar: calendar)+ }++ #expect(mock.callLog.prefix(2) == ["prepareNoEpisodeNotes", "todayPresentation"])+ #expect(mock.preparedCalendars.map(\.timeZone.identifier) == ["Pacific/Auckland"])+ }+ @Test("A step on a ready model runs on the resident repository and refreshes nothing") func residentReadRunsOnTheResidentRepository() async throws { let mock = MockLibraryProvider()@@ -210,6 +225,61 @@ struct IntentLibraryBrokerTests { #expect(try pendingMarkers(configuration).count == 1, "the read after it owes nothing more") } + @Test("A prepared cold read that fails still owes export after preparation")+ func preparedColdReadFailureKeepsExportOwed() async throws {+ let root = tempRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ try await createLibrary(at: root)+ let configuration = configuration(mirroring: false, at: root)+ let model = AppLibraryModel(configuration: configuration)++ do {+ _ = try await model.intentBroker.withPreparedToday(calendar: .current) {+ _ -> Int in+ throw LibraryRepositoryError.invalidInput(operation: "read", reason: "failed")+ }+ Issue.record("Expected the read failure")+ } catch {+ guard case .failed = error else {+ Issue.record("Expected a read failure, got \(error)")+ return+ }+ }++ #expect(try pendingMarkers(configuration).count == 1)+ #expect(!model.intentBroker.isBusy)+ }++ @Test("A cold preparation failure leaves no export marker or presentation read")+ func coldPreparationFailureOwesNoExport() async throws {+ let root = tempRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ try await createLibrary(at: root)+ let configuration = configuration(mirroring: false, at: root)+ let model = AppLibraryModel(configuration: configuration)+ let entered = Recorder()+ model.intentBroker.prepareToday = { _, _ in+ throw LibraryRepositoryError.invalidInput(operation: "prepare", reason: "failed")+ }++ do {+ _ = try await model.intentBroker.withPreparedToday(calendar: .current) {+ _ -> Int in+ entered.append("read")+ return 1+ }+ Issue.record("Expected the preparation failure")+ } catch {+ guard case .failed = error else {+ Issue.record("Expected a preparation failure, got \(error)")+ return+ }+ }++ #expect(entered.events.isEmpty)+ #expect(try pendingMarkers(configuration).isEmpty)+ }+ @Test("A cold step on an empty root is unavailable, and creates no store") func coldStepNeverCreatesAStore() async throws { let root = tempRoot()
diff --git a/Asterism/AsterismTests/PendingCaptureWatcherTests.swift b/Asterism/AsterismTests/PendingCaptureWatcherTests.swiftindex d51d4176..8b40cb96 100644--- a/Asterism/AsterismTests/PendingCaptureWatcherTests.swift+++ b/Asterism/AsterismTests/PendingCaptureWatcherTests.swift@@ -225,7 +225,7 @@ struct AppLibraryModelQueueArrivalTests { /// activation: the diagnoses are re-derived before the snapshots are /// rebuilt, because Recent is built from them. private static let refreshSequence =- ["refreshDiagnostics", "todayPresentation", "works", "siteNames"]+ ["refreshDiagnostics", "prepareNoEpisodeNotes", "todayPresentation", "works", "siteNames"] @Test("An arrival drains and then republishes, so the row reaches Recent (Req 4.6)") func arrivalRefreshesAfterTheDrain() async {
diff --git a/Asterism/AsterismTests/SettingsBackupModelTests.swift b/Asterism/AsterismTests/SettingsBackupModelTests.swiftindex 09f62724..0cec680a 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(- BackupV16ExportError.tornGroups(+ BackupV17ExportError.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(- BackupV16ExportError.tornGroups(+ BackupV17ExportError.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(- BackupV16ExportError.tornGroups(+ BackupV17ExportError.tornGroups( TornGroupsPayload( count: 1, blockingWorkSet: DuplicateSetKey(@@ -394,7 +394,7 @@ struct SettingsBackupModelTests { let mock = MockBackupExporting() mock.exportResult = .failure(- BackupV16ExportError.tornGroups(+ BackupV17ExportError.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: BackupV16Metadata? = mock.lastMetadata+ let metadata: BackupV17Metadata? = 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(- BackupV16ExportError.tornGroups(+ BackupV17ExportError.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: [- BackupV16ExportError.referencesStillArriving(detail: "rule 1"),- BackupV16ExportError.unrepresentableValue(+ BackupV17ExportError.referencesStillArriving(detail: "rule 1"),+ BackupV17ExportError.unrepresentableValue( record: "Character", field: "factsData", value: "…"),- BackupV16ExportError.snapshotFailed(reason: "read"),- BackupV16ExportError.encodingFailed(reason: "encode"),- BackupV16ExportError.stagingFailed(reason: "stage"),+ BackupV17ExportError.snapshotFailed(reason: "read"),+ BackupV17ExportError.encodingFailed(reason: "encode"),+ BackupV17ExportError.stagingFailed(reason: "stage"), ])- @MainActor func everyNineTenRefusalHasAMessage(error: BackupV16ExportError) async {+ @MainActor func everyNineTenRefusalHasAMessage(error: BackupV17ExportError) async { let mock = MockBackupExporting() mock.exportResult = .failure(error) @@ -495,9 +495,9 @@ struct SettingsBackupModelTests { @MainActor func coverRefusalNamesTheWork() async { let mock = MockBackupExporting() mock.exportResult = .failure(- BackupV16ExportError.unrepresentableValue(+ BackupV17ExportError.unrepresentableValue( record: "Work “Actual Title”",- field: BackupV16ExportError.thumbnailField,+ field: BackupV17ExportError.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: BackupV16Metadata?+ var lastMetadata: BackupV17Metadata? var exportResult: Result<BackupExportResult, Error> = .failure(MockBackupError.notConfigured) var exportDelay: Duration? - func export(metadata: BackupV16Metadata) async throws -> BackupExportResult {+ func export(metadata: BackupV17Metadata) async throws -> BackupExportResult { exportCallCount += 1 lastMetadata = metadata if let delay = exportDelay {
diff --git a/Asterism/AsterismTests/SettingsImportTests.swift b/Asterism/AsterismTests/SettingsImportTests.swiftindex 35135b60..28f5cb05 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 = BackupV16Payload(+ let payload = BackupV17Payload( entries: [- BackupV16Entry(+ BackupV17Entry( id: UUID(), captureTitle: "Chapter 1", captureTitleSource: .host, rawURL: rawURL, canonicalURL: nil, hostname: hostname, entryIdentityKey: rawURL,@@ -84,13 +84,13 @@ struct SettingsBackupImportModelTests { ], works: [], sites: [- BackupV16Site(+ BackupV17Site( hostname: hostname, displayName: hostname, mode: .untaught) ], titlePatterns: [], urlRules: [], workTypes: [])- return try! BackupV16Codec.encode(+ return try! BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(+ metadata: BackupV17Metadata( appBuild: "test", exportedAt: Date(timeIntervalSince1970: 1_800_000_000))) }()
diff --git a/Asterism/AsterismTests/TodayShelfTextTests.swift b/Asterism/AsterismTests/TodayShelfTextTests.swiftindex d6fb0e5c..1e951cfa 100644--- a/Asterism/AsterismTests/TodayShelfTextTests.swift+++ b/Asterism/AsterismTests/TodayShelfTextTests.swift@@ -31,11 +31,20 @@ struct TodayShelfTextTests { _ title: String, line: ReleaseRow.Line = .notNotedYet, type: WorkTypeDisplay = .untyped, lastChapter: Int? = nil, lastNotedDay: CivilDay? = nil, releasesSince: Int? = nil, primaryURL: URL? = nil,- progress: CatchUpProgress? = nil, workStatus: WorkStatus = .ongoing+ progress: CatchUpProgress? = nil, workStatus: WorkStatus = .ongoing,+ releaseState: ReleaseRow.ReleaseState? = nil ) -> ReleaseRow {- ReleaseRow(+ let state: ReleaseRow.ReleaseState+ if let releaseState {+ state = releaseState+ } else if case .notedOnDay = line {+ state = .noted+ } else {+ state = .pending+ }+ return ReleaseRow( id: UUID(), title: title, primaryHostname: "example.com", typeDisplay: type,- thumbnail: nil, line: line,+ thumbnail: nil, line: line, releaseState: state, progress: progress ?? CatchUpProgress.build( record: .pristine, notes: [], releaseDays: [], workStatus: .ongoing, day: today, calendar: Self.calendar()), workStatus: workStatus,@@ -45,6 +54,22 @@ struct TodayShelfTextTests { private var today: CivilDay { Self.civilDay(2026, 9, 23) } + @Test("The mark menu names the selected past, current, or future date")+ func markActionNamesSelectedDate() {+ let calendar = Self.calendar()+ let past = Self.civilDay(2026, 9, 22)+ let future = Self.civilDay(2026, 9, 24)++ #expect(ReleaseShelfText.markActionTitle(+ selectedDay: today, currentDay: today, calendar: calendar) == "No episode today")+ #expect(ReleaseShelfText.markActionTitle(+ selectedDay: past, currentDay: today, calendar: calendar)+ == "No episode on \(TodayDateText.abbreviated(past, calendar: calendar))")+ #expect(ReleaseShelfText.markActionTitle(+ selectedDay: future, currentDay: today, calendar: calendar)+ == "No episode on \(TodayDateText.abbreviated(future, calendar: calendar))")+ }+ private func progress( latest: Int?, read: Int?, confirmedDay: CivilDay? = nil, readDay: CivilDay? = nil, estimated: Bool = false,@@ -83,6 +108,25 @@ struct TodayShelfTextTests { #expect(ReleaseShelfText.summary([readA, unreadB, readC, unreadD]) == "2 of 4 read") } + @Test("No-episode works join the completed partition without increasing read count")+ func noEpisodeShelfState() {+ let pendingA = row("A")+ let skippedB = row("B", lastChapter: 20, releaseState: .noEpisode)+ let notedC = row("C", line: .notedOnDay(chapterLine: nil), releaseState: .noted)+ let pendingD = row("D")+ let skippedE = row("E", releaseState: .noEpisode)+ let rows = [pendingA, skippedB, notedC, pendingD, skippedE]++ #expect(ReleaseShelfText.ordered(rows).map(\.title) == ["A", "D", "B", "C", "E"])+ #expect(ReleaseShelfText.summary(rows) == "1 of 5 read · 2 no episode")+ #expect(ReleaseShelfText.badge(skippedB) == nil)+ #expect(ReleaseShelfText.label(skippedB) == "B, No episode")+ #expect(ReleaseShelfText.completedSymbol(skippedB) == "minus")+ #expect(ReleaseShelfText.completedSymbol(notedC) == "checkmark")+ #expect(ReleaseShelfText.verticalDetail(skippedB, line: "Not noted yet") == "No episode")+ #expect(ReleaseShelfText.verticalDetail(notedC, line: "Noted today") == "Noted today")+ }+ @Test("An unread cover's badge is the next whole chapter, spelled for the work's type") func shelfBadgeIsTheNextChapter() { #expect(ReleaseShelfText.badge(row("Novel", lastChapter: 686)) == "Ch 687")
diff --git a/Asterism/AsterismUITests/TodayUITests.swift b/Asterism/AsterismUITests/TodayUITests.swiftindex b2954ffb..7a4824b6 100644--- a/Asterism/AsterismUITests/TodayUITests.swift+++ b/Asterism/AsterismUITests/TodayUITests.swift@@ -79,6 +79,17 @@ final class TodayUITests: XCTestCase { waitFor(app.anyElement("today-header-date"), "…on a day rather than on every day") } + private func launchNoEpisode(accessibilitySize: Bool = false) {+ if accessibilitySize {+ app.launchArguments += [+ "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"+ ]+ }+ launch("seeded-no-episode")+ waitFor(app.collectionViews["recent-list"], "The release fixture opens", timeout: 60)+ waitFor(app.anyElement("today-header-date"), "Today is selected")+ }+ private var recentRows: XCUIElementQuery { app.elements(withIdentifierPrefix: "recent-entry-") }@@ -89,6 +100,113 @@ final class TodayUITests: XCTestCase { app.elements(withIdentifierPrefix: "today-release-shelf-item-") } + func testNoEpisodeShelfMenusMarkUndoAndKeepWorkNavigation() {+ launchNoEpisode()+ let amber = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-release-shelf-item-", "Amber Signal,")).firstMatch,+ "The pending release appears")+ XCTAssertTrue(amber.label.contains("not read yet"))+ amber.press(forDuration: 1)+ waitFor(app.buttons["No episode today"], "The mark action appears").tap()++ let marked = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label == %@",+ "today-release-shelf-item-", "Amber Signal, No episode")).firstMatch,+ "The saved mark appears")+ XCTAssertEqual(app.anyElement("today-releases-summary").label, "0 of 2 read · 2 no episode")+ marked.press(forDuration: 1)+ waitFor(app.buttons["Undo no episode"], "The undo action appears").tap()+ waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-release-shelf-item-", "Amber Signal, not read yet")).firstMatch,+ "The pending release returns")++ let blue = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label == %@",+ "today-release-shelf-item-", "Blue Signal, No episode")).firstMatch,+ "The other marked release remains")+ blue.press(forDuration: 1)+ XCTAssertTrue(app.buttons["Open Work Page"].exists)+ waitFor(app.buttons["Go to Work"], "The work navigation remains").tap()+ waitFor(app.anyElement("work-detail-pulse"), "The work opens", timeout: 20)+ }++ /// A long press on the second cover must use that work's menu. The older+ /// journey only mutated the first cover, so a shelf-wide hit target passed.+ func testNoEpisodeShelfSecondCoverMenuTargetsSecondWork() {+ launchNoEpisode()+ let amber = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-release-shelf-item-", "Amber Signal,")).firstMatch,+ "The first release appears")+ let blue = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-release-shelf-item-", "Blue Signal,")).firstMatch,+ "The second release appears")+ XCTAssertEqual(releaseRows.count, 2)+ XCTAssertGreaterThan(blue.frame.midX, amber.frame.maxX)+ XCTAssertTrue(amber.label.contains("not read yet"))+ XCTAssertTrue(blue.label.contains("No episode"))++ // The second item starts marked. Undo it, then mark it again from its+ // own visible cover; Amber must stay pending through both operations.+ blue.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.35))+ .press(forDuration: 1)+ waitFor(app.buttons["Undo no episode"], "Blue's undo action appears").tap()+ waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label == %@",+ "today-release-shelf-item-", "Blue Signal, not read yet")).firstMatch,+ "Blue becomes pending")+ XCTAssertTrue(amber.label.contains("not read yet"))++ blue.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.35))+ .press(forDuration: 1)+ waitFor(app.buttons["No episode today"], "Blue's mark action appears").tap()+ waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label == %@",+ "today-release-shelf-item-", "Blue Signal, No episode")).firstMatch,+ "Blue becomes marked again")+ XCTAssertTrue(amber.label.contains("not read yet"))++ blue.tap()+ XCTAssertEqual(+ waitFor(app.anyElement("work-detail-title"), "The second cover opens its work").label,+ "Blue Signal")+ }++ func testNoEpisodeActionAndLabelAtAccessibilitySize() {+ launchNoEpisode(accessibilitySize: true)+ XCTAssertFalse(app.anyElement("today-releases-shelf").exists)+ let amber = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-release-", "Amber Signal,")).firstMatch,+ "The pending vertical release appears")+ amber.press(forDuration: 1)+ waitFor(app.buttons["No episode today"], "The vertical menu offers marking").tap()+ let markedAmber = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-release-", "Amber Signal, No episode")).firstMatch,+ "The vertical row updates its spoken state")+ XCTAssertTrue(markedAmber.label.contains("from release.test"))++ let blue = app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-release-", "Blue Signal, No episode")).firstMatch+ scrollUntilPresent(blue, in: app, "The second completed vertical release is below the fold")+ XCTAssertTrue(blue.label.contains("from release.test"))+ }+ /// The catching-up card's rows (`catch-up-mode` Q4, Today v2 §5). The two /// prefixes are disjoint, which is why the counts above are unmoved by a /// catch-up work.
diff --git a/Asterism/AsterismUITests/WideLayoutUITests.swift b/Asterism/AsterismUITests/WideLayoutUITests.swiftindex bee56a0b..1a04bef6 100644--- a/Asterism/AsterismUITests/WideLayoutUITests.swift+++ b/Asterism/AsterismUITests/WideLayoutUITests.swift@@ -1025,6 +1025,27 @@ final class WideLayoutUITests: XCTestCase { app.elements(withIdentifierPrefix: "today-release-shelf-item-") } + func testNoEpisodeMenuWorksBesideWideDetailColumn() {+ launch("seeded-no-episode", orientation: .landscapeLeft)+ waitForLibrary()+ let amber = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+ "today-release-shelf-item-", "Amber Signal,")).firstMatch,+ "The pending release is in the wide list")+ amber.press(forDuration: 1)+ waitFor(app.buttons["No episode today"], "The mark action is available").tap()+ let marked = waitFor(+ app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH %@ AND label == %@",+ "today-release-shelf-item-", "Amber Signal, No episode")).firstMatch,+ "The marked release remains in the wide list")+ marked.press(forDuration: 1)+ waitFor(app.buttons["Go to Work"], "The work route remains").tap()+ waitFor(app.anyElement("wide-detail-column"), "The detail column remains beside Today")+ waitFor(app.anyElement("work-detail-pulse"), "The work opens in the detail column")+ }+ /// The catch-up section's rows (`catch-up-mode` Q4), whose prefix is /// deliberately not the releases one. private var catchUpRows: XCUIElementQuery {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift b/Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swiftindex e5b932ea..2283b9d4 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: BackupV16Work) -> ArchiveThumbnail {+ static func of(_ record: BackupV17Work) -> 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: BackupV16Site) -> Site {+ static func makeSite(_ record: BackupV17Site) -> Site { let site = Site(hostname: record.hostname, displayName: record.displayName) site.modeRaw = record.mode.rawValue return site } static func makeTitlePattern(- _ record: BackupV16TitlePattern, site: Site?+ _ record: BackupV17TitlePattern, site: Site? ) throws -> TitlePattern { return try TitlePattern( id: record.id,@@ -87,7 +87,7 @@ internal enum ArchiveRecordBuilders { } static func makeURLRule(- _ record: BackupV16URLRule, site: Site?+ _ record: BackupV17URLRule, 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: BackupV16WorkType) -> WorkTypeEntity {+ static func makeWorkType(_ record: BackupV17WorkType) -> 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: BackupV16Work, thumbnail: ArchiveThumbnail = .none+ _ record: BackupV17Work, thumbnail: ArchiveThumbnail = .none ) -> Work { let work = Work( id: record.id,@@ -147,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: BackupV16Membership, work: Work?, site: Site?+ _ record: BackupV17Membership, work: Work?, site: Site? ) -> WorkSiteMembership { WorkSiteMembership( id: record.id,@@ -165,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: BackupV16DistinctPair) -> WorkDistinctPair {+ static func makeDistinctPair(_ record: BackupV17DistinctPair) -> WorkDistinctPair { WorkDistinctPair( id: record.id, lowerWorkID: record.lowerWorkID, higherWorkID: record.higherWorkID, recordedAt: record.recordedAt)@@ -175,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: BackupV16Series) -> Series {+ static func makeSeries(_ record: BackupV17Series) -> Series { Series( id: record.id, name: record.name, notes: record.notes, createdAt: record.createdAt, modifiedAt: record.modifiedAt)@@ -184,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: BackupV16Link) -> WorkLink {+ static func makeLink(_ record: BackupV17Link) -> WorkLink { WorkLink( id: record.id, lowerWorkID: record.lowerWorkID, higherWorkID: record.higherWorkID, linkType: record.linkType,@@ -198,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: BackupV16Creator) -> Creator {+ static func makeCreator(_ record: BackupV17Creator) -> Creator { let row = Creator( id: record.id, name: record.name, notes: record.notes, stateRaw: record.stateRaw, canonicalID: record.canonicalID)@@ -211,7 +211,7 @@ internal enum ArchiveRecordBuilders { } /// One role row, the same way, with the archive's list position.- static func makeCreatorRole(_ record: BackupV16CreatorRole) -> CreatorRole {+ static func makeCreatorRole(_ record: BackupV17CreatorRole) -> CreatorRole { makeCreatorRole(record, position: record.position, at: record.positionModifiedAt) } @@ -220,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: BackupV16CreatorRole, position: Int, at positionModifiedAt: Date+ _ record: BackupV17CreatorRole, position: Int, at positionModifiedAt: Date ) -> CreatorRole { let row = CreatorRole( id: record.id, name: record.name, position: position,@@ -240,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: BackupV16Credit) -> WorkCredit {+ static func makeCredit(_ record: BackupV17Credit) -> 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: BackupV16Entry) -> Entry {+ static func makeEntry(_ record: BackupV17Entry) -> Entry { let entry = Entry( id: record.id, captureTitle: record.captureTitle,@@ -300,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: BackupV16Character) -> CharacterRecord {+ static func makeCharacter(_ record: BackupV17Character) -> CharacterRecord { makeRecord(CharacterRecord.self, record) } - static func makeSuppression(_ record: BackupV16Suppression) -> CharacterSuppression {+ static func makeSuppression(_ record: BackupV17Suppression) -> CharacterSuppression { makeSuppressionRow(CharacterSuppression.self, record) } - static func makePlace(_ record: BackupV16Place) -> Place {+ static func makePlace(_ record: BackupV17Place) -> Place { makeRecord(Place.self, record) } - static func makePlaceSuppression(_ record: BackupV16PlaceSuppression) -> PlaceSuppression {+ static func makePlaceSuppression(_ record: BackupV17PlaceSuppression) -> PlaceSuppression { makeSuppressionRow(PlaceSuppression.self, record) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swiftindex 67698ea7..9fa0cf8d 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 `BackupV16Codec` stamps. The literal has not moved with+ /// which is what `BackupV17Codec` 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).- /// `BackupV16Codec` stamps the literal `"multi-site"` rather than reading+ /// `BackupV17Codec` 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/AsterismSchemaV17.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17.swiftindex 2a3c4ccd..42d03eb2 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17.swift@@ -1,7 +1,7 @@ import Foundation import SwiftData -/// The live V17 schema. Its stored models are in `Models.swift`.+/// Frozen V17 schema. Its stored models are in `AsterismSchemaV17Models.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 {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17Models.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17Models.swiftnew file mode 100644index 00000000..1400024c--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV17Models.swift@@ -0,0 +1,1633 @@+import Foundation+import SwiftData++// Frozen V17 model snapshot. Do not edit after the V18 migration ships.+extension AsterismSchemaV17 {++@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 = ""+ /// M4a: the Site this Entry was captured on, as a modelled reference (Req+ /// 1.1). `hostname` stays beside it as capture-time evidence (Q3). Nil while+ /// the Site has not arrived, or where no Site row matches — a tolerated+ /// state, not an error (Req 2.1). Written in the same save as `hostname`+ /// (Req 1.4).+ public var site: Site?+ public var entryIdentityKey: String = ""+ /// M4 secondary lookup index: the conservative (v1) key for this Entry's raw+ /// URL, retained even after an S-rule rewrites `entryIdentityKey` to v3 so a+ /// title-less same-URL re-share still matches (Q21). Backfilled at migration.+ public var conservativeIdentityKey: String = ""+ public var identityBasisRaw: String = EntryIdentityBasis.conservative.rawValue+ public var urlWorkIdentity: String?+ public var chapterSequence: String?+ public var chapterTitle: String?+ public var note: String = ""+ public var ratingRaw: String?+ public var firstCapturedAt: Date = Date(timeIntervalSince1970: 0)+ public var lastSharedAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var work: Work?+ public var intentionallyUnattached: Bool = false+ /// V7: the fingerprint of the note text a character-extraction pass last+ /// covered (Q59). A **derived** field, excluded from authored content the+ /// way a parsed `chapterTitle` is: editing the note is what uncovers the+ /// revision, so this column tracks the model's work, never the reader's.+ /// Nil means the note has never been covered.+ public var characterExtractionFingerprint: String?+ /// V8: the Entry's seven rule citations and its identity basis, as one+ /// `EntryCitations` blob (Q25) — the column that superseded+ /// `identityKeyVersion` and the seventeen citation/provenance columns V9+ /// dropped, and now the **only** home any of them has.+ ///+ /// Every writer writes it and `init` seeds it, so nil means one thing: a row+ /// a V8 build wrote that this build has not rewritten. It reads as the+ /// default rather than throwing (Q6) and `entriesWithoutCitationBlobCount`+ /// counts it — a **report**, not a quarantine (Q25): the validator throws on+ /// bytes that will not decode and says nothing about bytes that are absent.+ public var citationsData: Data?++ public init(+ id: UUID = UUID(),+ captureTitle: String,+ captureTitleSource: CaptureTitleSource,+ rawURLString: String,+ canonicalURLString: String? = nil,+ hostname: String,+ entryIdentityKey: String,+ timestamp: Date,+ capturedAt: Date? = nil,+ note: String = "",+ rating: Rating? = nil,+ work: Work? = nil+ ) {+ self.id = id+ self.captureTitle = captureTitle+ captureTitleSourceRaw = captureTitleSource.rawValue+ self.rawURLString = rawURLString+ self.canonicalURLString = canonicalURLString+ self.hostname = hostname+ self.entryIdentityKey = entryIdentityKey+ self.note = note+ ratingRaw = rating?.rawValue+ // The two clocks (Req 3.2, Decision 2). `capturedAt` is the instant the+ // reader shared the page, which a preserved capture carries and an+ // ordinary one does not: it supplies the two reader-facing fields and+ // nothing else. `modifiedAt` is bookkeeping about this row and always+ // takes `timestamp`, the instant of the write — backdating it would+ // change which of two diverging copies wins on another device.+ firstCapturedAt = capturedAt ?? timestamp+ lastSharedAt = capturedAt ?? timestamp+ modifiedAt = timestamp+ self.work = work+ // **Every code path that creates an Entry writes the blob at creation**+ // (V9 Req 4). Since the blob is the only home a citation has, a row born+ // without one would read as "cites nothing" for the rest of its life+ // rather than as "not converted yet" — so the default value is written+ // here, once, instead of at a dozen construction sites. A nil blob is+ // therefore only ever a row a V8 build wrote and this one has not+ // rewritten, which is exactly the state the validator reports — so the+ // default is encoded once into a constant rather than `try?`d here,+ // where a failed encode would spell itself the same way.+ citationsData = EntryCitations.defaultBlob+ }++ public var captureTitleSource: CaptureTitleSource {+ get { ToleratedEnum.read(captureTitleSourceRaw, default: .manual) }+ set { captureTitleSourceRaw = newValue.rawValue }+ }++ public var rating: Rating? {+ get { ToleratedEnum.read(ratingRaw) }+ set { ratingRaw = newValue?.rawValue }+ }++ public var identityBasis: EntryIdentityBasis {+ get { ToleratedEnum.read(identityBasisRaw, default: .conservative) }+ set { identityBasisRaw = newValue.rawValue }+ }++ /// The chapter title's provenance kind, **derived from the blob**. Read-only:+ /// the blob stores the whole citation, and a kind written without its cited+ /// rule is a state `EntryCitations` deliberately cannot spell (Q39). Writers+ /// go through `setCitations` or `editCitations`.+ public var chapterTitleProvenance: FieldProvenanceKind {+ citationValues.chapterTitle.kind+ }++ /// How this Entry came to be on its Work, derived from the blob. Read-only,+ /// for the reason above.+ public var workAssignmentProvenance: FieldProvenanceKind {+ citationValues.workAssignment.provenanceKind+ }++ /// Which half of a URL rule assigned the Work, derived from the blob.+ public var workURLAssignmentKind: URLWorkAssignmentKind? {+ citationValues.workURLAssignmentKind+ }++ /// Everything this Entry cites, as one value (Q25).+ ///+ /// Nil bytes read as the default — identity `.rawURL`, nothing cited (Q6).+ /// A nil blob means a row a V8 build wrote and V9 has not rewritten; it is+ /// reported by the validator and counted by the diagnosis, but an ordinary+ /// read of one must not throw or a single exposed row would fail a screen.+ ///+ /// Throws on bytes that will not decode, as `URLRulePattern.definition`+ /// does; the validator turns that into a reportable per-row state rather+ /// than a substituted value.+ public var citations: EntryCitations {+ get throws {+ guard let citationsData else { return EntryCitations() }+ return try JSONBlob.decode(EntryCitations.self, from: citationsData)+ }+ }++ /// Whether the row carries **no** citation bytes at all, as against bytes+ /// that decode to the default. The two read the same and are a different+ /// fact: the second is what a writer wrote, the first is a row the V8 → V9+ /// drop stage reached before anything converted it (Q6). The validator, the+ /// diagnosis and the counter all ask this question, so they ask it once.+ public var citationsAreAbsent: Bool { citationsData == nil }++ /// The citations as every ordinary reader wants them: bytes that will not+ /// decode read as the default rather than throwing, which is the same+ /// tolerance the enum columns had (Q2). The validator is the one caller that+ /// wants the throw, and it uses `citations`.+ public var citationValues: EntryCitations {+ (try? citations) ?? EntryCitations()+ }++ /// Reads the citations, applies `edit`, and writes them back — the door for+ /// a writer that owns some arms of the blob and must leave the rest alone.+ ///+ /// **Bytes that will not decode are repaired in place** (Q24): the edit is+ /// applied over the default value and written, which is what the retired+ /// column-derived refresh did — it replaced bytes that would not decode+ /// rather than leaving them diagnosed for ever. Skipping the write+ /// instead would land the caller's *surrounding* write (a manual+ /// assignment, a re-teach) with its provenance stuck at `.none`, which is a+ /// state the validator refuses on the next save. What the row loses is the+ /// citations nothing could read anyway.+ ///+ /// **A nil blob is not undecodable** (Q23). It reads as the default, so a+ /// real edit over one is written and a no-op edit over one leaves it nil —+ /// which is what kept `entriesWithoutCitationBlobCount` meaning something+ /// while the reconcilers walked every Entry to rewrite citations. Those+ /// walks are gone with the version rewriting (T-2281); the guard stays,+ /// because any bulk writer that arrives next would trip the same wire.+ ///+ /// Value-guarded, so a writer that changed nothing dirties no row.+ @discardableResult+ public func editCitations(_ edit: (inout EntryCitations) -> Void) -> Bool {+ let decoded = try? citations+ var edited = decoded ?? EntryCitations()+ edit(&edited)+ // Undecodable bytes: always write, even where the edit produced the+ // default — the point of the write is that the row stops being+ // unreadable.+ if let current = decoded, edited == current { return false }+ do { try setCitations(edited) } catch { return false }+ return true+ }++ /// Writes the citations, leaving the stored bytes untouched when encoding+ /// fails (Req 4.6) — the `URLRulePattern.setDefinition` guarantee.+ public func setCitations(_ citations: EntryCitations) throws {+ try setCitations(citations) { try JSONBlob.encode($0) }+ }++ /// The seam the "a failed encode changes nothing" test drives. The+ /// assignment happens only after `encode` returns.+ internal func setCitations(+ _ citations: EntryCitations,+ encode: (EntryCitations) throws -> Data+ ) throws {+ citationsData = try encode(citations)+ }+}++@Model+public final class Work {+ public var id: UUID = UUID()+ public var displayTitle: String = ""+ public var lastParsedTitle: String?+ public var genericNotes: String = ""+ /// V6: the `WorkTypeEntity` this Work is assigned, cited by UUID rather than+ /// modelled as a relationship (Decision 8 — an inverse would fault every+ /// Work assigned a type, the Q17 fan-out at larger scale). A dangling value+ /// is a tolerated state, not corruption (Req 8.6): the type row may simply+ /// not have arrived yet.+ public var workTypeID: UUID?+ public var genreTags: [String] = []+ public var titleProvenanceRaw: String = TitleProvenance.manual.rawValue+ /// V10: the **author's** side — whether the work is still being written+ /// (Req 1.1). Reader-entered; nothing infers it and a capture never changes+ /// it (Q8).+ ///+ /// Defaulted, non-optional and non-unique, the CloudKit-mirrored shape every+ /// other column here already has — and the initialiser is what SwiftData+ /// turns into the Core Data attribute default, which is what fills the+ /// column on every existing row during the V9 → V10 lightweight stage+ /// (Req 9.1). That is also why `Work.init` and both `create` doors are+ /// untouched: a defaulted column is not an init parameter (Req 2.6).+ public var workStatusRaw: String = WorkStatus.ongoing.rawValue+ /// V10: the **reader's** side — where they stand with the work (Req 2.1).+ /// Same shape and same reasoning as `workStatusRaw`.+ public var readingStatusRaw: String = ReadingStatus.reading.rawValue+ /// V10: the reader's closing thought once they are done with the work+ /// (Req 2.4) — why they stopped under `abandoned`, how they found it under+ /// `finished`. One field serves both (Q6).+ ///+ /// Stored trimmed, with no length limit; the trim happens in `updateWork`,+ /// beside `normalizeTags` and nowhere else (Q33). It survives a reading+ /// status returning to `reading` and is simply not shown (Q7, Req 2.5), so+ /// nothing here clears it.+ public var verdict: String = ""+ /// V11: the series this work belongs to, by identifier+ /// (`series-and-related-works` Decision 6). Resolved through+ /// `SeriesDirectory` exactly as `workTypeID` is resolved through+ /// `WorkTypeDirectory`, and for the same reason: an inverse relationship+ /// would fault every work and would nullify a value that must survive its+ /// target being absent. An identifier naming a `Series` this device does not+ /// hold is a **tolerated** state, not damage (Req 11.2).+ ///+ /// Optional rather than defaulted, which is what lets the V10 → V11 stage be+ /// bare `.lightweight` with no attribute default to fill: nil is "in no+ /// series", and an existing row arrives already saying so.+ public var seriesID: UUID?+ /// V11: where this work sits in that series — a finite decimal the reader+ /// enters, ties and gaps allowed (Req 2.1, 2.2).+ ///+ /// The pair is both-or-neither by convention: at the repository boundary it+ /// is one `SeriesMembership?` value, and a half-set row that arrives through+ /// sync reads as no membership and is normalised on the next write.+ public var seriesPosition: Double?+ /// V15: the weekdays this work's author publishes on, as lowercase English+ /// day names (`update-schedule` Req 1.1, Q27).+ ///+ /// Defaulted, non-optional and non-unique — the CloudKit-mirrored shape+ /// `genreTags` has had since V5, and the shape a small closed value set+ /// takes here. A bitmask would be unreadable in the CloudKit dashboard and+ /// in the archive, and a join table is the shape for a fact two devices edit+ /// concurrently, which one work's own days are not.+ ///+ /// The property initialiser is what SwiftData turns into the Core Data+ /// attribute default, which is what fills the column on every existing row+ /// during the V14 → V15 lightweight stage (Req 9.1). That is also why+ /// `Work.init` and both `create` doors are untouched: a defaulted column is+ /// not an init parameter, which is what makes Req 1.5's creation paths free.+ ///+ /// Read through `releaseDays` everywhere the set is shown or evaluated; the+ /// **raw** column is what export reads, so an unrepresentable value can be+ /// refused by name (Req 8.3).+ public var releaseDaysRaw: [String] = []+ /// V17: independently elected catch-up progress values. Optional blobs migrate as nil.+ public var catchUpConfirmationData: Data? = nil+ public var lastChapterOverrideData: Data? = nil+ /// V14: the reader's cover for this work, as JPEG bytes+ /// (`work-thumbnails` Decision 2, Req 1.1).+ ///+ /// **`.externalStorage` is part of the stored shape, not a hint.** SwiftData+ /// keeps the blob in a sidecar file under the store's `_SUPPORT` directory+ /// and leaves a reference on the row, which is what keeps the whole-table+ /// faults the works list, Recent, the validator and the extension's open all+ /// perform from reading a single cover (Req 7.1, Req 9.3): a host probe over+ /// 1,000 rows with one in five carrying 150 KB measured 0.2 MB resident+ /// against 62.7 MB inline, and the phone probe measured +0.0 MB against a+ /// 10 MB gate. It is the first `@Attribute` in the schema and it must+ /// survive the next freeze verbatim.+ ///+ /// Optional with no default, like V11's two columns: nil is "this work has+ /// no cover", so the V13 → V14 stage has nothing to write.+ ///+ /// The three columns below are written and cleared **together** by every+ /// writer that touches them (Req 1.4). A row where they disagree — bytes+ /// missing, or not matching the digest, or not of the shape's dimensions —+ /// is a *tolerated* state (Req 1.8), never a diagnosis: it presents the+ /// glyph until a Save sets or removes the thumbnail, and a restore heals it+ /// because import re-derives the digest from the archived bytes.+ @Attribute(.externalStorage)+ public var thumbnailData: Data?+ /// V14: the cover's shape, `"portrait"` or `"square"`. Read tolerantly+ /// through `thumbnailShape`, where a set but unrecognised spelling answers+ /// `.portrait` (Q63) — writing stays intolerant, and the export refuses an+ /// unknown raw by name (Req 8.3).+ public var thumbnailShapeRaw: String?+ /// V14: the SHA-256 hex of the cover bytes (Q38), which is what every+ /// comparison of thumbnails reads instead of the bytes (Decision 1,+ /// Req 1.7). Fixed for this schema generation (Req 1.10).+ public var thumbnailDigest: String?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// V7: the fingerprint of the generic-notes text a character-extraction pass+ /// last covered (Q59). Derived, like `Entry.characterExtractionFingerprint`,+ /// and excluded from authored content for the same reason.+ public var genericNotesExtractionFingerprint: String?+ @Relationship(deleteRule: .nullify, inverse: \Entry.work)+ public var entries: [Entry]?+ /// V7: the characters extracted or hand-created for this Work (Q58). The+ /// inverse of `Character.work`, `.nullify` exactly as `entries` is — the+ /// cascade is repository-enforced, so a nullified orphan is a tolerated+ /// in-flight state (Req 6.7) rather than a delete SwiftData performs behind+ /// the repository's back.+ @Relationship(deleteRule: .nullify, inverse: \Character.work)+ public var characters: [Character]?+ /// V7: the suppression rows scoped to this Work (Q60). Same shape and same+ /// reasoning as `characters`.+ @Relationship(deleteRule: .nullify, inverse: \CharacterSuppression.work)+ public var characterSuppressions: [CharacterSuppression]?+ /// V8: this Work's site memberships, one per hostname (Req 1.1, Q3). The+ /// inverse of `WorkSiteMembership.work`, `.nullify` exactly as `entries` is:+ /// the cascade is repository-enforced (Req 7.3), so a nullified orphan is a+ /// tolerated in-flight state (Req 8.3) rather than a delete SwiftData+ /// performs behind the repository's back.+ @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.work)+ public var siteMemberships: [WorkSiteMembership]? = []++ /// **Not public** (Decision 4, Q41): a Work must always hold at least one+ /// site membership (Req 1.3), and the only way to make that true by+ /// construction is to give creation a single door — `Work.create`, which+ /// mints the row and its first membership together. This initializer is the+ /// inside of that door, reachable from the package (and from `@testable`+ /// suites modelling a Req 2.7 membership-less arrival) and from nowhere else.+ ///+ /// It takes no hostname since V9: `siteHostname` was the last column a+ /// Work's site presence had outside its `WorkSiteMembership`, and the row+ /// that carries it is minted by `createCarrying` in the same call.+ init(id: UUID = UUID(), displayTitle: String, timestamp: Date) {+ self.id = id+ self.displayTitle = displayTitle+ createdAt = timestamp+ modifiedAt = timestamp+ }++ public var titleProvenance: TitleProvenance {+ get { ToleratedEnum.read(titleProvenanceRaw, default: .manual) }+ set { titleProvenanceRaw = newValue.rawValue }+ }++ /// Req 1.3: a spelling this build has no case for — an empty string+ /// included — reads as `ongoing` everywhere the status is shown or filtered.+ /// Writing is unaffected (Q19): committing edit mode writes what the picker+ /// showed, and the export still refuses an unrepresentable raw by name+ /// (Req 8.3).+ public var workStatus: WorkStatus {+ get { ToleratedEnum.read(workStatusRaw, default: .ongoing) }+ set { workStatusRaw = newValue.rawValue }+ }++ /// Req 2.7, the same policy on the reader's side, defaulting to `reading`.+ public var readingStatus: ReadingStatus {+ get { ToleratedEnum.read(readingStatusRaw, default: .reading) }+ set { readingStatusRaw = newValue.rawValue }+ }++ /// V15: the work's release days, canonical and ordered (Req 1.1).+ ///+ /// **Tolerant on read, canonical on write** — the same policy `workStatus`+ /// and `readingStatus` follow, spelled over an array. The getter drops a+ /// spelling this build has no case for, so an unknown value is ignored+ /// everywhere the set is shown or evaluated (Req 1.6); the setter writes the+ /// canonical order, so any write through this accessor normalises and two+ /// rows given the same days in different orders hold the same bytes+ /// (Req 7.5).+ ///+ /// Export reads `releaseDaysRaw` rather than this, so it can refuse an+ /// unknown value by name (Req 8.3, Q21), and the snapshot carries both, so+ /// the editor can tell a set that merely dropped an unknown value from an+ /// unchanged one.+ public var releaseDays: [ReleaseDay] {+ get { ReleaseDay.canonical(releaseDaysRaw.compactMap(ReleaseDay.init(rawValue:))) }+ set { releaseDaysRaw = ReleaseDay.canonical(newValue).map(\.rawValue) }+ }++ /// V14: the cover's shape, or nil where the column is unset. A *set* but+ /// unrecognised spelling reads as `.portrait` rather than as nil (Q63), so a+ /// cover a future build wrote is still shown, still removable and still+ /// named by the export refusal.+ public var thumbnailShape: ThumbnailShape? {+ ToleratedEnum.read(thumbnailShapeRaw, defaultIfSet: .portrait)+ }++ /// V14: the work's thumbnail **presence**, which is the shape and the digest+ /// and never the bytes (Req 1.1, Decision 1).+ ///+ /// Both columns set is a thumbnail; anything else is none. The bytes are+ /// expected beside them and their absence is tolerated (Req 1.8), which is+ /// exactly why presence has to be readable without them.+ public var thumbnailIdentity: ThumbnailIdentity? {+ guard let shape = thumbnailShape, let digest = thumbnailDigest else { return nil }+ return ThumbnailIdentity(shape: shape, digest: digest)+ }++ /// V14: the **one** way the three cover columns are written (Req 1.4).+ ///+ /// They are a tuple, and every writer either sets all three or clears all+ /// three — a row holding one of them without the others is the tolerated+ /// state Req 1.8 describes, never one a writer should be able to create by+ /// forgetting a line. Six call sites spelled the three assignments by hand;+ /// this is that spelling, once, so a seventh cannot be written wrong.+ ///+ /// Deliberately unguarded: *when* to write is the caller's policy and it+ /// differs per site — `updateWork` writes unconditionally so a re-pick+ /// repairs a torn row (Q58), the silent fold guards on the digest (Req+ /// 1.11), and import guards on all three so an unchanged cover does not+ /// rewrite an external-storage sidecar. This is only the write.+ public func applyThumbnail(bytes: Data?, shapeRaw: String?, digest: String?) {+ thumbnailData = bytes+ thumbnailShapeRaw = shapeRaw+ thumbnailDigest = digest+ }++ public var entryValues: [Entry] { entries ?? [] }+ public var characterValues: [Character] { characters ?? [] }+ public var characterSuppressionValues: [CharacterSuppression] { characterSuppressions ?? [] }++ /// The Work's memberships in the order Req 1.2 fixes: creation date, then+ /// identifier. Every surface that lists sites reads this, so "membership+ /// order" is one rule in one place rather than a sort each caller repeats.+ public var membershipValues: [WorkSiteMembership] {+ Self.membershipOrder(siteMemberships ?? [])+ }++ /// The **primary** membership: the first row in `membershipValues`, found+ /// without sorting the rest.+ ///+ /// `GroupOrdering` reads this once per Work on a path every write takes+ /// (Q18), and `membershipValues.first` charged that read a whole sort to+ /// answer a question `min` answers in one pass.+ public var primaryMembership: WorkSiteMembership? {+ (siteMemberships ?? []).min(by: Self.membershipPrecedes)+ }++ /// Req 1.2's order over an explicit set of rows, for the callers that hold+ /// one — a commit that has deleted a membership and not yet saved cannot+ /// trust the inverse array to have dropped it.+ static func membershipOrder(_ rows: [WorkSiteMembership]) -> [WorkSiteMembership] {+ rows.sorted(by: membershipPrecedes)+ }++ /// Req 1.2's comparison itself, so the order and the `min` that picks its+ /// first element cannot disagree about which membership is primary.+ private static func membershipPrecedes(+ _ lhs: WorkSiteMembership, _ rhs: WorkSiteMembership+ ) -> Bool {+ lhs.createdAt == rhs.createdAt+ ? lhs.id.uuidString < rhs.id.uuidString+ : lhs.createdAt < rhs.createdAt+ }++ /// The membership for `hostname`, or nil where the Work holds none.+ ///+ /// Req 1.1 forbids two memberships on one hostname, but sync can produce+ /// them until reconciliation resolves them (Req 2.6, 8.2), so this answers+ /// with one of them rather than asserting uniqueness — and the one it+ /// answers with is the **survivor** the dedupe would keep (Q23, Q61):+ /// strongest identity state, then earliest created, then lowest id.+ ///+ /// Deliberately *not* membership order, which Req 1.2 fixes for+ /// presentation. Between a duplicate arriving and the next reconcile, a+ /// state-`none` twin sorting first under `(createdAt, id)` would make+ /// identity-first matching read the Work as having no identity on this site+ /// (Req 3.1) and mint a second Work — a loss the reconcile could not undo.+ /// Answering with the survivor means the row this returns now is the row+ /// that will still be here afterwards.+ public func membership(for hostname: String) -> WorkSiteMembership? {+ Self.membership(in: siteMemberships ?? [], for: hostname)+ }++ /// The same answer over rows the caller already holds — a reader that+ /// fetched the memberships rather than faulting the inverse array (Q55,+ /// Decision 5). One rule in one place, so the two cannot disagree about+ /// which duplicate is the survivor.+ public static func membership(+ in rows: [WorkSiteMembership], for hostname: String+ ) -> WorkSiteMembership? {+ rows.filter { $0.hostname == hostname }.sorted { $0.id.uuidString < $1.id.uuidString }.first+ }++ /// Every row on `hostname` with the hostname matched+ /// **case-insensitively**, in survivor order+ /// (`wrong-host-work-url-heal` Q65).+ ///+ /// A stored hostname is not normalised, while a host derived from a URL+ /// always is, so a caller holding a derived host — the wrong-host heal, which+ /// asks about the membership of the host a Work URL names — cannot use the+ /// exact match above: a `Example.com` row would be invisible to it and it+ /// would mint a second row in a different case, which nothing ever folds.+ /// Every other caller holds a stored hostname already and keeps the exact+ /// match, which is one string comparison rather than two allocations.+ ///+ /// Plural because the heal needs both halves of the question — the row a+ /// value lands on, and *every* row a value is cleared from — and one+ /// spelling of "on this host" is what keeps those two agreeing.+ static func memberships(+ in rows: [WorkSiteMembership], forHostMatching hostname: String+ ) -> [WorkSiteMembership] {+ let host = hostname.lowercased()+ return rows.filter { $0.hostname.lowercased() == host }.sorted { $0.id.uuidString < $1.id.uuidString }+ }++ /// The survivor of `memberships(in:forHostMatching:)` — the row every+ /// caller that wants one gets handed.+ static func membership(+ in rows: [WorkSiteMembership], forHostMatching hostname: String+ ) -> WorkSiteMembership? {+ memberships(in: rows, forHostMatching: hostname).first+ }+}++@Model+public final class Site {+ public var hostname: String = ""+ public var displayName: String = ""+ public var modeRaw: String = SiteMode.untaught.rawValue+ @Relationship(deleteRule: .cascade, inverse: \TitlePattern.site)+ public var patterns: [TitlePattern]?+ @Relationship(deleteRule: .cascade, inverse: \URLRulePattern.site)+ public var urlRules: [URLRulePattern]?+ /// Inverse of `Entry.site`, present only because CloudKit requires every+ /// relationship to have one (Req 1.3). **Deliberately `internal`** while+ /// `Site` is `public`, so the app target cannot reach it: traversing this+ /// faults every Entry for a hostname — roughly 125× the fan-out of+ /// `Work.entries` — which the Req 5.1 budgets would pay for (Q17). No+ /// `entryValues` accessor exists, for the same reason.+ @Relationship(deleteRule: .nullify, inverse: \Entry.site)+ var entries: [Entry]?+ /// V8: inverse of `WorkSiteMembership.site`, present because CloudKit+ /// requires every relationship to have one. Internal for the same reason+ /// `works` is (Q17): traversing it faults every membership for a hostname,+ /// and the repository fetches memberships by predicate instead.+ @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.site)+ var workMemberships: [WorkSiteMembership]?+ // `junkSuffixRule` stood here: the reader-taught title cleaner articles mode+ // applied. It went with the mode at V16 (`remove-article-mode` Req 4.1). The+ // `JunkSuffixRule` type stays in `ValueObjects.swift`, unchanged and with no+ // consumer but the frozen `AsterismSchemaV17` snapshot, which is frozen by+ // reference to it (Q8).++ public init(hostname: String, displayName: String? = nil) {+ self.hostname = hostname+ self.displayName = displayName ?? hostname+ }++ public var mode: SiteMode {+ get { ToleratedEnum.read(modeRaw, default: .untaught) }+ set { modeRaw = newValue.rawValue }+ }++ /// The Site's active title pattern (Decision 5: a taught Site always holds+ /// exactly one). Nil for an untaught Site.+ ///+ /// One of the two accessors every reader of a current rule goes through+ /// (T-2281 Req 4.2, Q11): `RuleSelection.current` carries the Decision 1+ /// tiebreak for the double-marked Site the version invariant's retirement+ /// leaves readable until the next reconcile repairs it.+ public var activePattern: TitlePattern? { patternValues.first(where: \.isActive) }++ /// The Site's current URL rule, by the same rule as `activePattern`. Nil+ /// where the Site holds no marked URL rule.+ public var currentURLRule: URLRulePattern? { urlRuleValues.first(where: \.isCurrent) }++ public var patternValues: [TitlePattern] { patterns ?? [] }+ public var urlRuleValues: [URLRulePattern] { urlRules ?? [] }+}++@Model+public final class TitlePattern {+ public var id: UUID = UUID()+ public var version: Int = 1+ public var isActive: Bool = false+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// V8: the pattern's whole definition surface — the arm *and* both trims —+ /// as one `StoredPatternDefinition` blob (Q25), and since V9 the only home+ /// it has: the ten decomposed columns it superseded are gone.+ ///+ /// Nil means a row a V8 build wrote that nothing has rewritten since; no+ /// pass converts one, because the ten columns it would be derived from are+ /// gone. `storedDefinition` throws for one, the validator reports it as+ /// `unreadableTitlePattern`, and `GroupOrdering` gives it its own constant+ /// ordering key (Q11).+ public var definitionData: Data?+ public var site: Site?++ /// The trims are initializer parameters rather than columns a caller+ /// assigns afterwards: V8 stores the whole definition surface as one blob+ /// (Q25), so a trim written after construction would have to re-encode it.+ public init(+ id: UUID = UUID(),+ version: Int,+ isActive: Bool = false,+ createdAt: Date,+ definition: PatternDefinition,+ trimPrefix: String? = nil,+ trimSuffix: String? = nil,+ site: Site? = nil+ ) throws {+ guard version > 0 else {+ throw ModelInvariantError.nonPositiveVersion(field: "title pattern version")+ }+ self.id = id+ self.version = version+ self.isActive = isActive+ self.createdAt = createdAt+ // **Before the relationship, deliberately.** Assigning `site` to a row+ // that is already in a context registers this object with that context+ // there and then, and SwiftData snapshots the backing data at that+ // point: a `definitionData` written afterwards is dropped on an+ // SQLite-backed store (it survives an in-memory one, which is how this+ // hid). Every stored value goes in first, the relationship last.+ try setDefinition(+ StoredPatternDefinition(+ definition: try definition.validated(),+ trimPrefix: trimPrefix, trimSuffix: trimSuffix))+ self.site = site+ }++ /// Compatibility initializer for V1-shaped tests and migration mapping. It+ /// always creates the V2 segment arm; runtime callers still validate it+ /// against the injected gate before persistence.+ public convenience init(+ id: UUID = UUID(),+ version: Int,+ isActive: Bool = false,+ createdAt: Date,+ workAnchor: SegmentRangeSpec,+ junkAnchors: [SegmentPositionSpec] = [],+ site: Site? = nil+ ) {+ try! self.init(+ id: id,+ version: version,+ isActive: isActive,+ createdAt: createdAt,+ definition: .segment(work: workAnchor, ignored: junkAnchors),+ site: site+ )+ }++ /// The pattern's whole definition surface, read from the blob (Q25) — the+ /// only home it has since V9.+ ///+ /// Throws rather than substituting a rule the reader never taught (Req 4.3),+ /// exactly as `URLRulePattern.definition` does and for the same reason: a+ /// fabricated definition validates cleanly and blames the captures. **A nil+ /// blob throws for that reason too**: it used to fall back to the ten legacy+ /// columns, and with those unwritten there is nothing behind it. The+ /// validator reports such a row as `unreadableTitlePattern` and+ /// `GroupOrdering` gives it its own constant ordering key (Q11).+ public var storedDefinition: StoredPatternDefinition {+ get throws {+ guard let definitionData else {+ throw ModelInvariantError.invalidCombination(field: "title pattern definition")+ }+ return try JSONBlob.decode(StoredPatternDefinition.self, from: definitionData)+ }+ }++ /// The arm alone. Every caller that also needs the trims reads+ /// `storedDefinition` once instead, because this decodes on every access.+ public var definition: PatternDefinition {+ get throws { try storedDefinition.definition }+ }++ /// Writes the whole definition surface, leaving the stored bytes untouched+ /// when encoding fails (Req 4.6) — the `URLRulePattern.setDefinition`+ /// guarantee, for the same reason: one failed write must not leave bytes+ /// behind that will not decode on the next read.+ public func setDefinition(_ definition: StoredPatternDefinition) throws {+ try setDefinition(definition) { try JSONBlob.encode($0) }+ }++ /// The seam the "a failed encode changes nothing" test drives. The+ /// assignment happens only after `encode` returns, which is the whole+ /// guarantee.+ internal func setDefinition(+ _ definition: StoredPatternDefinition,+ encode: (StoredPatternDefinition) throws -> Data+ ) throws {+ definitionData = try encode(definition)+ }++ /// Writes a definition only where it differs from the one already stored,+ /// and reports whether anything changed.+ ///+ /// The value guard is what makes a second reconciliation pass over a+ /// converged rule group export no transaction (Req 2.4 of+ /// `relational-references`). It compares the **whole** surface, trims+ /// included: two rows agreeing on the arm and differing in a trim derive+ /// different chapter titles, so a group "converged" without them would still+ /// replay two answers (Q63).+ @discardableResult+ internal func applyStoredDefinition(_ definition: StoredPatternDefinition) throws -> Bool {+ let validated = StoredPatternDefinition(+ definition: try definition.definition.validated(),+ trimPrefix: definition.trimPrefix,+ trimSuffix: definition.trimSuffix)+ guard (try? storedDefinition) != validated else { return false }+ try setDefinition(validated)+ return true+ }+}++@Model+public final class URLRulePattern {+ public var id: UUID = UUID()+ public var version: Int = 1+ public var isCurrent: Bool = false+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var originRaw: String = URLRuleOrigin.readerTaught.rawValue+ public var definitionData: Data = Data()+ public var site: Site?++ public init(+ id: UUID = UUID(),+ version: Int,+ isCurrent: Bool,+ createdAt: Date,+ origin: URLRuleOrigin,+ definition: URLRuleDefinition,+ site: Site? = nil+ ) throws {+ guard version > 0 else {+ throw ModelInvariantError.nonPositiveVersion(field: "URL rule version")+ }+ try definition.validate(origin: origin, isCurrent: isCurrent)+ self.id = id+ self.version = version+ self.isCurrent = isCurrent+ self.createdAt = createdAt+ originRaw = origin.rawValue+ self.definitionData = try JSONBlob.encode(definition)+ self.site = site+ }++ public var origin: URLRuleOrigin? { URLRuleOrigin(rawValue: originRaw) }++ /// Throws rather than substituting a rule the reader never taught (Req 4.3),+ /// mirroring `TitlePattern.definition`.+ ///+ /// It used to answer a decode failure with+ /// `.work(locator: .query(name: "identity"))`. No URL in a real library+ /// carries an `identity` query item, so every extraction against the+ /// substitute failed with `missingComponent`, the citing Works' evidence+ /// became `.failed`, and their URL identity was cleared — while the+ /// diagnosis blamed the captures, because the *fabricated* definition+ /// validates cleanly (Decision 5).+ public var definition: URLRuleDefinition {+ get throws {+ try JSONBlob.decode(URLRuleDefinition.self, from: definitionData)+ }+ }++ /// Writes a definition, leaving the stored bytes untouched when encoding+ /// fails (Req 4.6).+ ///+ /// A Swift computed-property setter cannot throw, and the one this replaced+ /// wrote `Data()` on an encoding failure — itself a route to bytes that will+ /// not decode, so one failed write produced an unreadable rule on the next+ /// read with no version skew involved. Leaving the old bytes in place is+ /// also what keeps the rule recoverable rather than overwritten.+ public func setDefinition(_ definition: URLRuleDefinition) throws {+ try setDefinition(definition) { try JSONBlob.encode($0) }+ }++ /// The seam the "a failed encode changes nothing" test drives. Production+ /// goes through the public overload; the assignment happens only after+ /// `encode` returns, which is the whole guarantee.+ internal func setDefinition(+ _ definition: URLRuleDefinition,+ encode: (URLRuleDefinition) throws -> Data+ ) throws {+ definitionData = try encode(definition)+ }+}++/// V6: one entry in the configured work-type list (Decision 3). Works cite it by+/// `Work.workTypeID`; it cites nothing back, so it declares **no relationships**+/// at all (Decision 8).+///+/// Removal is a state change, never a delete: the additive-only CloudKit posture+/// this project holds to means a removed entry stays in the store so works can+/// keep displaying it (Req 5.1) and so restoring it is the same identity again+/// (Req 5.3). `merged` marks an entry convergence redirected to `canonicalID`+/// (Req 6.2/6.3).+///+/// **The per-field timestamps are load-bearing** (Decision 10). Duplicate rows of+/// one identity are permanent — concurrent seeding creates them and nothing ever+/// deletes them — so two devices' edits can land on *different rows* of the same+/// UUID. Only a field-wise fold combines a remove written to one row with a+/// rename written to another (Req 6.6), which is what `WorkTypeDirectory` does;+/// `modifiedAt` is derived from the two, the max.+///+/// Epoch (`Date(timeIntervalSince1970: 0)`) field timestamps are the *pristine*+/// sentinel: a seeded row nobody has touched never asserts its spelling or state+/// against a user-touched row (Decision 9). Anything that stamps a seed row's+/// timestamps without a user action silently promotes it.+@Model+public final class WorkTypeEntity {+ public var id: UUID = UUID()+ /// The stored spelling, trimmed, as the user entered it. Normalized names+ /// are computed in the directory and never stored (Q30).+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = WorkTypeState.active.rawValue+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The identity this entry merged into, set when `state == .merged`. Never+ /// rewritten after the marking: the chase is total instead (Q31).+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// `max(nameModifiedAt, stateModifiedAt)`, maintained by the shared writer.+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ /// Every parameter is defaulted so the memberwise construction and the+ /// stored defaults are the same thing — a row created with no arguments is+ /// the pristine empty active entry CloudKit would materialize.+ public init(+ id: UUID = UUID(),+ name: String = "",+ state: WorkTypeState = .active,+ canonicalID: UUID? = nil,+ timestamp: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.name = name+ stateRaw = state.rawValue+ self.canonicalID = canonicalID+ createdAt = timestamp+ modifiedAt = timestamp+ nameModifiedAt = timestamp+ stateModifiedAt = timestamp+ }++ /// Unknown raw values read as `.active`, matching every other enum column in+ /// this schema: an unrecognised state is tolerated data, not corruption.+ public var state: WorkTypeState {+ get { ToleratedEnum.read(stateRaw, default: .active) }+ set { stateRaw = newValue.rawValue }+ }+}++/// V7: one character of one work — accepted from an extraction proposal or+/// created by hand (Decision 1). Reader-authored throughout: the name, the+/// aliases, the note and the facts' statements are all editable, so the record+/// participates in the duplicate/torn machinery like an Entry or a Work.+///+/// Facts are a Codable blob rather than a table (Q57), on the+/// `URLRulePattern.definitionData` precedent: a fact edit is a character-level+/// authored change, so a character tears at character granularity, and the+/// entry-detail lookup scans a work's characters, where N is small.+///+/// `nameKey` is **retained**: minted once at accept or creation commit (Q19/Q46)+/// and never re-derived from a rename, so a renamed character keeps attracting+/// the proposals that named it before (Req 2.3's second matching tier).+///+/// Every property is defaulted or optional and nothing is unique: this is a+/// CloudKit-mirrored table like the rest.+@Model+public final class Character {+ public var id: UUID = UUID()+ public var name: String = ""+ /// The key the character was accepted or created under, retained through+ /// renames (Q19/Q46). Normalised by `RecordNameKey.normalize`.+ public var nameKey: String = ""+ /// Extra match keys, reader-editable (Q56) and grown by the combine+ /// (Decision 4). Stored as the reader's spellings; matching normalises.+ public var aliases: [String] = []+ public var note: String = ""+ /// `[RecordFact]` in the canonical encoding (Q75). Optional rather than+ /// defaulted-empty because CloudKit materialises a missing column as nil,+ /// and "no facts yet" and "column not synced" are the same thing to a+ /// reader.+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The Work this character belongs to. Nil is a **tolerated** in-flight+ /// state (Req 6.7, Q70): a character that synced ahead of its work is inert+ /// — reachable only through the work — and appears when the work lands.+ public var work: Work?++ /// Every parameter defaulted, so memberwise construction and the stored+ /// defaults are the same value CloudKit would materialise.+ public init(+ id: UUID = UUID(),+ name: String = "",+ nameKey: String = "",+ aliases: [String] = [],+ note: String = "",+ facts: [RecordFact] = [],+ timestamp: Date = Date(timeIntervalSince1970: 0),+ work: Work? = nil+ ) {+ self.id = id+ self.name = name+ self.nameKey = nameKey+ self.aliases = aliases+ self.note = note+ factsData = RecordFactCodec.encode(facts)+ createdAt = timestamp+ modifiedAt = timestamp+ self.work = work+ }++ // `facts` is `RecordRow`'s (RecordRow.swift): the decode is the same for+ // every record table, so it is written once rather than per model.+}++/// V7: one remembered decision not to re-propose something (Q60/Q72).+///+/// A **system record**, never reader-authored (Q40): it never tears, never+/// blocks an export, and converges to the reader's most recent action rather+/// than by set union — which is what makes a clear (Req 2.5) representable at+/// all. Writes update the local row in place, keyed by+/// (work, kind, nameKey, source, evidence); rows duplicated by sync are read+/// through by latest `actionAt`, tie-broken cleared-wins then lowest row UUID+/// (Q82).+@Model+public final class CharacterSuppression {+ public var id: UUID = UUID()+ /// Nil is tolerated for the same reason `Character.work` tolerates it.+ public var work: Work?+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ /// Present on fact rows only; nil on candidate rows. Explicit rather than+ /// inferred from a nil `sourceEntryID`, so a malformed row is+ /// distinguishable from a generic-notes citation (Q72).+ public var sourceKindRaw: String?+ /// Set only where `sourceKind == .entry`.+ public var sourceEntryID: UUID?+ /// The fact's evidence span, on fact rows only. The third component of the+ /// identity triple (Q29).+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ /// When the reader acted. The comparable Q52 convergence needs (Q60).+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ work: Work? = nil,+ kind: CharacterSuppressionKind = .candidate,+ nameKey: String = "",+ source: SourceRef? = nil,+ evidence: String? = nil,+ status: CharacterSuppressionStatus = .active,+ actionAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.work = work+ kindRaw = kind.rawValue+ self.nameKey = nameKey+ sourceKindRaw = source?.kindRaw+ sourceEntryID = source?.entryID+ self.evidence = evidence+ statusRaw = status.rawValue+ self.actionAt = actionAt+ }++ /// An unknown raw value reads as `.candidate`, matching every other enum+ /// column in this schema: unrecognised data is tolerated, not corruption.+ public var kind: CharacterSuppressionKind {+ get { ToleratedEnum.read(kindRaw, default: .candidate) }+ set { kindRaw = newValue.rawValue }+ }++ public var status: CharacterSuppressionStatus {+ get { ToleratedEnum.read(statusRaw, default: .active) }+ set { statusRaw = newValue.rawValue }+ }++ /// The cited source on a fact row, or nil on a candidate row — and nil for a+ /// malformed row, which is why `sourceKindRaw` is stored explicitly.+ public var source: SourceRef? {+ get { SourceRef(kindRaw: sourceKindRaw, entryID: sourceEntryID) }+ set {+ sourceKindRaw = newValue?.kindRaw+ sourceEntryID = newValue?.entryID+ }+ }+}++/// V8: a Work's presence on one site (Q3).+///+/// The row a Work's site presence moved into: one per hostname, carrying that+/// site's URL identity, the identity state, the rule that derived it and the+/// confirmed Work URL for that site. A Work holds at least one (Req 1.3) and+/// never two on one hostname (Req 1.1) — though sync can produce a duplicate+/// until reconciliation resolves it (Req 2.6, 8.2).+///+/// `workID` sits beside the `work` relationship deliberately (Q37): an import-+/// or sync-orphaned row must be able to re-attach when its Work arrives, and a+/// nullified relationship alone loses the intent. A membership whose Work has+/// not arrived is tolerated indefinitely and deleted only with its Work+/// (Req 8.3, Q22).+///+/// Every property is defaulted or optional, nothing is unique, and both+/// relationships are `.nullify` with their inverse on the to-many side: this is+/// a CloudKit-mirrored table like the rest.+@Model+public final class WorkSiteMembership {+ public var id: UUID = UUID()+ public var hostname: String = ""+ /// Req 1.2's ordering key, paired with `id`. A membership minted by the+ /// population pass copies its Work's `createdAt`, so a migrated single-site+ /// Work orders exactly as it did before.+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var urlIdentity: String?+ public var urlIdentityStateRaw: String = WorkURLIdentityState.none.rawValue+ /// The rule row that derived `urlIdentity`, **by UUID only** (Req 10.4,+ /// Q28): the citation names the row and carries no version.+ public var urlIdentityRuleID: UUID?+ public var workURLString: String?+ /// The Work this row belongs to, kept while `work` is nil (Q37).+ public var workID: UUID?+ public var work: Work?+ /// The Site row for `hostname`, nil while it has not arrived — the same+ /// tolerance `Entry.site` carries (Req 1.5).+ public var site: Site?++ /// Every parameter defaulted, so memberwise construction and the stored+ /// defaults are the value CloudKit would materialise.+ public init(+ id: UUID = UUID(),+ hostname: String = "",+ createdAt: Date = Date(timeIntervalSince1970: 0),+ urlIdentity: String? = nil,+ urlIdentityState: WorkURLIdentityState = .none,+ urlIdentityRuleID: UUID? = nil,+ workURLString: String? = nil,+ workID: UUID? = nil,+ work: Work? = nil,+ site: Site? = nil+ ) {+ self.id = id+ self.hostname = hostname+ self.createdAt = createdAt+ self.urlIdentity = urlIdentity+ urlIdentityStateRaw = urlIdentityState.rawValue+ self.urlIdentityRuleID = urlIdentityRuleID+ self.workURLString = workURLString+ self.workID = workID ?? work?.id+ self.work = work+ self.site = site+ }++ /// An unrecognised spelling reads as `.none`, matching every other enum+ /// column in this schema.+ public var urlIdentityState: WorkURLIdentityState {+ get { ToleratedEnum.read(urlIdentityStateRaw, default: .none) }+ set { urlIdentityStateRaw = newValue.rawValue }+ }++ /// The Work this row belongs to, by identifier: the column where a writer+ /// set it, the relationship where a lagging one did not (Q37).+ ///+ /// Reading the relationship faults it, so a caller walking the whole table+ /// on the capture path reads `workID` alone (Q84) and does not come through+ /// here. This is for the callers that must not miss a row an older writer+ /// attached without the column.+ public var resolvedWorkID: UUID? { workID ?? work?.id }++ /// Every membership in the store, indexed by the Work it names, **by+ /// `workID` alone**.+ ///+ /// Nothing here reads `membership.work`: that faults one relationship per+ /// row, on passes that run on every foreground and every arrival, which is+ /// the cost Q84 is written around. A row naming no Work is an orphan+ /// awaiting one (Req 8.3) and belongs to no Work's list; a row with a blank+ /// hostname is on no site (Q30) and contributes no relation.+ ///+ /// Each Work's list comes back in **survivor order** — the order membership+ /// de-duplication keeps a survivor by, and the order the wrong-host Work URL+ /// heal takes its candidates in (Q35). Without it, a caller asking "which+ /// value does this Work hold on this hostname" would be answered by fetch+ /// order, which two devices need not agree on, and the foreground pass and+ /// the full validator could name different hosts for one torn group. The+ /// ordering columns are read as three scalars beside the ones the basis+ /// carries; the rows themselves are still not retained.+ static func indexByWorkID(+ context: ModelContext, batchSize: Int+ ) throws -> [UUID: [WorkMembershipBasis]] {+ // The ordering columns are carried as raw scalars, not as an `OrderKey`:+ // the key is built below for the groups that actually have rows to sort,+ // so the common single-membership Work pays no key at all (Q60).+ typealias Row = (+ state: WorkURLIdentityState, createdAt: Date, id: UUID, basis: WorkMembershipBasis+ )+ var index: [UUID: [Row]] = [:]+ try context.enumerate(+ FetchDescriptor<WorkSiteMembership>(), batchSize: batchSize+ ) { membership in+ // The same blankness test `LibraryValidator.validate(membership:)`+ // applies, so a whitespace-only hostname is on no site here either.+ guard let workID = membership.workID, !M2Unicode.isBlank(membership.hostname)+ else { return }+ index[workID, default: []].append(+ (membership.urlIdentityState, membership.createdAt, membership.id,+ WorkMembershipBasis(+ hostname: membership.hostname, urlIdentity: membership.urlIdentity,+ workURLString: membership.workURLString)))+ }+ return index.mapValues { rows in+ guard rows.count > 1 else { return rows.map(\.basis) }+ return rows+ .map { (key: OrderKey($0.state, $0.createdAt, $0.id), basis: $0.basis) }+ .sorted { $0.key < $1.key }+ .map(\.basis)+ }+ }++ /// Q23's survivor order as three scalars, so a caller that must not retain+ /// the rows can still sort by it — and so the one order has one spelling.+ ///+ /// `indexByWorkID` walks the whole table under `enumerate` and yields value+ /// snapshots; `wrong-host-work-url-heal` Q35 makes the two derivations of+ /// the wrong-host diagnosis agree only because they take their candidates in+ /// **one** order. `MembershipReconciler.survivorFirst` sorts on it too.+ ///+ /// The identifier is kept as a `UUID` and stringified only inside `<`+ /// (Q60): the key is built on the foreground scan and the arrival duplicate+ /// phase, and a `uuidString` per membership there is an allocation on a path+ /// this repo already keeps keys out of.+ struct OrderKey: Comparable {+ let identityRank: Int+ let createdAt: Date+ let id: UUID++ init(_ membership: WorkSiteMembership) {+ self.init(membership.urlIdentityState, membership.createdAt, membership.id)+ }++ init(_ state: WorkURLIdentityState, _ createdAt: Date, _ id: UUID) {+ identityRank = Self.rank(state)+ self.createdAt = createdAt+ self.id = id+ }++ /// The strongest identity state first, then the earliest created, then+ /// the lowest identifier.+ ///+ /// State leads because earliest-created alone would let a healed+ /// state-`none` row discard a rule-derived identity — the exact pair+ /// `multi-site-works` Req 2.6 produces when one device heals a Work the+ /// other had already migrated.+ static func < (left: OrderKey, right: OrderKey) -> Bool {+ if left.identityRank != right.identityRank {+ return left.identityRank > right.identityRank+ }+ if left.createdAt != right.createdAt { return left.createdAt < right.createdAt }+ return UUID.bytesPrecede(left.id, right.id)+ }++ private static func rank(_ state: WorkURLIdentityState) -> Int {+ switch state {+ case .rule: 2+ case .legacyUnverified: 1+ case .none: 0+ }+ }+ }+}++/// V8: the reader's "not the same work" over an unordered pair of Works+/// (Req 5.5, Q20).+///+/// Two UUID columns rather than relationships (Q27): a pair must outlive the+/// absence of either Work and re-point by rewriting a column, where a+/// relationship would nullify silently. `lowerWorkID` and `higherWorkID` are the+/// two identifiers sorted, so the unordered pair has one spelling and duplicate+/// detection is a group-by (Req 5.8).+@Model+public final class WorkDistinctPair {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ public var recordedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ lowerWorkID: UUID = UUID(),+ higherWorkID: UUID = UUID(),+ recordedAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.lowerWorkID = lowerWorkID+ self.higherWorkID = higherWorkID+ self.recordedAt = recordedAt+ }++ /// The canonical spelling of an unordered pair: the two ids sorted by their+ /// string form, which is the ordering every writer and every group-by uses.+ public static func sortedIDs(_ a: UUID, _ b: UUID) -> (lower: UUID, higher: UUID) {+ a.uuidString <= b.uuidString ? (a, b) : (b, a)+ }+}++/// V11: a reader-named collection a work belongs to at a position+/// (`series-and-related-works` Decision 1).+///+/// **No relationships**, on `WorkDistinctPair`'s grounds (its Q27) and+/// Decision 6's: a work names its series by `Work.seriesID`, so a series+/// outlives the absence of any member and a member outlives the absence of its+/// series. An inverse would fault every work in the series to answer a count,+/// and would nullify a membership that must survive a target still in transit.+///+/// Names are **not** unique (Q11): two devices may create "Foo" concurrently,+/// and the reader resolves it by moving works rather than by a convergence rule.+/// Where two listed series share a name, `SeriesDirectory` qualifies them.+///+/// Every column is defaulted, non-optional and non-unique — the CloudKit+/// -mirrored shape every other column here already has.+@Model+public final class Series {+ public var id: UUID = UUID()+ /// Stored trimmed, with no length limit (Req 1.1).+ public var name: String = ""+ /// The reader's notes about the set rather than about any one work (Q7).+ /// Stored trimmed; may be empty.+ public var notes: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// Stamped by every writer with the quantized clock. No convergence rule+ /// reads it — a rename is not a convergence question, because names need+ /// not be unique — but archive import does: `commitSeries` keeps the row+ /// unless the record is at least as recent (`series-and-related-works`+ /// Req 13.4).+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ name: String = "",+ notes: String = "",+ createdAt: Date = Date(timeIntervalSince1970: 0),+ modifiedAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.name = name+ self.notes = notes+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// V11: an undirected, typed connection between two distinct works+/// (`series-and-related-works` Decision 5).+///+/// The shape is `WorkDistinctPair`'s, for the same reasons: two UUID columns+/// rather than relationships, so a link outlives the absence of either end and+/// re-points by rewriting a column; `lowerWorkID` and `higherWorkID` are the two+/// identifiers sorted through `WorkDistinctPair.sortedIDs`, so the unordered+/// pair has one spelling and duplicate detection is a group-by.+///+/// What it adds over a distinct pair is content the reader owns — a free-text+/// `linkType` — and therefore a `modifiedAt` a convergence rule reads: when more+/// than one row exists over a pair after sync, every device keeps the latest+/// modification, then the lowest identifier (Q27, Req 11.4).+@Model+public final class WorkLink {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ /// Free text, stored trimmed and non-empty (Req 6.4). Not a managed+ /// vocabulary: the suggestions are derived from the rows that exist.+ public var linkType: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// The survivor key over a duplicated pair, latest first (Req 11.4).+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ lowerWorkID: UUID = UUID(),+ higherWorkID: UUID = UUID(),+ linkType: String = "",+ createdAt: Date = Date(timeIntervalSince1970: 0),+ modifiedAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.lowerWorkID = lowerWorkID+ self.higherWorkID = higherWorkID+ self.linkType = linkType+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// V12: a person a work is credited to (`work-creators` Decision 2).+///+/// The shape is `WorkTypeEntity`'s (`:814`), for its reasons: **no+/// relationships** at all — a `WorkCredit` names a creator by identifier — and+/// **one timestamp per independently converging field**, because duplicate rows+/// of one identity are permanent under CloudKit and two devices' edits can land+/// on different rows of the same UUID. Only a field-wise fold combines a rename+/// written to one row with a merge written to another (Q26). `modifiedAt` is+/// derived from the field timestamps, the max, and exists for the archive guard+/// and the list rather than for the fold.+///+/// Epoch (`Date(timeIntervalSince1970: 0)`) field timestamps are the *pristine*+/// sentinel (Q36): a record nobody has touched never asserts its spelling or+/// state against a reader-touched row.+///+/// There is **no `removed` state**: a creator the reader deletes is really+/// deleted, along with the credits naming it (Decision 4, Q16). `merged` marks+/// the loser of a name collision, redirected to `canonicalID`.+///+/// Every column is defaulted, non-optional and non-unique — the+/// CloudKit-mirrored shape. `stateRaw` defaults to the **literal** `"active"`+/// rather than to a case's `rawValue`, so the next freeze inherits one fewer+/// frozen enum spelling; it is read through `ToleratedEnum` at the call sites.+@Model+public final class Creator {+ public var id: UUID = UUID()+ /// The stored spelling, trimmed, as the reader entered it. Normalized names+ /// are computed in the directory and never stored.+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// Free text — "also publishes as X" and the like (Q7). Stored trimmed; may+ /// be empty. Convergence appends a loser's notes to the survivor's.+ public var notes: String = ""+ public var notesModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The identity this record merged into, set when the state is `merged`.+ /// Never rewritten after the marking: the chase is total instead.+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// `max(nameModifiedAt, notesModifiedAt, stateModifiedAt)`, maintained by+ /// the shared writer.+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ /// Every parameter is defaulted so the memberwise construction and the+ /// stored defaults are the same thing — a row created with no arguments is+ /// the pristine empty active record CloudKit would materialize.+ public init(+ id: UUID = UUID(),+ name: String = "",+ notes: String = "",+ stateRaw: String = "active",+ canonicalID: UUID? = nil,+ timestamp: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.name = name+ self.notes = notes+ self.stateRaw = stateRaw+ self.canonicalID = canonicalID+ createdAt = timestamp+ modifiedAt = timestamp+ nameModifiedAt = timestamp+ notesModifiedAt = timestamp+ stateModifiedAt = timestamp+ }+}++/// V12: one entry in the reader-managed, ordered role list credits reference by+/// identity (`work-creators` Decision 1).+///+/// `Creator`'s shape with `position` in place of `notes`, and a third state:+/// removal is a state change, never a delete, so a credit keeps the identifier+/// and simply does not show it, and adding the name again restores the same+/// identity (Decision 4).+///+/// A seeded role's `positionModifiedAt` is the pristine sentinel, so a reader's+/// reorder on another device — which stamps every shifted role — beats it in the+/// fold.+@Model+public final class CreatorRole {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The reader's order, 0-based over the active roles. It is also the first+ /// key a work's credits are ordered by (Q10).+ public var position: Int = 0+ public var positionModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// `max(nameModifiedAt, positionModifiedAt, stateModifiedAt)`.+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ name: String = "",+ position: Int = 0,+ stateRaw: String = "active",+ canonicalID: UUID? = nil,+ timestamp: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.name = name+ self.position = position+ self.stateRaw = stateRaw+ self.canonicalID = canonicalID+ createdAt = timestamp+ modifiedAt = timestamp+ nameModifiedAt = timestamp+ positionModifiedAt = timestamp+ stateModifiedAt = timestamp+ }+}++/// V12: one work-and-creator pairing, carrying the roles that creator holds on+/// that work (`work-creators` Decision 6).+///+/// The shape is `WorkLink`'s: plain UUID columns rather than relationships, so a+/// credit outlives the absence of the work, the creator or any role it names —+/// which is the tolerated unresolved state the sync rules are written around,+/// not damage. Nothing prunes a row for naming an absent target.+///+/// `roleIDs` is a plain SwiftData `[String]` on the `genreTags` shape, holding+/// role identifiers as `uuidString`. It is **`[String]` rather than `[UUID]` on+/// purpose** (Q47): every array column this CloudKit-mirrored schema carries is+/// `[String]`, and a `[UUID]` array would be the first of its kind under+/// mirroring. It is stored sorted and deduplicated at every write, so equal sets+/// are equal arrays; an entry that does not parse as a UUID is ignored on read.+@Model+public final class WorkCredit {+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var creatorID: UUID = UUID()+ public var roleIDs: [String] = []+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ /// Stamped when the role set changes. The dedupe over a duplicated pair+ /// keeps the *earliest* created row rather than the latest modified one+ /// (Q42), so this is the archive guard rather than the survivor key.+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ workID: UUID = UUID(),+ creatorID: UUID = UUID(),+ roleIDs: [String] = [],+ createdAt: Date = Date(timeIntervalSince1970: 0),+ modifiedAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.workID = workID+ self.creatorID = creatorID+ self.roleIDs = roleIDs+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// V13: one named place of one work — accepted from an extraction proposal or+/// created by hand (`place-extraction` Decision 3, Q3).+///+/// The shape is `Character`'s, field for field, because the two are one record+/// type to every piece of store code: `RecordRow` is written once and both+/// tables conform (Decision 3). What differs is the single column below.+///+/// **The owning work is a `UUID` column, not a relationship** — the `WorkCredit`+/// shape, and CLAUDE.md's standing rule made a fourth time. An inverse would+/// fault every place of a work to answer a count, and a `.nullify` on an absent+/// target would erase a value that has to survive while the work is still in+/// transit. `workID` is non-optional and defaulted (Q44): the value is always+/// known at insert, and an orphan keeps the id it will re-attach by, so nothing+/// needs to be nullable. Orphan-ness is "no work resolves", never nil (Req 5.5).+///+/// `nameKey` is **retained**: minted once at accept or creation commit and never+/// re-derived from a rename, so a renamed place keeps attracting the proposals+/// that named it before. A place converted from a character carries the+/// character's retained key (Q34).+///+/// Every property is defaulted or optional and nothing is unique: this is a+/// CloudKit-mirrored table like the rest.+@Model+public final class Place {+ public var id: UUID = UUID()+ public var name: String = ""+ /// The key the place was accepted, created or converted under, retained+ /// through renames. Normalised by `RecordNameKey.normalize`.+ public var nameKey: String = ""+ /// Extra match keys, reader-editable and grown by the combine. Stored as the+ /// reader's spellings; matching normalises.+ public var aliases: [String] = []+ public var note: String = ""+ /// `[RecordFact]` in the canonical encoding. Optional rather than+ /// defaulted-empty because CloudKit materialises a missing column as nil,+ /// and "no facts yet" and "column not synced" are the same thing to a+ /// reader.+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ /// The Work this place belongs to, by identifier. A value naming no Work is+ /// a **tolerated** orphan: displayed nowhere, never validated, exported+ /// as-is, and found by the predicate the moment the work arrives (Req 5.5).+ public var workID: UUID = UUID()++ /// Every parameter defaulted, so memberwise construction and the stored+ /// defaults are the same value CloudKit would materialise.+ public init(+ id: UUID = UUID(),+ name: String = "",+ nameKey: String = "",+ aliases: [String] = [],+ note: String = "",+ facts: [RecordFact] = [],+ timestamp: Date = Date(timeIntervalSince1970: 0),+ workID: UUID = UUID()+ ) {+ self.id = id+ self.name = name+ self.nameKey = nameKey+ self.aliases = aliases+ self.note = note+ factsData = RecordFactCodec.encode(facts)+ createdAt = timestamp+ modifiedAt = timestamp+ self.workID = workID+ }++ // `facts` is `RecordRow`'s (RecordRow.swift): the decode is the same for+ // every record table, so it is written once rather than per model.+}++/// V13: one remembered decision not to re-propose a **place**+/// (`place-extraction` Decision 2).+///+/// A separate record type rather than a record-kind column on+/// `CharacterSuppression`, because both configurations mirror to CloudKit and a+/// pre-feature build sharing the container cannot see a new column: to that+/// build a place suppression would be a character suppression with the same+/// converging tuple, and accepting a character would *clear* it (Req 5.2). A+/// record type it does not know is ignored entirely.+///+/// A **system record**, like its character twin: it never tears, never blocks an+/// export, and converges to the reader's most recent action rather than by set+/// union. The two enum columns store the raw strings `CharacterSuppressionKind`+/// and `CharacterSuppressionStatus` spell — the enums are shared across kinds+/// (Q27) — and the defaults name those cases rather than restating their+/// spellings, exactly as `CharacterSuppression` does.+///+/// The work is a `UUID` column for `Place`'s reasons.+@Model+public final class PlaceSuppression {+ public var id: UUID = UUID()+ /// The Work this suppression belongs to, by identifier. An unresolved value+ /// is the same tolerated orphan `Place.workID` describes.+ public var workID: UUID = UUID()+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ /// Present on fact rows only; nil on candidate rows. Explicit rather than+ /// inferred from a nil `sourceEntryID`, so a malformed row is+ /// distinguishable from a generic-notes citation.+ public var sourceKindRaw: String?+ /// Set only where `sourceKind == .entry`.+ public var sourceEntryID: UUID?+ /// The fact's evidence span, on fact rows only. The third component of the+ /// identity triple.+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ /// When the reader acted. The comparable convergence needs.+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init(+ id: UUID = UUID(),+ workID: UUID = UUID(),+ kind: CharacterSuppressionKind = .candidate,+ nameKey: String = "",+ source: SourceRef? = nil,+ evidence: String? = nil,+ status: CharacterSuppressionStatus = .active,+ actionAt: Date = Date(timeIntervalSince1970: 0)+ ) {+ self.id = id+ self.workID = workID+ kindRaw = kind.rawValue+ self.nameKey = nameKey+ sourceKindRaw = source?.kindRaw+ sourceEntryID = source?.entryID+ self.evidence = evidence+ statusRaw = status.rawValue+ self.actionAt = actionAt+ }++ /// An unknown raw value reads as `.candidate`, matching every other enum+ /// column in this schema: unrecognised data is tolerated, not corruption.+ public var kind: CharacterSuppressionKind {+ get { ToleratedEnum.read(kindRaw, default: .candidate) }+ set { kindRaw = newValue.rawValue }+ }++ public var status: CharacterSuppressionStatus {+ get { ToleratedEnum.read(statusRaw, default: .active) }+ set { statusRaw = newValue.rawValue }+ }++ /// The cited source on a fact row, or nil on a candidate row — and nil for a+ /// malformed row, which is why `sourceKindRaw` is stored explicitly.+ public var source: SourceRef? {+ get { SourceRef(kindRaw: sourceKindRaw, entryID: sourceEntryID) }+ set {+ sourceKindRaw = newValue?.kindRaw+ sourceEntryID = newValue?.entryID+ }+ }+}++} // extension AsterismSchemaV17
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swiftnew file mode 100644index 00000000..f68d6520--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift@@ -0,0 +1,41 @@+import Foundation+import SwiftData++/// The live schema. V18 adds an independent action table with scalar work IDs.+public enum AsterismSchemaV18: VersionedSchema {+ public static let versionIdentifier = Schema.Version(18, 0, 0)++ public static var models: [any PersistentModel.Type] {+ [Entry.self, Work.self, Site.self, TitlePattern.self, URLRulePattern.self,+ WorkTypeEntity.self, Character.self, CharacterSuppression.self,+ WorkSiteMembership.self, WorkDistinctPair.self, Series.self, WorkLink.self,+ Creator.self, CreatorRole.self, WorkCredit.self, Place.self,+ PlaceSuppression.self, NoEpisodeAction.self]+ }+}++public enum AsterismV18MigrationPlan: SchemaMigrationPlan {+ public static var schemas: [any VersionedSchema.Type] {+ [AsterismSchemaV16.self, AsterismSchemaV17.self, AsterismSchemaV18.self]+ }++ public static var stages: [MigrationStage] {+ [.lightweight(fromVersion: AsterismSchemaV16.self, toVersion: AsterismSchemaV17.self),+ .lightweight(fromVersion: AsterismSchemaV17.self, toVersion: AsterismSchemaV18.self)]+ }+}++extension AsterismSchemaV18 {+ @Model+ public final class NoEpisodeAction {+ public var workID: UUID = UUID()+ public var key: String = ""+ public var payloadData: Data = Data()++ public init(workID: UUID, key: String, payloadData: Data) {+ self.workID = workID+ self.key = key+ self.payloadData = payloadData+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swiftindex 831065ec..fc2cb7ea 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: [BackupV16Entry]- let sites: [BackupV16Site]- let titlePatterns: [BackupV16TitlePattern]- let urlRules: [BackupV16URLRule]+ let entries: [BackupV17Entry]+ let sites: [BackupV17Site]+ let titlePatterns: [BackupV17TitlePattern]+ let urlRules: [BackupV17URLRule] /// 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: [BackupV16Membership]+ let memberships: [BackupV17Membership] } /// 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 BackupV16ExportError.referencesStillArriving(+ throw BackupV17ExportError.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 BackupV16ExportError.referencesStillArriving(+ throw BackupV17ExportError.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: [BackupV16Site] = []- var wirePatterns: [BackupV16TitlePattern] = []- var wireRules: [BackupV16URLRule] = []+ var wireSites: [BackupV17Site] = []+ var wirePatterns: [BackupV17TitlePattern] = []+ var wireRules: [BackupV17URLRule] = [] for site in projected {- wireSites.append(mapV16SiteRecord(site))+ wireSites.append(mapV17SiteRecord(site)) for projectedPattern in site.patterns where !omittedTitlePatternIDs.contains(projectedPattern.pattern.id) { wirePatterns.append(- try mapV16TitlePatternRecord(projectedPattern, hostname: site.hostname))+ try mapV17TitlePatternRecord(projectedPattern, hostname: site.hostname)) } for projectedRule in site.urlRules where !omittedURLRuleIDs.contains(projectedRule.rule.id) {- wireRules.append(try mapV16URLRuleRecord(projectedRule, hostname: site.hostname))+ wireRules.append(try mapV17URLRuleRecord(projectedRule, hostname: site.hostname)) } } return ArchiveCommonProjection( groups: groups,- entries: try groups.entries.map { try mapV16EntryRecord($0, citations: citations) },+ entries: try groups.entries.map { try mapV17EntryRecord($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,7 +225,7 @@ extension LibraryRepository { // than reached by a mapper that would throw a raw `DecodingError`. do { _ = try citations.value(of: entry) } catch {- throw BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.unrepresentableValue( record: record, field: "citations", value: String(describing: error)) } }@@ -234,14 +234,14 @@ extension LibraryRepository { if let data = work.catchUpConfirmationData { do { _ = try JSONBlob.decode(CatchUpConfirmation.self, from: data) } catch {- throw BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.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(+ throw BackupV17ExportError.unrepresentableValue( record: record, field: "last chapter override", value: String(describing: error)) } }@@ -266,22 +266,22 @@ extension LibraryRepository { case (nil, nil): break case (let id?, nil):- throw BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.unrepresentableValue( record: record, field: "series membership", value: "series \(id) with no position") case (nil, let position?):- throw BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.unrepresentableValue( record: record, field: "series membership", value: "position \(position) with no series") case (_?, let position?): guard position.isFinite else {- throw BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.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 BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.unrepresentableValue( record: record, field: "series position", value: String(position)) } }@@ -289,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 `mapV16WorkRecord`, against+ // archive exports. It is refused in `mapV17WorkRecord`, against // exactly the bytes the record takes (Q79). // // `update-schedule` Req 8.3, on the statuses' terms: the accessor@@ -329,7 +329,7 @@ extension LibraryRepository { // `formRaw` that no longer exists. do { _ = try pattern.storedDefinition } catch {- throw BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.unrepresentableValue( record: record, field: "definition", value: String(describing: error)) } }@@ -367,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 BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.unrepresentableValue( record: "URL rule \(id)", field: "definition", value: "\(rule.definitionData.count) bytes that do not decode") }@@ -418,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 BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.unrepresentableValue( record: "Title rule \(id)", field: "definition", value: pattern.definitionData.map { "\($0.count) bytes that do not decode" } ?? "no stored definition")@@ -474,7 +474,7 @@ extension LibraryRepository { _ value: Value?, _ record: String, _ field: String, _ raw: String ) throws { guard value == nil else { return }- throw BackupV16ExportError.unrepresentableValue(record: record, field: field, value: raw)+ throw BackupV17ExportError.unrepresentableValue(record: record, field: field, value: raw) } /// Req 3.7's third face: a hostname whose *projected* tuple the archive@@ -499,7 +499,7 @@ extension LibraryRepository { switch site.mode { case .taught: guard activePatterns != 1 else { continue }- throw BackupV16ExportError.referencesStillArriving(+ throw BackupV17ExportError.referencesStillArriving( detail: "site \(site.hostname) is taught, and the one active title rule " + "that state needs is not in the library") case .untaught:@@ -507,7 +507,7 @@ extension LibraryRepository { $0.rule.origin == .importedV2 && !$0.isCurrent } guard !site.patterns.isEmpty || currentRules > 0 || !historyOnly else { continue }- throw BackupV16ExportError.referencesStillArriving(+ throw BackupV17ExportError.referencesStillArriving( detail: "site \(site.hostname) is untaught while still holding rules, " + "so the teaching that owns them has not arrived") }@@ -528,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: [BackupV16Entry],- memberships: [BackupV16Membership],- titlePatterns: [BackupV16TitlePattern],- urlRules: [BackupV16URLRule]+ entries: [BackupV17Entry],+ memberships: [BackupV17Membership],+ titlePatterns: [BackupV17TitlePattern],+ urlRules: [BackupV17URLRule] ) throws { let rulesByID = Dictionary(urlRules.map { ($0.id, $0) }, uniquingKeysWith: { lhs, _ in lhs }) let patternHostnames = Dictionary(@@ -571,14 +571,14 @@ extension LibraryRepository { private static func crossSiteCitation( _ record: String, _ field: String, taughtFor hostname: String- ) -> BackupV16ExportError {+ ) -> BackupV17ExportError { .referencesStillArriving( detail: "\(record) names \(field), which is taught for \(hostname)") } private static func missingCitation( _ record: String, _ field: String- ) -> BackupV16ExportError {+ ) -> BackupV17ExportError { .referencesStillArriving( detail: "\(record) names \(field), which the library does not hold") }@@ -625,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 mapV16EntryRecord(+ internal static func mapV17EntryRecord( _ group: EntryGroup, citations cache: EntryCitationsCache- ) throws -> BackupV16Entry {+ ) throws -> BackupV17Entry { let snap = try snapshot(group) let entry = group.representative let carrier = group.carrier@@ -637,7 +637,7 @@ extension LibraryRepository { citations.chapterTitle = carried.chapterTitle citations.workAssignment = carried.workAssignment }- return BackupV16Entry(+ return BackupV17Entry( id: snap.id, captureTitle: snap.captureTitle, captureTitleSource: snap.captureTitleSource,@@ -717,34 +717,37 @@ 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 BackupV16ExportError.unrepresentableValue(- record: titled, field: BackupV16ExportError.thumbnailField, value: raw)+ throw BackupV17ExportError.unrepresentableValue(+ record: titled, field: BackupV17ExportError.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 BackupV16ExportError.unrepresentableValue(- record: titled, field: BackupV16ExportError.thumbnailField,+ throw BackupV17ExportError.unrepresentableValue(+ record: titled, field: BackupV17ExportError.thumbnailField, value: "\(bytes.count) bytes that are not a \(raw) cover") } return bytes } - internal static func mapV16WorkRecord(+ internal static func mapV17WorkRecord( _ group: WorkGroup, canonicalWorkIDs: [UUID: UUID], types: WorkTypeDirectory- ) throws -> BackupV16Work {+ ) throws -> BackupV17Work { 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 `BackupV16Work` carries is a read+ // exported work to fill a field no `BackupV17Work` carries is a read // this path skips.- credits: .empty)+ credits: .empty,+ // This mapper reads only Work-owned columns. The archive projects+ // full action history separately from the indexed action table.+ history: .empty) let thumbnailBytes = try requireRepresentableCover(group) let thumbnailShapeRaw = thumbnailBytes == nil ? nil : group.carrier.thumbnailShapeRaw let assignment = WorkTypeAssignment.assignment(of: group.carrier)@@ -756,7 +759,7 @@ extension LibraryRepository { case .configured(let id): (workTypeID, typeName) = (id, types.resolve(id)?.name) }- return BackupV16Work(+ return BackupV17Work( id: snap.id, displayTitle: snap.displayTitle, lastParsedTitle: snap.lastParsedTitle,@@ -840,7 +843,7 @@ extension LibraryRepository { /// there. private static func mapMembershipRecords( _ rows: [WorkSiteMembership]- ) -> [BackupV16Membership] {+ ) -> [BackupV17Membership] { var byKey: [MembershipReconciler.Key: [WorkSiteMembership]] = [:] var unattributed: [WorkSiteMembership] = [] for row in rows {@@ -851,8 +854,8 @@ extension LibraryRepository { byKey[MembershipReconciler.Key(workID: workID, hostname: row.hostname), default: []] .append(row) }- func record(_ row: WorkSiteMembership, workURLString: String?) -> BackupV16Membership {- BackupV16Membership(+ func record(_ row: WorkSiteMembership, workURLString: String?) -> BackupV17Membership {+ BackupV17Membership( id: row.id, workID: row.resolvedWorkID, hostname: row.hostname, createdAt: row.createdAt, urlIdentity: row.urlIdentity, urlIdentityState: row.urlIdentityState,@@ -867,7 +870,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: [BackupV16Membership] = []+ var records: [BackupV17Membership] = [] for rows in byKey.values { let ordered = MembershipReconciler.survivorFirst(rows) guard let keeper = ordered.first else { continue }@@ -905,7 +908,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 -> [BackupV16Series] {+ internal static func projectSeries(context: ModelContext) throws -> [BackupV17Series] { var byID: [UUID: Series] = [:] for row in try context.fetch(FetchDescriptor<Series>()) { guard let held = byID[row.id] else {@@ -916,7 +919,7 @@ extension LibraryRepository { } return byID.values .map {- BackupV16Series(+ BackupV17Series( id: $0.id, name: $0.name, notes: $0.notes, createdAt: $0.createdAt, modifiedAt: $0.modifiedAt) }@@ -938,7 +941,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 -> [BackupV16Link] {+ internal static func projectLinks(context: ModelContext) throws -> [BackupV17Link] { var byKey: [WorkPairKey: [WorkLink]] = [:] for row in try context.fetch(FetchDescriptor<WorkLink>()) where row.lowerWorkID != row.higherWorkID {@@ -948,7 +951,7 @@ extension LibraryRepository { guard let survivor = MembershipReconciler.survivorFirstLinks(rows).first else { return nil }- return BackupV16Link(+ return BackupV17Link( id: survivor.id, lowerWorkID: key.lower, higherWorkID: key.higher, linkType: survivor.linkType, createdAt: survivor.createdAt, modifiedAt: survivor.modifiedAt)@@ -980,7 +983,7 @@ extension LibraryRepository { /// the same number the next local pass would. internal static func projectCredits( context: ModelContext, creators: CreatorDirectory- ) throws -> [BackupV16Credit] {+ ) throws -> [BackupV17Credit] { var byKey: [CreditReconciler.Key: [WorkCredit]] = [:] for row in try context.fetch(FetchDescriptor<WorkCredit>()) { let key = CreditReconciler.Key(@@ -990,7 +993,7 @@ extension LibraryRepository { return byKey.compactMap { _, rows in let ordered = WorkCreditSupport.survivorFirstCredits(rows) guard let head = ordered.first else { return nil }- return BackupV16Credit(+ return BackupV17Credit( id: head.id, workID: head.workID, creatorID: head.creatorID, roleIDs: WorkCreditSupport.roleIDs(ordered.flatMap(\.roleIDs)), createdAt: head.createdAt,@@ -1001,7 +1004,7 @@ extension LibraryRepository { internal static func projectDistinctPairs( context: ModelContext- ) throws -> [BackupV16DistinctPair] {+ ) throws -> [BackupV17DistinctPair] { var byKey: [WorkPairKey: [WorkDistinctPair]] = [:] for row in try context.fetch(FetchDescriptor<WorkDistinctPair>()) where row.lowerWorkID != row.higherWorkID {@@ -1013,7 +1016,7 @@ extension LibraryRepository { guard let survivor = MembershipReconciler.survivorFirstPairs(rows).first else { return nil }- return BackupV16DistinctPair(+ return BackupV17DistinctPair( id: survivor.id, lowerWorkID: key.lower, higherWorkID: key.higher, recordedAt: survivor.recordedAt) }@@ -1023,20 +1026,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 mapV16SiteRecord(+ internal static func mapV17SiteRecord( _ projected: SiteUnionProjection.ProjectedSite- ) -> BackupV16Site {- BackupV16Site(+ ) -> BackupV17Site {+ BackupV17Site( hostname: projected.hostname, displayName: projected.displayName, mode: projected.mode ) } - internal static func mapV16TitlePatternRecord(+ internal static func mapV17TitlePatternRecord( _ projected: SiteUnionProjection.ProjectedTitlePattern, hostname: String- ) throws -> BackupV16TitlePattern {- BackupV16TitlePattern(+ ) throws -> BackupV17TitlePattern {+ BackupV17TitlePattern( id: projected.pattern.id, siteHostname: hostname, // The version stored on the row the per-UUID reduction kept, without@@ -1051,17 +1054,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 mapV16URLRuleRecord(+ internal static func mapV17URLRuleRecord( _ projected: SiteUnionProjection.ProjectedURLRule, hostname: String- ) throws -> BackupV16URLRule {+ ) throws -> BackupV17URLRule { let definition: URLRuleDefinition do { definition = try projected.rule.definition } catch {- throw BackupV16ExportError.unrepresentableValue(+ throw BackupV17ExportError.unrepresentableValue( record: "URL rule \(projected.rule.id)", field: "definition", value: "\(projected.rule.definitionData.count) bytes that do not decode") }- return BackupV16URLRule(+ return BackupV17URLRule( 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 ccec9f43..501f8d9e 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: [BackupV16Entry],- works: [BackupV16Work],- memberships: [BackupV16Membership],- distinctPairs: [BackupV16DistinctPair],- sites: [BackupV16Site],- titlePatterns: [BackupV16TitlePattern],- urlRules: [BackupV16URLRule],- series: [BackupV16Series],- links: [BackupV16Link],- creators: [BackupV16Creator],- creatorRoles: [BackupV16CreatorRole],- credits: [BackupV16Credit],+ entries: [BackupV17Entry],+ works: [BackupV17Work],+ memberships: [BackupV17Membership],+ distinctPairs: [BackupV17DistinctPair],+ sites: [BackupV17Site],+ titlePatterns: [BackupV17TitlePattern],+ urlRules: [BackupV17URLRule],+ series: [BackupV17Series],+ links: [BackupV17Link],+ creators: [BackupV17Creator],+ creatorRoles: [BackupV17CreatorRole],+ credits: [BackupV17Credit], formatLabel: String ) throws { let siteHostnames = Set(sites.map(\.hostname))@@ -314,9 +314,9 @@ internal enum BackupArchiveReferenceChecks { // MARK: Site closed tuple (supersedes M3 8.1) private static func validateSiteTuple(- _ site: BackupV16Site,- patterns: [BackupV16TitlePattern],- rules: [BackupV16URLRule]+ _ site: BackupV17Site,+ patterns: [BackupV17TitlePattern],+ rules: [BackupV17URLRule] ) throws { let id = site.hostname guard !M2Unicode.isBlank(site.hostname) else { throw invalid("Site", id, "hostname is blank") }@@ -377,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: BackupV16Membership,+ _ membership: BackupV17Membership, siteHostnames: Set<String>,- rulesByID: [UUID: BackupV16URLRule]+ rulesByID: [UUID: BackupV17URLRule] ) throws { let id = membership.id.uuidString guard !M2Unicode.isBlank(membership.hostname) else {@@ -408,12 +408,12 @@ internal enum BackupArchiveReferenceChecks { // MARK: Entry (Entry-state enumeration, supersedes M3 8.12) private static func validateEntry(- _ entry: BackupV16Entry,+ _ entry: BackupV17Entry, siteHostnames: Set<String>, workIDs: Set<UUID>, hostnamesByWork: [UUID: Set<String>],- patternsByID: [UUID: BackupV16TitlePattern],- rulesByID: [UUID: BackupV16URLRule]+ patternsByID: [UUID: BackupV17TitlePattern],+ rulesByID: [UUID: BackupV17URLRule] ) throws { let id = entry.id.uuidString guard siteHostnames.contains(entry.hostname) else {@@ -494,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: BackupV16Entry, rulesByID: [UUID: BackupV16URLRule]+ _ cited: CitedRule, entry: BackupV17Entry, rulesByID: [UUID: BackupV17URLRule] ) -> Bool { rulesByID[cited.id]?.siteHostname == entry.hostname } private static func requireSameSiteRule( _ cited: CitedRule,- entry: BackupV16Entry,- rulesByID: [UUID: BackupV16URLRule]+ entry: BackupV17Entry,+ rulesByID: [UUID: BackupV17URLRule] ) throws { guard resolvesSameSite(cited, entry: entry, rulesByID: rulesByID) else { throw invalid(@@ -512,10 +512,10 @@ internal enum BackupArchiveReferenceChecks { } private static func validateEntryRuleReference(- _ entry: BackupV16Entry,+ _ entry: BackupV17Entry, field: String, cited: CitedRule?,- rulesByID: [UUID: BackupV16URLRule]+ rulesByID: [UUID: BackupV17URLRule] ) 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 3a8d3287..3ae5ee21 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. `BackupV16Exporter` is the only producer.+/// cleaned up afterwards. `BackupV17Exporter` 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 b1ad158c..7ab18182 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: `BackupV16ExportError.tornGroups` when the store holds a torn+ /// - Throws: `BackupV17ExportError.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 BackupV16ExportError.tornGroups(+ throw BackupV17ExportError.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 6f588658..2bd272d4 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: [BackupV16Creator],- creatorRoles: [BackupV16CreatorRole],+ creators: [BackupV17Creator],+ creatorRoles: [BackupV17CreatorRole], importedAt: Date, context: ModelContext, saveStrategy: any RepositorySaveStrategy@@ -72,7 +72,7 @@ extension LibraryRepository { /// - Returns: whether anything was written. private static func mergeImportedCreators(- _ records: [BackupV16Creator], context: ModelContext+ _ records: [BackupV17Creator], 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: BackupV16Creator]+ _ survivor: UUID, local: CreatorDirectory, archive: [UUID: BackupV17Creator] ) -> 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: [BackupV16CreatorRole], importedAt: Date, context: ModelContext+ _ records: [BackupV17CreatorRole], 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: BackupV16CreatorRole]+ _ survivor: UUID, local: CreatorRoleDirectory, archive: [UUID: BackupV17CreatorRole] ) -> 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 64caca2f..fc725158 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 BackupV16Character: ArchivedRecord {+extension BackupV17Character: ArchivedRecord { var recordID: UUID { id } var archivedWorkID: UUID? { workID } } -extension BackupV16Place: ArchivedRecord {+extension BackupV17Place: ArchivedRecord { var recordID: UUID { id } var archivedWorkID: UUID? { workID } } -extension BackupV16Suppression: ArchivedSuppression {+extension BackupV17Suppression: ArchivedSuppression { var recordID: UUID { id } var archivedWorkID: UUID? { workID } } -extension BackupV16PlaceSuppression: ArchivedSuppression {+extension BackupV17PlaceSuppression: 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 8546abf5..933a8d59 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: [BackupV16WorkType],- works: [BackupV16Work],+ workTypes: [BackupV17WorkType],+ works: [BackupV17Work], 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: [BackupV16WorkType]+ _ records: [BackupV17WorkType] ) -> [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: [BackupV16Work], in local: WorkTypeDirectory+ _ works: [BackupV17Work], 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 e1aadd6a..845c78ad 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift@@ -11,47 +11,49 @@ import OSLog /// longer exist and every accessor answered the same arm three times. What /// remains is the payload's arrays, named. ///-/// This is `BackupV16Payload`'s content rather than the type itself: the wire+/// This is `BackupV17Payload`'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: [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 let entries: [BackupV17Entry]+ public let works: [BackupV17Work]+ public let sites: [BackupV17Site]+ public let titlePatterns: [BackupV17TitlePattern]+ public let urlRules: [BackupV17URLRule]+ public let workTypes: [BackupV17WorkType]+ public let memberships: [BackupV17Membership]+ public let distinctPairs: [BackupV17DistinctPair]+ public let characters: [BackupV17Character]+ public let suppressions: [BackupV17Suppression]+ public let places: [BackupV17Place]+ public let placeSuppressions: [BackupV17PlaceSuppression]+ public let series: [BackupV17Series]+ public let links: [BackupV17Link]+ public let creators: [BackupV17Creator]+ public let creatorRoles: [BackupV17CreatorRole]+ public let credits: [BackupV17Credit]+ public let noEpisodeActions: [BackupV17NoEpisodeAction] public init(- 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] = []+ entries: [BackupV17Entry],+ works: [BackupV17Work],+ sites: [BackupV17Site],+ titlePatterns: [BackupV17TitlePattern],+ urlRules: [BackupV17URLRule],+ workTypes: [BackupV17WorkType] = [],+ memberships: [BackupV17Membership] = [],+ distinctPairs: [BackupV17DistinctPair] = [],+ characters: [BackupV17Character] = [],+ suppressions: [BackupV17Suppression] = [],+ places: [BackupV17Place] = [],+ placeSuppressions: [BackupV17PlaceSuppression] = [],+ series: [BackupV17Series] = [],+ links: [BackupV17Link] = [],+ creators: [BackupV17Creator] = [],+ creatorRoles: [BackupV17CreatorRole] = [],+ credits: [BackupV17Credit] = [],+ noEpisodeActions: [BackupV17NoEpisodeAction] = [] ) { self.entries = entries self.works = works@@ -81,9 +83,10 @@ public struct BackupImportPayload: Sendable, Equatable { // archive's row is normalised on the way in rather than left as a shape // the next comparison never matches. self.credits = credits.map(\.normalized)+ self.noEpisodeActions = noEpisodeActions } - public init(_ payload: BackupV16Payload) {+ public init(_ payload: BackupV17Payload) { self.init( entries: payload.entries, works: payload.works, sites: payload.sites, titlePatterns: payload.titlePatterns, urlRules: payload.urlRules,@@ -92,7 +95,8 @@ public struct BackupImportPayload: Sendable, Equatable { suppressions: payload.suppressions, places: payload.places, placeSuppressions: payload.placeSuppressions, series: payload.series, links: payload.links, creators: payload.creators,- creatorRoles: payload.creatorRoles, credits: payload.credits)+ creatorRoles: payload.creatorRoles, credits: payload.credits,+ noEpisodeActions: payload.noEpisodeActions) } /// Whether any record carries a character-extraction coverage fingerprint.@@ -134,7 +138,7 @@ public struct BackupImportPlan: Sendable, Equatable { /// A plan over a wire payload, which is how every archive reaches one. public init(- metadata: BackupImportMetadata, payload: BackupV16Payload,+ metadata: BackupImportMetadata, payload: BackupV17Payload, counts: LibraryRecordCounts ) { self.init(@@ -252,7 +256,7 @@ public enum BackupImporter { /// constants, so the accepted pair moves with the generation rather than /// being restated here. private static let supportedVersions = (- format: BackupV16Document.formatVersion, schema: BackupV16Document.schemaVersion+ format: BackupV17Document.formatVersion, schema: BackupV17Document.schemaVersion ) // MARK: - Plan Dispatch (Req 5.1, 5.2, Decision 2)@@ -283,9 +287,9 @@ public enum BackupImporter { } private static func planFromArchive(_ data: Data) throws -> BackupImportPlan {- let document: BackupV16Document+ let document: BackupV17Document do {- document = try BackupV16Codec.decode(data)+ document = try BackupV17Codec.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 5009227f..fd19ed23 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 `BackupV16Codec`: the+// paths were removed. Both helpers are used by the live `BackupV17Codec`: 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. `BackupV16ArchiveTests` covers both properties by editing+/// no-trailing-bytes. `BackupV17ArchiveTests` 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/BackupV17Codec.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV17Codec.swiftnew file mode 100644index 00000000..1e40f8cc--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV17Codec.swift@@ -0,0 +1,301 @@+import Foundation++/// The strict 17/18 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.+///+/// The only codec. It was cloned from the 11/12 one rather than grown out of it —+/// a shipped archive format is never redefined in place — and 11/12 was deleted+/// with the payload it described (`place-extraction` Req 5.1, Q51). What it+/// shares with nothing in+/// particular, because there is nothing else, is stated once beside it: the+/// record-level checking body (`BackupArchiveReferenceChecks`), the envelope+/// shape (`BackupArchiveShapeValidator`) and the canonical JSON settings.+///+/// 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 17/18 backup declares. 17/18 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 BackupV17Codec {+ /// Pinned literally. 17/18 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 = "V17"++ // MARK: - Encode++ /// The envelope's keys that sort **before** `"payload"`, and the one that+ /// sorts after it.+ ///+ /// The payload is encoded once, for the checksum, and then spliced into the+ /// envelope rather than encoded a second time as `BackupV17Document.payload`+ /// would be. Over a covered library the payload is tens of megabytes and the+ /// envelope is a hundred bytes, so the second encode was the whole file+ /// written twice to add nine keys to it.+ ///+ /// Two halves rather than a search for where to insert: the canonical+ /// encoder sorts keys, so the split point is a fact about the alphabet+ /// (`exportedAt` < `payload` < `workCount`) and not something to look for in+ /// bytes a build string could have imitated.+ private struct EnvelopeHead: Encodable {+ let appBuild: String+ let backupFormatVersion: Int+ let capabilityGate: String+ let checksum: String+ let databaseSchemaVersion: Int+ let entryCount: Int+ let exportedAt: Date+ }++ private struct EnvelopeTail: Encodable {+ let workCount: Int+ }++ public static func encode(+ payload: BackupV17Payload,+ metadata: BackupV17Metadata+ ) throws -> Data {+ let encoder = BackupCanonicalJSON.encoder()++ let payloadData = try encoder.encode(payload)+ let checksum = BackupCanonicalJSON.sha256Hex(payloadData)++ let head = try encoder.encode(EnvelopeHead(+ appBuild: metadata.appBuild,+ backupFormatVersion: BackupV17Document.formatVersion,+ capabilityGate: Self.gate,+ checksum: checksum,+ databaseSchemaVersion: BackupV17Document.schemaVersion,+ entryCount: payload.entries.count,+ exportedAt: metadata.exportedAt))+ let tail = try encoder.encode(EnvelopeTail(workCount: payload.works.count))++ guard head.first == UInt8(ascii: "{"), head.last == UInt8(ascii: "}"),+ tail.first == UInt8(ascii: "{"), tail.last == UInt8(ascii: "}")+ else {+ throw BackupCodecError.encodingFailed(reason: "envelope halves are not JSON objects")+ }++ var document = Data(capacity: head.count + payloadData.count + tail.count + 16)+ document.append(head.dropLast()) // {"appBuild":…,"exportedAt":"…"+ document.append(contentsOf: Array(#","payload":"#.utf8))+ document.append(payloadData)+ document.append(UInt8(ascii: ","))+ document.append(tail.dropFirst()) // "workCount":N}+ return document+ }++ // MARK: - Decode++ /// 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.+ ///+ /// The version pair is exact. `(9, 9)` and `(8, 10)` are rejected here, not+ /// only at the importer's dispatch: a mismatched pair is a file this codec+ /// cannot claim to understand whichever door it arrived through.+ ///+ /// 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 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 -> BackupV17Document {+ do {+ let rootKeys = try DuplicateJSONKeyValidator.validate(data)+ try BackupArchiveShapeValidator.validate(rootKeys: rootKeys)++ let document = try BackupCanonicalJSON.decoder()+ .decode(BackupV17Document.self, from: data)++ guard document.backupFormatVersion == BackupV17Document.formatVersion else {+ throw BackupCodecError.invalidFormatVersion(document.backupFormatVersion)+ }+ guard document.databaseSchemaVersion == BackupV17Document.schemaVersion else {+ throw BackupCodecError.invalidSchemaVersion(document.databaseSchemaVersion)+ }+ guard document.capabilityGate == Self.gate else {+ throw BackupCodecError.unsupportedGate(document.capabilityGate)+ }++ guard document.entryCount == document.payload.entries.count else {+ throw BackupCodecError.countMismatch(+ field: "entryCount",+ expected: document.entryCount,+ actual: document.payload.entries.count+ )+ }+ guard document.workCount == document.payload.works.count else {+ throw BackupCodecError.countMismatch(+ field: "workCount",+ expected: document.workCount,+ actual: document.payload.works.count+ )+ }++ // Verify checksum: re-encode payload with the same settings.+ let payloadData = try BackupCanonicalJSON.encoder().encode(document.payload)+ let computedChecksum = BackupCanonicalJSON.sha256Hex(payloadData)+ guard document.checksum == computedChecksum else {+ throw BackupCodecError.checksumMismatch(+ expected: document.checksum,+ actual: computedChecksum+ )+ }++ try BackupV17ReferenceValidator.validate(payload: document.payload)++ return document+ } catch let error as BackupCodecError { throw error }+ catch {+ throw BackupCodecError.decodingFailed(reason: String(describing: error))+ }+ }+}++// MARK: - V16 Metadata++public struct BackupV17Metadata: Sendable {+ public let appBuild: String+ public let exportedAt: Date++ public init(appBuild: String, exportedAt: Date) {+ self.appBuild = appBuild+ self.exportedAt = exportedAt+ }+}++// MARK: - Shape Validator++/// Root-strict shape validation: the envelope root must carry exactly the+/// required keys; deeper shape is enforced by typed decoding and the reference+/// validator.+///+/// The keys come from `DuplicateJSONKeyValidator`'s walk rather than from a+/// `JSONSerialization` object graph over the whole document — over a covered+/// library that graph was the payload materialised a second time to read nine+/// keys off the top of it. `decode` must keep running that validator first,+/// which it does: this takes what it returned.+internal enum BackupArchiveShapeValidator {+ static func validate(rootKeys: Set<String>?) throws {+ guard let root = rootKeys else {+ throw BackupCodecError.invalidValue(key: "$", reason: "expected object")+ }+ let required: Set<String> = [+ "backupFormatVersion", "databaseSchemaVersion", "appBuild",+ "exportedAt", "capabilityGate", "entryCount", "workCount",+ "checksum", "payload",+ ]+ if let unknown = root.subtracting(required).sorted().first {+ throw BackupCodecError.unknownKey("$.\(unknown)")+ }+ if let missing = required.subtracting(root).sorted().first {+ throw BackupCodecError.missingKey("$.\(missing)")+ }+ }+}++// MARK: - V16 Reference Validator++/// The shared record checks, the type-list rules, the two character arrays and+/// the two place arrays.+///+/// **What it deliberately does not check.** A fact's `sourceEntryID` and a fact+/// suppression's are exempt (`character-extraction` Decision 2): a citation+/// whose entry the reader deleted — or whose entry has not synced — is a+/// tolerated state, not corruption, and refusing here would fail a whole backup+/// over routine curation.+///+/// What it does refuse is a payload contradicting itself: two records for one+/// 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 BackupV17ReferenceValidator {+ static func validate(payload: BackupV17Payload) throws {+ do { _ = try NoEpisodeHistory(payload.noEpisodeActions.map { try $0.action() }) }+ catch {+ throw BackupCodecError.invalidStateTuple(+ type: "NoEpisodeAction", id: BackupV17Codec.label,+ reason: String(describing: error))+ }+ do {+ try BackupArchiveReferenceChecks.validate(+ entries: payload.entries,+ works: payload.works,+ memberships: payload.memberships,+ distinctPairs: payload.distinctPairs,+ sites: payload.sites,+ titlePatterns: payload.titlePatterns,+ urlRules: payload.urlRules,+ series: payload.series,+ links: payload.links,+ creators: payload.creators,+ creatorRoles: payload.creatorRoles,+ credits: payload.credits,+ formatLabel: BackupV17Codec.label)+ } catch let issue as BackupArchiveReferenceIssue {+ throw BackupCodecError(issue)+ }++ let typeIDs = Set(payload.workTypes.map(\.id))+ guard typeIDs.count == payload.workTypes.count else {+ throw BackupCodecError.invalidStateTuple(+ type: "Payload", id: BackupV17Codec.label, reason: "duplicate work type ID")+ }++ let workIDs = Set(payload.works.map(\.id))++ var characterIDs: Set<UUID> = []+ for character in payload.characters {+ guard characterIDs.insert(character.id).inserted else {+ throw BackupCodecError.invalidStateTuple(+ type: "Payload", id: BackupV17Codec.label, reason: "duplicate Character ID")+ }+ if let workID = character.workID, !workIDs.contains(workID) {+ throw BackupCodecError.unresolvedReference(+ type: "Character", id: character.id.uuidString, reference: "Work \(workID)")+ }+ }++ var suppressionIDs: Set<UUID> = []+ for suppression in payload.suppressions {+ guard suppressionIDs.insert(suppression.id).inserted else {+ throw BackupCodecError.invalidStateTuple(+ type: "Payload", id: BackupV17Codec.label, reason: "duplicate CharacterSuppression ID")+ }+ if let workID = suppression.workID, !workIDs.contains(workID) {+ throw BackupCodecError.unresolvedReference(+ type: "CharacterSuppression", id: suppression.id.uuidString,+ reference: "Work \(workID)")+ }+ }++ // The places, on the **contradiction** half of the rule only+ // (`place-extraction` Req 5.1, 5.5). Two records for one identity is a+ // payload disagreeing with itself, exactly as it is for a character. An+ // unresolvable `workID` is not: a place names its owner in a column, so+ // an owner that has not arrived is the tolerated orphan rather than a+ // dangling relationship, and refusing here would decline a backup over a+ // state every screen in the app already shows (Q60).+ var placeIDs: Set<UUID> = []+ for place in payload.places {+ guard placeIDs.insert(place.id).inserted else {+ throw BackupCodecError.invalidStateTuple(+ type: "Payload", id: BackupV17Codec.label, reason: "duplicate Place ID")+ }+ }++ var placeSuppressionIDs: Set<UUID> = []+ for suppression in payload.placeSuppressions {+ guard placeSuppressionIDs.insert(suppression.id).inserted else {+ throw BackupCodecError.invalidStateTuple(+ type: "Payload", id: BackupV17Codec.label,+ reason: "duplicate PlaceSuppression ID")+ }+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV17Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV17Exporter.swiftnew file mode 100644index 00000000..b8bf804a--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV17Exporter.swift@@ -0,0 +1,481 @@+import Foundation+import SwiftData++// MARK: - Snapshot Providing++/// Provides one coherent 16/17 payload under a shared lock. Isolated from+/// persistence so export can be unit-tested with injected snapshots.+public protocol BackupV17SnapshotProviding: Sendable {+ func backupV17Snapshot() async throws -> BackupV17Payload+}++// MARK: - Export Errors++/// The export's refusals — the three states a backup can decline over, and the+/// three ways the machinery around it can fail.+///+/// One enum, not one per generation. It used to be three, each restating the+/// same six cases and each carrying an initializer that renamed another+/// generation's finding into its own. The distinctions a reader is shown are all+/// here — what is gone is the per-generation prefix, which said nothing the+/// detected format pair does not already say.+///+/// `tornGroups` covers a **character** group whose rows disagree about something+/// 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 BackupV17ExportError: 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+ /// loss inside a backup.+ case tornGroups(TornGroupsPayload)+ /// A record holds a stored value the wire format cannot represent —+ /// typically an enum raw value a newer app version wrote and synced down, or+ /// a Codable blob it cannot decode. Omitting the record is silent data loss;+ /// representing the value is a format change. So the record and the value+ /// are named and the export refuses.+ case unrepresentableValue(record: String, field: String, value: String)+ /// A record cites a rule no row in the library holds, or a hostname whose+ /// projected tuple the format has no case for. Transient by nature: the+ /// missing row is en route.+ case referencesStillArriving(detail: String)++ case snapshotFailed(reason: String)+ case encodingFailed(reason: String)+ case stagingFailed(reason: String)++ /// The one `field` value whose refusal carries its own remedy+ /// (`work-thumbnails` Req 8.3). Named here rather than spelled twice, so the+ /// thrower and the message cannot drift apart.+ public static let thumbnailField = "thumbnail"++ public var description: String {+ switch self {+ case .tornGroups(let payload):+ payload.count == 1+ ? "Backup export refused: 1 record exists in differing copies, and a "+ + "backup cannot hold both"+ : "Backup export refused: \(payload.count) records exist in differing "+ + "copies, and a backup cannot hold them all"+ case .unrepresentableValue(let record, let field, let value)+ where field == Self.thumbnailField:+ // `work-thumbnails` Req 8.3. The generic tail below tells the reader+ // a newer version wrote the value, which is true but useless: there+ // is nothing they can do about a status raw. A cover they *can* do+ // something about, and the whole point of refusing rather than+ // dropping it is that they get to choose, so the message says how.+ "Backup export refused: \(record) holds a cover this backup cannot carry "+ + "(\(value)). 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 export"+ case .unrepresentableValue(let record, let field, let value):+ "Backup export refused: \(record) holds \(field) '\(value)', which this "+ + "backup format cannot represent — it was probably written by a newer "+ + "version of Asterism"+ case .referencesStillArriving(let detail):+ "Backup export refused: records are still arriving from iCloud (\(detail)). "+ + "Try again once syncing has settled"+ case .snapshotFailed(let reason): "Backup snapshot failed: \(reason)"+ case .encodingFailed(let reason): "Backup encoding failed: \(reason)"+ case .stagingFailed(let reason): "Backup staging failed: \(reason)"+ }+ }+}++// MARK: - LibraryRepository Snapshot++extension LibraryRepository: BackupV17SnapshotProviding {+ /// 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+ /// most wanted: an ordinary sync quarantines a hostname or leaves 2,995 of+ /// 3,000 records holding an unresolved Site reference, and the backup tool+ /// then declined. What made removing them possible is `SiteUnionProjection`+ /// — duplicate rows project to one wire Site, rowless hostnames to a+ /// synthesised untaught one, and nil-site rules attach through their citers.+ ///+ /// Three refusals remain, each named: a torn identity group (3.3), a stored+ /// value the format cannot represent (3.6), and citations that do not+ /// resolve (3.7).+ ///+ /// Export never writes. The projection is computed read-side precisely so a+ /// 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 backupV17Snapshot() async throws -> BackupV17Payload {+ let outcome: Result<BackupV17Payload, BackupV17ExportError> =+ try await withLockedBackupContext { context in+ do { return .success(try Self.projectV17Payload(context: context)) }+ catch let error as BackupV17ExportError { return .failure(error) }+ }+ return try outcome.get()+ }++ /// 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+ /// every character and every membership whole (Q17, Q78 — never+ /// works→children, so a sync orphan exports naming its Work instead of+ /// 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 projectV17Payload(context: ModelContext) throws -> BackupV17Payload {+ let common = try projectCommonArchiveRecords(context: context)++ // Req 7.2 and Q32: the **folded** list, one record per identity. Rows+ // sharing a UUID are a normal permanent state in the live store — the+ // strict duplicate arm applies to materialized archives, which is what+ // this fold produces. `identities` is ordered by identifier, so two+ // devices holding the same rows write the same bytes.+ let directory = common.groups.types+ let workTypes = directory.identities.map {+ BackupV17WorkType(+ 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 mapV17WorkRecord(+ $0, canonicalWorkIDs: common.groups.canonicalWorkIDs, types: directory)+ }++ // Req 3.7: the archive's own reference validator refuses a citation that+ // does not resolve, and the import gates refuse such a file. Discovering+ // that inside export's verify-decode would surface a library-shape+ // problem as a codec error, so it is named here instead.+ try requireCitationsResolve(+ entries: common.entries,+ memberships: common.memberships,+ titlePatterns: common.titlePatterns,+ urlRules: common.urlRules)++ let characters = common.groups.characters.map(mapV17CharacterRecord)++ let suppressions = try context.fetch(FetchDescriptor<CharacterSuppression>())+ .map(mapV17SuppressionRecord)+ .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(mapV17PlaceRecord)++ let placeSuppressions = try context.fetch(FetchDescriptor<PlaceSuppression>())+ .map(mapV17PlaceSuppressionRecord)+ .sorted { $0.id.uuidString < $1.id.uuidString }++ // `work-creators` Req 9.1: the two directories folded, one record per+ // identity, carrying the per-field timestamps the fold reads (Q50) —+ // the work-type rule above with the field history the credits' own+ // convergence needs. Built here rather than in the common projection+ // because no other generation's records want them.+ //+ // Elected before they are projected (Req 9.2, Q71): a library caught+ // between a rename and the reconcile pass that answers for it holds two+ // records spelled the same, which is a file the archive's own reference+ // checks refuse. The election is `CreatorReconciler`'s, read-only.+ let creators = electedCreators(try creatorDirectory(context: context))+ let creatorRoles = electedCreatorRoles(try creatorRoleDirectory(context: context))++ return BackupV17Payload(+ entries: common.entries,+ works: works,+ sites: common.sites,+ titlePatterns: common.titlePatterns,+ urlRules: common.urlRules,+ workTypes: workTypes,+ memberships: common.memberships,+ distinctPairs: try projectDistinctPairs(context: context),+ characters: characters,+ suppressions: suppressions,+ places: places,+ placeSuppressions: placeSuppressions,+ // `series-and-related-works` Req 13.1 and 13.2: the series table+ // whole, and one link per pair — the row the next reconcile would+ // keep, so an archive never carries a row that pass deletes.+ series: try projectSeries(context: context),+ links: try projectLinks(context: context),+ creators: mapV17CreatorRecords(creators),+ creatorRoles: mapV17CreatorRoleRecords(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.+ credits: try projectCredits(context: context, creators: creators),+ noEpisodeActions: try NoEpisodeIndex(context: context).allActions.map(+ BackupV17NoEpisodeAction.init))+ }++ /// The creator directory as the next convergence pass would leave it: every+ /// set of visible identities sharing a normalized name collapsed to its+ /// survivor, the rest marked merged into it (Req 9.2, Q71).+ ///+ /// The collision sets and the survivor order are `CreatorReconciler`'s own,+ /// called read-only, so there is one spelling of Req 10.3's election rather+ /// than a second one written for export. What is *not* projected is the+ /// survivor's field election and the notes append: neither changes whether+ /// the file is accepted, and the notes append reads a clock an export does+ /// not have. The result is a fixed point either way — the loser arrives+ /// merged, so the importing device's own pass finds nothing left to elect.+ ///+ /// A converged library has no collisions and the directory is returned+ /// untouched, which is the ordinary case.+ private static func electedCreators(_ directory: CreatorDirectory) -> CreatorDirectory {+ var merges: [UUID: UUID] = [:]+ for colliding in CreatorReconciler.collisions(+ directory.identities, normalizedName: \.normalizedName, isMerged: \.isMerged+ ) {+ guard let survivor = colliding.first else { continue }+ for loser in colliding.dropFirst() { merges[loser.id] = survivor.id }+ }+ guard !merges.isEmpty else { return directory }+ return CreatorDirectory(+ rows: directory.identities.map { identity in+ CreatorDirectory.Row(+ id: identity.id, name: identity.name,+ nameModifiedAt: identity.nameModifiedAt,+ notes: identity.notes, notesModifiedAt: identity.notesModifiedAt,+ stateRaw: merges[identity.id] == nil+ ? identity.state.rawValue : CreatorState.merged.rawValue,+ stateModifiedAt: identity.stateModifiedAt,+ canonicalID: merges[identity.id] ?? identity.canonicalID,+ createdAt: identity.createdAt)+ })+ }++ /// `electedCreators` over the role table, where active and removed records+ /// share one name space (Req 9.5).+ private static func electedCreatorRoles(+ _ directory: CreatorRoleDirectory+ ) -> CreatorRoleDirectory {+ var merges: [UUID: UUID] = [:]+ for colliding in CreatorReconciler.collisions(+ directory.identities, normalizedName: \.normalizedName, isMerged: \.isMerged+ ) {+ guard let survivor = colliding.first else { continue }+ for loser in colliding.dropFirst() { merges[loser.id] = survivor.id }+ }+ guard !merges.isEmpty else { return directory }+ return CreatorRoleDirectory(+ rows: directory.identities.map { identity in+ CreatorRoleDirectory.Row(+ id: identity.id, name: identity.name,+ nameModifiedAt: identity.nameModifiedAt,+ position: identity.position,+ positionModifiedAt: identity.positionModifiedAt,+ stateRaw: merges[identity.id] == nil+ ? identity.state.rawValue : CreatorRoleState.merged.rawValue,+ stateModifiedAt: identity.stateModifiedAt,+ canonicalID: merges[identity.id] ?? identity.canonicalID,+ createdAt: identity.createdAt)+ })+ }++ /// The creator table as records: every folded identity, merged ones pointing+ /// at their **final** survivor (Req 9.1, Q33).+ ///+ /// A merged identity whose chain does not end at a record this archive+ /// carries — the survivor has not synced, or the chain is a cycle — is+ /// written with **no** survivor rather than with the pointer it stores+ /// (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 mapV17CreatorRecords(+ _ directory: CreatorDirectory+ ) -> [BackupV17Creator] {+ directory.identities.map { identity in+ BackupV17Creator(+ id: identity.id, name: identity.name,+ nameModifiedAt: identity.nameModifiedAt,+ notes: identity.notes, notesModifiedAt: identity.notesModifiedAt,+ stateRaw: identity.state.rawValue,+ stateModifiedAt: identity.stateModifiedAt,+ canonicalID: identity.state == .merged+ ? finalSurvivor(of: identity.id, in: directory) : nil,+ createdAt: identity.createdAt, modifiedAt: identity.modifiedAt)+ }+ }++ private static func mapV17CreatorRoleRecords(+ _ directory: CreatorRoleDirectory+ ) -> [BackupV17CreatorRole] {+ directory.identities.map { identity in+ BackupV17CreatorRole(+ id: identity.id, name: identity.name,+ nameModifiedAt: identity.nameModifiedAt,+ position: identity.position,+ positionModifiedAt: identity.positionModifiedAt,+ stateRaw: identity.state.rawValue,+ stateModifiedAt: identity.stateModifiedAt,+ canonicalID: identity.state == .merged+ ? finalSurvivor(of: identity.id, in: directory) : nil,+ createdAt: identity.createdAt, modifiedAt: identity.modifiedAt)+ }+ }++ /// The end of a merged record's alias chain, or `nil` where the chase does+ /// not reach a record that answers for it. The directories' own `resolve`+ /// does the walking, so the archive and every screen agree about which+ /// record a credit reads as.+ private static func finalSurvivor(of id: UUID, in directory: CreatorDirectory) -> UUID? {+ guard let survivor = directory.resolve(id), survivor.id != id,+ survivor.state != .merged+ else { return nil }+ return survivor.id+ }++ private static func finalSurvivor(+ of id: UUID, in directory: CreatorRoleDirectory+ ) -> UUID? {+ guard let survivor = directory.resolve(id), survivor.id != id,+ survivor.state != .merged+ else { return nil }+ return survivor.id+ }++ /// 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 mapV17CharacterRecord(_ group: CharacterGroup) -> BackupV17Character {+ let content = group.presentedContent+ return BackupV17Character(+ id: group.id,+ workID: group.carrier.ownerWorkID,+ name: content.name,+ nameKey: group.carrier.nameKey,+ aliases: content.aliases,+ note: content.note,+ facts: content.facts,+ createdAt: group.createdAt,+ modifiedAt: group.modifiedAt)+ }++ /// 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 mapV17SuppressionRecord(+ _ row: CharacterSuppression+ ) -> BackupV17Suppression {+ BackupV17Suppression(+ 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)+ }++ /// `mapV17CharacterRecord` 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: `BackupV17Place.workID` is a+ /// `UUID` and `BackupV17Character.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 mapV17PlaceRecord(_ group: RecordGroup<Place>) -> BackupV17Place {+ let content = group.presentedContent+ return BackupV17Place(+ id: group.id,+ workID: group.carrier.workID,+ name: content.name,+ nameKey: group.carrier.nameKey,+ aliases: content.aliases,+ note: content.note,+ facts: content.facts,+ createdAt: group.createdAt,+ modifiedAt: group.modifiedAt)+ }++ /// One-for-one, duplicates included, for `mapV17SuppressionRecord`'s reason.+ private static func mapV17PlaceSuppressionRecord(+ _ row: PlaceSuppression+ ) -> BackupV17PlaceSuppression {+ BackupV17PlaceSuppression(+ 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)+ }+}++// MARK: - The Exporter++/// 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 16/17 document.+public final class BackupV17Exporter: Sendable {+ private let repository: any BackupV17SnapshotProviding+ private let stagingDirectory: URL++ public init(+ repository: any BackupV17SnapshotProviding,+ stagingDirectory: URL+ ) {+ self.repository = repository+ self.stagingDirectory = stagingDirectory+ }++ public func export(metadata: BackupV17Metadata) async throws -> BackupExportResult {+ let payload: BackupV17Payload+ do {+ payload = try await repository.backupV17Snapshot()+ } catch let error as BackupV17ExportError {+ throw error+ } catch {+ throw BackupV17ExportError.snapshotFailed(reason: String(describing: error))+ }++ let encoded: Data+ do {+ encoded = try BackupV17Codec.encode(payload: payload, metadata: metadata)+ } catch {+ throw BackupV17ExportError.encodingFailed(reason: String(describing: error))+ }++ do {+ let decoded = try BackupV17Codec.decode(encoded)+ guard decoded.payload == payload else {+ throw BackupV17ExportError.encodingFailed(reason: "decode-validation payload mismatch")+ }+ } catch let error as BackupV17ExportError {+ throw error+ } catch {+ throw BackupV17ExportError.encodingFailed(reason: "decode-validation failed: \(error)")+ }++ do {+ try FileManager.default.createDirectory(+ at: stagingDirectory, withIntermediateDirectories: true)+ let fileURL = stagingDirectory.appending(+ path: ExportStaging.backupFilename(+ version: "v\(BackupV17Document.formatVersion)",+ exportedAt: metadata.exportedAt))+ do {+ try ExportStaging.write(encoded, to: fileURL)+ } catch {+ throw BackupV17ExportError.stagingFailed(reason: String(describing: error))+ }+ return BackupExportResult(fileURL: fileURL)+ } catch let error as BackupV17ExportError {+ throw error+ } catch {+ throw BackupV17ExportError.stagingFailed(+ reason: "preparing staging directory failed: \(error)")+ }+ }++ public func cleanup(_ result: BackupExportResult) {+ try? FileManager.default.removeItem(at: result.fileURL)+ }++ /// Removes abandoned backup files older than 24 hours from the staging area,+ /// which still covers the files a previous build staged at an earlier+ /// generation.+ public func scavengeStaleFiles() {+ ExportStaging.scavengeBackups(in: stagingDirectory)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV17Types.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV17Types.swiftnew file mode 100644index 00000000..2b262194--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV17Types.swift@@ -0,0 +1,1075 @@+import Foundation++// MARK: - Backup V17 Document++/// The 17/18 backup envelope: format version 17 over live schema version 18.+/// The schema number names the store schema the archive was taken from.+///+/// It replaces the 16/17 importer outright. An older archive has no+/// no-episode action history, so this build refuses it before a library write.+///+/// The schema number is **pinned to the live schema by a test**+/// (`BackupV17ArchiveTests.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 BackupV17Document: Codable, Equatable, Sendable {+ public static let formatVersion = 17+ public static let schemaVersion = 18++ public let backupFormatVersion: Int+ public let databaseSchemaVersion: Int+ public let appBuild: String+ public let exportedAt: Date+ public let capabilityGate: String+ public let entryCount: Int+ public let workCount: Int+ public let checksum: String+ public let payload: BackupV17Payload++ public init(+ appBuild: String,+ exportedAt: Date,+ capabilityGate: String,+ entryCount: Int,+ workCount: Int,+ checksum: String,+ payload: BackupV17Payload+ ) {+ backupFormatVersion = Self.formatVersion+ databaseSchemaVersion = Self.schemaVersion+ self.appBuild = appBuild+ self.exportedAt = exportedAt+ self.capabilityGate = capabilityGate+ self.entryCount = entryCount+ self.workCount = workCount+ self.checksum = checksum+ self.payload = payload+ }+}++// MARK: - V16 Payload++/// 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,+/// a Work naming its Entries and a coverage table keyed by the record it+/// described; each of the three was a second spelling of a relationship the+/// child already states, and each could disagree with it. Memberships and+/// 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 BackupV17Payload: Codable, Equatable, Sendable {+ public let entries: [BackupV17Entry]+ public let works: [BackupV17Work]+ public let sites: [BackupV17Site]+ public let titlePatterns: [BackupV17TitlePattern]+ public let urlRules: [BackupV17URLRule]+ public let workTypes: [BackupV17WorkType]+ /// One row per Work and hostname (Req 9.1). The Work's site presence lives+ /// here and nowhere else.+ public let memberships: [BackupV17Membership]+ /// The reader's "not the same work" over an unordered pair (Req 5.5).+ public let distinctPairs: [BackupV17DistinctPair]+ public let characters: [BackupV17Character]+ public let suppressions: [BackupV17Suppression]+ /// 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: [BackupV17Place]+ /// 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: [BackupV17PlaceSuppression]+ /// 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: [BackupV17Series]+ /// 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: [BackupV17Link]+ /// The reader's creators, one record per folded identity+ /// (`work-creators` Req 9.1).+ public let creators: [BackupV17Creator]+ /// The reader's role list, one record per folded identity, carrying the+ /// list order every credit is read in.+ public let creatorRoles: [BackupV17CreatorRole]+ /// 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: [BackupV17Credit]+ /// Full remove-wins history, including clears and dangling work references.+ public let noEpisodeActions: [BackupV17NoEpisodeAction]++ public init(+ entries: [BackupV17Entry],+ works: [BackupV17Work],+ sites: [BackupV17Site],+ titlePatterns: [BackupV17TitlePattern],+ urlRules: [BackupV17URLRule],+ workTypes: [BackupV17WorkType] = [],+ memberships: [BackupV17Membership] = [],+ distinctPairs: [BackupV17DistinctPair] = [],+ characters: [BackupV17Character] = [],+ suppressions: [BackupV17Suppression] = [],+ places: [BackupV17Place] = [],+ placeSuppressions: [BackupV17PlaceSuppression] = [],+ series: [BackupV17Series] = [],+ links: [BackupV17Link] = [],+ creators: [BackupV17Creator] = [],+ creatorRoles: [BackupV17CreatorRole] = [],+ credits: [BackupV17Credit] = [],+ noEpisodeActions: [BackupV17NoEpisodeAction] = []+ ) {+ self.entries = entries+ self.works = works+ self.sites = sites+ self.titlePatterns = titlePatterns+ self.urlRules = urlRules+ self.workTypes = workTypes+ self.memberships = memberships+ self.distinctPairs = distinctPairs+ self.characters = characters+ self.suppressions = suppressions+ self.places = places+ self.placeSuppressions = placeSuppressions+ self.series = series+ self.links = links+ self.creators = creators+ self.creatorRoles = creatorRoles+ self.credits = credits+ self.noEpisodeActions = noEpisodeActions+ }+}++public struct BackupV17NoEpisodeAction: Codable, Equatable, Sendable {+ public let workID: UUID+ public let key: String+ public let payloadData: Data++ public init(workID: UUID, key: String, payloadData: Data) {+ self.workID = workID+ self.key = key+ self.payloadData = payloadData+ }++ public init(_ action: NoEpisodeHistory.Action) throws {+ self.init(workID: action.workID, key: action.key, payloadData: try action.canonicalData())+ }++ public func action() throws -> NoEpisodeHistory.Action {+ let value = try NoEpisodeHistory.Action.decode(payloadData, workID: workID)+ guard key == value.key, try value.canonicalData() == payloadData else {+ throw NoEpisodeHistory.HistoryError.invalidPayload+ }+ return value+ }+}++// 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 → 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.+///+/// `mode` stays the **typed** `SiteMode` rather than its raw string: a spelling+/// 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 BackupV17Site: Codable, Equatable, Sendable {+ public let hostname: String+ public let displayName: String+ public let mode: SiteMode++ public init(+ hostname: String,+ displayName: String,+ mode: SiteMode+ ) {+ self.hostname = hostname+ self.displayName = displayName+ self.mode = mode+ }+}++/// 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 BackupV17TitlePattern: Codable, Equatable, Sendable {+ public let id: UUID+ public let siteHostname: String+ public let version: Int+ public let isActive: Bool+ public let createdAt: Date+ public let definition: StoredPatternDefinition++ public init(+ id: UUID,+ siteHostname: String,+ version: Int,+ isActive: Bool,+ createdAt: Date,+ definition: StoredPatternDefinition+ ) {+ self.id = id+ self.siteHostname = siteHostname+ self.version = version+ self.isActive = isActive+ self.createdAt = createdAt+ self.definition = definition+ }+}++/// 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 BackupV17URLRule: Codable, Equatable, Sendable {+ public let id: UUID+ public let version: Int+ public let isCurrent: Bool+ public let createdAt: Date+ public let origin: URLRuleOrigin+ public let definition: URLRuleDefinition+ public let siteHostname: String++ public init(+ id: UUID,+ version: Int,+ isCurrent: Bool,+ createdAt: Date,+ origin: URLRuleOrigin,+ definition: URLRuleDefinition,+ siteHostname: String+ ) {+ self.id = id+ self.version = version+ self.isCurrent = isCurrent+ self.createdAt = createdAt+ self.origin = origin+ self.definition = definition+ self.siteHostname = siteHostname+ }+}++/// One entry of the configured type list, as the exporter's fold produced it.+///+/// **One record per identity** (`configurable-work-types` Q32). Duplicate rows of+/// 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 BackupV17WorkType: Codable, Equatable, Sendable {+ public let id: UUID+ public let name: String+ /// `active` / `removed` / `merged`, carried raw so an archive written by a+ /// later build's wider state set decodes here rather than refusing.+ public let stateRaw: String+ public let canonicalID: UUID?+ public let createdAt: Date+ public let modifiedAt: Date++ public init(+ id: UUID,+ name: String,+ stateRaw: String,+ canonicalID: UUID?,+ createdAt: Date,+ modifiedAt: Date+ ) {+ self.id = id+ self.name = name+ self.stateRaw = stateRaw+ self.canonicalID = canonicalID+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// One Work, with **no site of its own** (Req 9.1).+///+/// The hostname, URL identity, identity state, cited rule and confirmed Work URL+/// the 6/7 record carried are the membership's now, one row per site. `entryIDs`+/// is gone with the other child lists (Req 9.3), and `legacyType` with the+/// column only it carried — a Work typed by a legacy `typeRaw` is untyped from+/// V8 on (Req 10.3, Q16).+///+/// `genericNotesExtractionFingerprint` rides here rather than in a coverage+/// table (Req 9.4): it describes this record's own `genericNotes`, and a+/// separate table keyed by Work id was a second place for the same fact.+///+/// **11/12 adds the three status fields** (`work-and-reading-status` Req 8.1):+/// the two statuses travel as the typed enums, exactly as `titleProvenance`+/// does, and the verdict as the reader's text. All three are **required** —+/// there is no `decodeIfPresent` and no default (Q34). The only archive this+/// 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 BackupV17Work: Codable, Equatable, Sendable {+ public let id: UUID+ public let displayTitle: String+ public let lastParsedTitle: String?+ public let genericNotes: String+ public let genreTags: [String]+ public let titleProvenance: TitleProvenance+ /// Whether the work itself is still being published (Req 1.1).+ public let workStatus: WorkStatus+ /// Where the reader is with it (Req 2.1).+ public let readingStatus: ReadingStatus+ /// 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 `BackupV17WorkType`, 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?+ /// The resolved display name at export time, nil when the Work is untyped or+ /// its type is unresolved. It is what lets a *cross-library* import display+ /// and re-mint a type whose entry the archive could not carry.+ public let typeName: String?+ public let createdAt: Date+ public let modifiedAt: Date+ /// The fingerprint of the `genericNotes` text a character-extraction pass+ /// last covered, or nil.+ public let genericNotesExtractionFingerprint: String?+ /// **11/12 adds the membership pair** (`series-and-related-works` Req 13.1).+ /// It rides on the work record because that is where it lives in the store:+ /// a membership is part of the work's own content and travels with the work+ /// wherever the work goes.+ ///+ /// Both optional and **both or neither**: `requireRepresentableValues`+ /// refuses a half-set row at export and the reference checks refuse one at+ /// import (Req 13.5), so nothing downstream has to answer what half a+ /// membership means. `seriesID` may name a series the archive does not+ /// carry — that imports unresolved and is tolerated (Req 11.2), exactly as a+ /// dangling `workTypeID` is.+ public let seriesID: UUID?+ /// Finite, and carrying at most one fraction digit (Q15). Refused at both+ /// doors otherwise.+ public let seriesPosition: Double?+ /// **12/13 → 13/14 adds the cover** (`work-thumbnails` Req 8.1): the shape's+ /// raw spelling and the bytes, and deliberately **not** the digest.+ ///+ /// The digest is derived from the bytes alone (Req 1.10), so archiving it+ /// would put a second copy of one fact in the file and invite the two to+ /// disagree; import re-derives it, which is also what heals a row whose+ /// stored digest never matched its blob (Req 1.8).+ ///+ /// The raw spelling travels rather than the enum, as `stateRaw` does above:+ /// reading is tolerant and writing is not, so a cover a newer build cropped+ /// keeps its own spelling in the file — but the *export* still refuses one+ /// this build cannot name (Req 8.3), because an unknown raw is the one case+ /// where the reader has an escape and a silent default would record a shape+ /// they never chose.+ public let thumbnailShape: String?+ /// Base64 through `Codable`'s own `Data` encoding (Q5). Absent where the+ /// work has no cover, and absent where the row carries an identity with no+ /// bytes behind it — Req 1.8's tolerated state exports as a work with no+ /// cover rather than making the library unbackupable (Q52).+ public let thumbnail: Data?+ /// **13/14 → 14/15 adds the release days** (`update-schedule` Req 8.1, Q22,+ /// Q36): the weekdays the reader says this work publishes on, in canonical+ /// order, off the carrier row like the rest of a split group's authored+ /// content.+ ///+ /// **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 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,+ displayTitle: String,+ lastParsedTitle: String?,+ genericNotes: String,+ genreTags: [String],+ titleProvenance: TitleProvenance,+ workStatus: WorkStatus,+ readingStatus: ReadingStatus,+ verdict: String,+ // **Required** for the statuses' reason (Q22): the field is required on+ // the wire, and a default here would let an exporter build a record+ // claiming a work has no schedule without ever reading the column.+ releaseDays: [ReleaseDay],+ workTypeID: UUID?,+ typeName: String?,+ createdAt: Date,+ modifiedAt: Date,+ genericNotesExtractionFingerprint: String? = nil,+ seriesID: UUID? = nil,+ seriesPosition: Double? = nil,+ thumbnailShape: String? = 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+ self.genericNotes = genericNotes+ self.genreTags = genreTags+ self.titleProvenance = titleProvenance+ self.workStatus = workStatus+ self.readingStatus = readingStatus+ self.verdict = verdict+ self.workTypeID = workTypeID+ self.typeName = typeName+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ self.genericNotesExtractionFingerprint = genericNotesExtractionFingerprint+ }++ /// The record's type, as the one assignment enum every subsystem takes.+ public var assignment: WorkTypeAssignment {+ workTypeID.map(WorkTypeAssignment.configured) ?? .none+ }+}++/// One series (`series-and-related-works` Req 13.1).+///+/// Five columns and no member list: a work's membership is on the work's own+/// record, which is the same rule that removed every other child list from this+/// 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 BackupV17Series: Codable, Equatable, Sendable {+ public let id: UUID+ /// Stored trimmed and non-empty; an empty trimmed name is refused at the+ /// door (Req 13.5).+ public let name: String+ public let notes: String+ public let createdAt: Date+ /// The import's guard: a series in both keeps the archive's name and notes+ /// only where the record is at least as recent (Req 13.4).+ public let modifiedAt: Date++ public init(id: UUID, name: String, notes: String, createdAt: Date, modifiedAt: Date) {+ self.id = id+ self.name = name+ self.notes = notes+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// One related-work link (`series-and-related-works` Req 13.1).+///+/// `BackupV17DistinctPair`'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 BackupV17Link: Codable, Equatable, Sendable {+ public let id: UUID+ public let lowerWorkID: UUID+ public let higherWorkID: UUID+ public let linkType: String+ public let createdAt: Date+ public let modifiedAt: Date++ public init(+ id: UUID, lowerWorkID: UUID, higherWorkID: UUID, linkType: String,+ createdAt: Date, modifiedAt: Date+ ) {+ self.id = id+ self.lowerWorkID = lowerWorkID+ self.higherWorkID = higherWorkID+ self.linkType = linkType+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }++ /// The record with its two ids in the canonical order, whatever order they+ /// arrived in — `BackupV17DistinctPair.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: BackupV17Link {+ let ids = WorkDistinctPair.sortedIDs(lowerWorkID, higherWorkID)+ guard ids.lower != lowerWorkID || ids.higher != higherWorkID else { return self }+ return BackupV17Link(+ id: id, lowerWorkID: ids.lower, higherWorkID: ids.higher, linkType: linkType,+ createdAt: createdAt, modifiedAt: modifiedAt)+ }+}++/// One creator (`work-creators` Req 9.1).+///+/// **One record per folded identity**, `BackupV17WorkType`'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+/// untouched fields assert against the next sync.+///+/// 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 BackupV17Creator: 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.+ public let name: String+ public let nameModifiedAt: Date+ public let notes: String+ public let notesModifiedAt: Date+ /// `active` / `merged`, carried raw so an archive written by a later build's+ /// wider state set decodes here rather than refusing.+ public let stateRaw: String+ public let stateModifiedAt: Date+ /// The identity this record merged into. Absent where the record is active —+ /// or where the chain it names resolves to nothing this archive carries, a+ /// record that reads as unresolved on every device (Q68).+ public let canonicalID: UUID?+ public let createdAt: Date+ /// The maximum of the three field timestamps, as the store derives it. It is+ /// the list's comparable; the fold reads the field timestamps.+ public let modifiedAt: Date++ public init(+ id: UUID,+ name: String,+ nameModifiedAt: Date,+ notes: String,+ notesModifiedAt: Date,+ stateRaw: String,+ stateModifiedAt: Date,+ canonicalID: UUID?,+ createdAt: Date,+ modifiedAt: Date+ ) {+ self.id = id+ self.name = name+ self.nameModifiedAt = nameModifiedAt+ self.notes = notes+ self.notesModifiedAt = notesModifiedAt+ self.stateRaw = stateRaw+ self.stateModifiedAt = stateModifiedAt+ self.canonicalID = canonicalID+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// One role of the reader's list (`work-creators` Req 9.1).+///+/// `BackupV17Creator`'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 BackupV17CreatorRole: Codable, Equatable, Sendable {+ public let id: UUID+ public let name: String+ public let nameModifiedAt: Date+ /// The reader's list order, and the first key a work's credits sort by.+ public let position: Int+ public let positionModifiedAt: Date+ /// `active` / `removed` / `merged`, raw for the reason the creator's is.+ public let stateRaw: String+ public let stateModifiedAt: Date+ public let canonicalID: UUID?+ public let createdAt: Date+ public let modifiedAt: Date++ public init(+ id: UUID,+ name: String,+ nameModifiedAt: Date,+ position: Int,+ positionModifiedAt: Date,+ stateRaw: String,+ stateModifiedAt: Date,+ canonicalID: UUID?,+ createdAt: Date,+ modifiedAt: Date+ ) {+ self.id = id+ self.name = name+ self.nameModifiedAt = nameModifiedAt+ self.position = position+ self.positionModifiedAt = positionModifiedAt+ self.stateRaw = stateRaw+ self.stateModifiedAt = stateModifiedAt+ self.canonicalID = canonicalID+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// One credit: that one creator worked on one work, in the roles it holds+/// (`work-creators` Req 9.1).+///+/// `BackupV17Link`'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+/// refusal and never dropped.+///+/// `roleIDs` travels **as stored**, every identifier in any state (Q27):+/// archiving only the roles a credit currently *shows* would strip removed ones,+/// 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 BackupV17Credit: Codable, Equatable, Sendable {+ public let id: UUID+ public let workID: UUID+ public let creatorID: UUID+ public let roleIDs: [String]+ public let createdAt: Date+ /// The import's guard (Q67): a record at least as recent as the row wins,+ /// with the tie decided by content so a stale archive cannot narrow a union.+ public let modifiedAt: Date++ public init(+ id: UUID,+ workID: UUID,+ creatorID: UUID,+ roleIDs: [String],+ createdAt: Date,+ modifiedAt: Date+ ) {+ self.id = id+ self.workID = workID+ self.creatorID = creatorID+ self.roleIDs = roleIDs+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }++ /// The record with its role identifiers in the one order a stored set has —+ /// sorted and deduplicated, as every writer leaves them.+ ///+ /// `BackupV17Link.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: BackupV17Credit {+ let roles = WorkCreditSupport.roleIDs(roleIDs)+ guard roles != roleIDs else { return self }+ return BackupV17Credit(+ id: id, workID: workID, creatorID: creatorID, roleIDs: roles,+ createdAt: createdAt, modifiedAt: modifiedAt)+ }+}++/// One Work's presence on one site (Req 9.1), a top-level record naming its Work+/// the way a character does (Q17).+///+/// `workID` is written from the row's own column rather than from its+/// relationship (Q37), so a membership whose Work has not arrived still exports+/// the Work it belongs to and re-attaches when that Work appears. It is optional+/// only because the column is; a row carrying neither is inert.+///+/// The cited rule is a **bare UUID**: a membership names the rule row and+/// carries no rule version (Req 10.4, Q28).+public struct BackupV17Membership: Codable, Equatable, Sendable {+ public let id: UUID+ public let workID: UUID?+ public let hostname: String+ public let createdAt: Date+ public let urlIdentity: String?+ public let urlIdentityState: WorkURLIdentityState+ public let urlIdentityRuleID: UUID?+ public let workURLString: String?++ public init(+ id: UUID,+ workID: UUID?,+ hostname: String,+ createdAt: Date,+ urlIdentity: String?,+ urlIdentityState: WorkURLIdentityState,+ urlIdentityRuleID: UUID?,+ workURLString: String?+ ) {+ self.id = id+ self.workID = workID+ self.hostname = hostname+ self.createdAt = createdAt+ self.urlIdentity = urlIdentity+ self.urlIdentityState = urlIdentityState+ self.urlIdentityRuleID = urlIdentityRuleID+ self.workURLString = workURLString+ }+}++/// One dismissed cross-site duplicate candidate (Req 5.5, 9.1).+///+/// Two UUIDs, sorted, exactly as the store holds them (Q21, Q27): the pair is+/// 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 BackupV17DistinctPair: Codable, Equatable, Sendable {+ public let id: UUID+ public let lowerWorkID: UUID+ public let higherWorkID: UUID+ public let recordedAt: Date++ public init(id: UUID, lowerWorkID: UUID, higherWorkID: UUID, recordedAt: Date) {+ self.id = id+ self.lowerWorkID = lowerWorkID+ self.higherWorkID = higherWorkID+ self.recordedAt = recordedAt+ }++ /// The record with its two ids in the canonical order, whatever order they+ /// arrived in. An unsorted pair is a second spelling of one dismissal, and+ /// `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: BackupV17DistinctPair {+ let ids = WorkDistinctPair.sortedIDs(lowerWorkID, higherWorkID)+ guard ids.lower != lowerWorkID || ids.higher != higherWorkID else { return self }+ return BackupV17DistinctPair(+ id: id, lowerWorkID: ids.lower, higherWorkID: ids.higher, recordedAt: recordedAt)+ }+}++/// One Entry.+///+/// The seventeen citation columns and `identityKeyVersion` are one+/// `EntryCitations` value here (Q25, Q26), exactly as the store holds them: the+/// identity *basis version* is a case rather than an integer, and every citation+/// is one `CitedRule?`.+///+/// **This is what 8/9 changed, and 11/12 keeps.** A `CitedRule` is the rule's+/// UUID and nothing else (T-2281, Req 1.1 of `rule-citation-by-uuid`), so no+/// citation on the wire carries a `version` — and because the codec's checksum+/// is taken over the payload bytes and compared against a re-encoding, a file+/// that does carry one is refused.+///+/// `characterExtractionFingerprint` rides on the record whose `note` it+/// describes (Req 9.4), for the reason the Work's does.+public struct BackupV17Entry: Codable, Equatable, Sendable {+ public let id: UUID+ public let captureTitle: String+ public let captureTitleSource: CaptureTitleSource+ public let rawURL: String+ public let canonicalURL: String?+ public let hostname: String+ public let entryIdentityKey: String+ /// The v1 key alias, always the raw URL (`m4` Q21). Retained after an S-rule+ /// rewrites `entryIdentityKey` so a title-less same-URL re-share still+ /// matches.+ public let conservativeIdentityKey: String+ public let identityBasis: EntryIdentityBasis+ public let urlWorkIdentity: String?+ public let chapterSequence: String?+ public let chapterTitle: String?+ public let note: String+ public let rating: Rating?+ public let firstCapturedAt: Date+ public let lastSharedAt: Date+ public let modifiedAt: Date+ public let workID: UUID?+ public let intentionallyUnattached: Bool+ public let citations: EntryCitations+ public let characterExtractionFingerprint: String?++ public init(+ id: UUID,+ captureTitle: String,+ captureTitleSource: CaptureTitleSource,+ rawURL: String,+ canonicalURL: String?,+ hostname: String,+ entryIdentityKey: String,+ conservativeIdentityKey: String,+ identityBasis: EntryIdentityBasis,+ urlWorkIdentity: String?,+ chapterSequence: String?,+ chapterTitle: String?,+ note: String,+ rating: Rating?,+ firstCapturedAt: Date,+ lastSharedAt: Date,+ modifiedAt: Date,+ workID: UUID?,+ intentionallyUnattached: Bool,+ citations: EntryCitations,+ characterExtractionFingerprint: String? = nil+ ) {+ self.id = id+ self.captureTitle = captureTitle+ self.captureTitleSource = captureTitleSource+ self.rawURL = rawURL+ self.canonicalURL = canonicalURL+ self.hostname = hostname+ self.entryIdentityKey = entryIdentityKey+ self.conservativeIdentityKey = conservativeIdentityKey+ self.identityBasis = identityBasis+ self.urlWorkIdentity = urlWorkIdentity+ self.chapterSequence = chapterSequence+ self.chapterTitle = chapterTitle+ self.note = note+ self.rating = rating+ self.firstCapturedAt = firstCapturedAt+ self.lastSharedAt = lastSharedAt+ self.modifiedAt = modifiedAt+ self.workID = workID+ self.intentionallyUnattached = intentionallyUnattached+ self.citations = citations+ self.characterExtractionFingerprint = characterExtractionFingerprint+ }+}++/// One character, as the archive holds it.+///+/// `facts` carries `RecordFact` itself rather than a wire clone of it: the+/// fact *is* a value type with a stable Codable shape, and a second spelling+/// would be two definitions of one thing with no way to notice them drifting.+///+/// `workID` is optional and checked only when present — a character whose work+/// 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 BackupV17Character: Codable, Equatable, Sendable {+ public let id: UUID+ public let workID: UUID?+ public let name: String+ /// The retained key, minted at accept or creation and never re-derived from+ /// a rename, so it travels rather than being recomputed on the way in.+ public let nameKey: String+ public let aliases: [String]+ public let note: String+ public let facts: [RecordFact]+ public let createdAt: Date+ public let modifiedAt: Date++ public init(+ id: UUID,+ workID: UUID?,+ name: String,+ nameKey: String,+ aliases: [String],+ note: String,+ facts: [RecordFact],+ createdAt: Date,+ modifiedAt: Date+ ) {+ self.id = id+ self.workID = workID+ self.name = name+ self.nameKey = nameKey+ self.aliases = aliases+ self.note = note+ self.facts = facts+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// One suppression row.+///+/// The enum columns travel **raw**, for the reason `BackupV17WorkType`'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 BackupV17Suppression: Codable, Equatable, Sendable {+ public let id: UUID+ public let workID: UUID?+ public let kindRaw: String+ public let nameKey: String+ /// Present on fact rows only. Explicit rather than inferred from a nil+ /// `sourceEntryID`, so a malformed row is distinguishable from a+ /// generic-notes citation.+ public let sourceKindRaw: String?+ public let sourceEntryID: UUID?+ public let evidence: String?+ public let statusRaw: String+ /// When the reader acted — the comparable the import value-guards with.+ public let actionAt: Date++ public init(+ id: UUID,+ workID: UUID?,+ kindRaw: String,+ nameKey: String,+ sourceKindRaw: String?,+ sourceEntryID: UUID?,+ evidence: String?,+ statusRaw: String,+ actionAt: Date+ ) {+ self.id = id+ self.workID = workID+ self.kindRaw = kindRaw+ self.nameKey = nameKey+ self.sourceKindRaw = sourceKindRaw+ self.sourceEntryID = sourceEntryID+ self.evidence = evidence+ self.statusRaw = statusRaw+ self.actionAt = actionAt+ }++ public var kind: CharacterSuppressionKind {+ ToleratedEnum.read(kindRaw, default: .candidate)+ }++ public var status: CharacterSuppressionStatus {+ ToleratedEnum.read(statusRaw, default: .active)+ }++ public var source: SourceRef? {+ SourceRef(kindRaw: sourceKindRaw, entryID: sourceEntryID)+ }+}++/// One place, as the archive holds it (`place-extraction` Req 5.1).+///+/// `BackupV17Character`'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+/// one: a `workID` nothing resolves (Q60, Q67).+///+/// The consequence for the validator is the one asymmetry between the two+/// tables: a character naming a work the file does not carry is a file+/// 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 BackupV17Place: 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.+ public let workID: UUID+ public let name: String+ /// The retained key, minted at accept or creation and never re-derived from+ /// a rename, so it travels rather than being recomputed on the way in.+ public let nameKey: String+ public let aliases: [String]+ public let note: String+ public let facts: [RecordFact]+ public let createdAt: Date+ public let modifiedAt: Date++ public init(+ id: UUID,+ workID: UUID,+ name: String,+ nameKey: String,+ aliases: [String],+ note: String,+ facts: [RecordFact],+ createdAt: Date,+ modifiedAt: Date+ ) {+ self.id = id+ self.workID = workID+ self.name = name+ self.nameKey = nameKey+ self.aliases = aliases+ self.note = note+ self.facts = facts+ self.createdAt = createdAt+ self.modifiedAt = modifiedAt+ }+}++/// One place-suppression row.+///+/// `BackupV17Suppression`'s shape with `BackupV17Place`'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 BackupV17PlaceSuppression: Codable, Equatable, Sendable {+ public let id: UUID+ public let workID: UUID+ public let kindRaw: String+ public let nameKey: String+ /// Present on fact rows only. Explicit rather than inferred from a nil+ /// `sourceEntryID`, so a malformed row is distinguishable from a+ /// generic-notes citation.+ public let sourceKindRaw: String?+ public let sourceEntryID: UUID?+ public let evidence: String?+ public let statusRaw: String+ /// When the reader acted — the comparable the import value-guards with.+ public let actionAt: Date++ public init(+ id: UUID,+ workID: UUID,+ kindRaw: String,+ nameKey: String,+ sourceKindRaw: String?,+ sourceEntryID: UUID?,+ evidence: String?,+ statusRaw: String,+ actionAt: Date+ ) {+ self.id = id+ self.workID = workID+ self.kindRaw = kindRaw+ self.nameKey = nameKey+ self.sourceKindRaw = sourceKindRaw+ self.sourceEntryID = sourceEntryID+ self.evidence = evidence+ self.statusRaw = statusRaw+ self.actionAt = actionAt+ }++ public var kind: CharacterSuppressionKind {+ ToleratedEnum.read(kindRaw, default: .candidate)+ }++ public var status: CharacterSuppressionStatus {+ ToleratedEnum.read(statusRaw, default: .active)+ }++ public var source: SourceRef? {+ SourceRef(kindRaw: sourceKindRaw, entryID: sourceEntryID)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift b/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swiftindex a4399565..08c9fd11 100644--- a/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift@@ -46,7 +46,8 @@ public struct CatchUpProgress: Equatable, Sendable { public static func build( record: CatchUpRecord, notes: [NumberedNote], releaseDays: [ReleaseDay],- workStatus: WorkStatus, day: CivilDay, calendar: Calendar+ noEpisodeDays: Set<CivilDay> = [], workStatus: WorkStatus,+ day: CivilDay, calendar: Calendar ) -> CatchUpProgress { let override: (number: Int, at: Date)? if case .value(let number, let moment) = record.override {@@ -80,7 +81,8 @@ public struct CatchUpProgress: Equatable, Sendable { 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+ of: releaseDays, after: start, through: day,+ noEpisodeDays: noEpisodeDays, calendar: calendar) ?? 0 } let effectiveLatest: Int?@@ -112,21 +114,26 @@ public struct CatchUpProgress: Equatable, Sendable { } public static func build(work: WorkSnapshot, day: CivilDay, calendar: Calendar) -> CatchUpProgress {- build(+ let notedDays = Set(work.entries.map { CivilDay($0.lastSharedAt, calendar: calendar) })+ return build( record: work.catchUp, notes: NumberedNote.from(work.entries),- releaseDays: work.releaseDays, workStatus: work.workStatus,+ releaseDays: work.releaseDays,+ noEpisodeDays: work.noEpisodeHistory.activeDays(for: work.id).subtracting(notedDays),+ workStatus: work.workStatus, day: day, calendar: calendar) } public static func rebased( record: CatchUpRecord, notes: [NumberedNote], releaseDays: [ReleaseDay],- workStatus: WorkStatus, now: Date, calendar: Calendar+ noEpisodeDays: Set<CivilDay> = [], 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)+ noEpisodeDays: noEpisodeDays, workStatus: workStatus,+ day: day, calendar: calendar) guard let effectiveLatest = progress.effectiveLatest else { return nil } return CatchUpRecord( confirmation: CatchUpConfirmation(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swiftindex d1443d39..e1410217 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift@@ -180,6 +180,8 @@ public struct ReconciliationOutcome: Equatable, Sendable { /// a Work's site line shows, so a pass that healed one and touched nothing /// else still has to make the callers refresh. public var memberships = MembershipReconcileReport()+ /// A note-clear action was materialized during this pass.+ public var noEpisodeChanged = false /// Whether the duplicate phase ran at all. False on an arrival-tier pass /// the gate declined (Q53/Q58). public var duplicatePhaseRan = false@@ -190,7 +192,7 @@ public struct ReconciliationOutcome: Equatable, Sendable { public var isEmpty: Bool { site.isEmpty && duplicates.isEmpty && workTypes.isEmpty && creators.isEmpty- && credits.isEmpty && memberships.isEmpty+ && credits.isEmpty && memberships.isEmpty && !noEpisodeChanged } } @@ -212,6 +214,7 @@ enum DuplicateReconciler { struct PassResult { var outcome = DuplicateReconciliationOutcome() var deletions: [DuplicateDeletionPlan] = []+ var noteActionsChanged = false /// The assignment normalisation the deletion phase re-derives its Entry /// fingerprints under, so the two halves of one pass agree about which /// assignments are equal.@@ -237,7 +240,8 @@ enum DuplicateReconciler { batchSize: Int, context: ModelContext, saveStrategy: any RepositorySaveStrategy,- types: WorkTypeDirectory+ types: WorkTypeDirectory,+ noteCalendar: Calendar = .current ) throws -> PassResult { var result = PassResult() // Record keys are retained like every other type's, both kinds. Without@@ -254,14 +258,17 @@ enum DuplicateReconciler { let workPhase = try resolveWorkSets( scan.workSets, ledger: &ledger, batchSize: batchSize,- context: context, saveStrategy: saveStrategy, types: types)+ context: context, saveStrategy: saveStrategy, types: types,+ noteCalendar: noteCalendar) result.outcome.formUnion(workPhase.outcome)+ result.noteActionsChanged = result.noteActionsChanged || workPhase.noteActionsChanged result.deletions += workPhase.deletions let entryPhase = try resolveEntrySets( scan, ledger: &ledger, batchSize: batchSize,- context: context, saveStrategy: saveStrategy)+ context: context, saveStrategy: saveStrategy, noteCalendar: noteCalendar) result.outcome.formUnion(entryPhase.outcome)+ result.noteActionsChanged = result.noteActionsChanged || entryPhase.noteActionsChanged result.deletions += entryPhase.deletions result.canonicalWorkIDs = entryPhase.canonicalWorkIDs @@ -532,7 +539,8 @@ enum DuplicateReconciler { batchSize: Int, context: ModelContext, saveStrategy: any RepositorySaveStrategy,- types: WorkTypeDirectory+ types: WorkTypeDirectory,+ noteCalendar: Calendar ) throws -> PassResult { var result = PassResult() let resolvable = sets.filter { $0.classification == .silentlyResolvable }@@ -580,9 +588,16 @@ enum DuplicateReconciler { // Req 5.2, and Req 2.1's ordering: the Entries move and commit // before anything is deleted, so no interruption can leave an Entry // reachable only through a doomed Work.+ let affectedEntries = set.members.dropFirst()+ .compactMap { rowsByID[$0.id] }.flatMap { $0 }.flatMap { $0.entryValues }+ let beforeNotes = NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar) let moved = repointEntries( from: set.members.dropFirst().compactMap { rowsByID[$0.id] }.flatMap { $0 }, to: survivor)+ result.noteActionsChanged = try NoEpisodeWriter.recordNoteTransition(+ before: beforeNotes,+ after: NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar),+ context: context) || result.noteActionsChanged if moved > 0 { wrote = true } if wrote { result.outcome.contentWrites += 1 }@@ -949,7 +964,8 @@ enum DuplicateReconciler { ledger: inout DuplicateSettlingLedger, batchSize: Int, context: ModelContext,- saveStrategy: any RepositorySaveStrategy+ saveStrategy: any RepositorySaveStrategy,+ noteCalendar: Calendar ) throws -> PassResult { var result = PassResult() let resolvable = scan.entrySets.filter { $0.classification == .silentlyResolvable }@@ -978,6 +994,7 @@ enum DuplicateReconciler { let memberRows = set.key.memberIDs.compactMap { rowsByID[$0] } guard memberRows.count == set.members.count else { continue } let allRows = memberRows.flatMap { $0 }+ let beforeNotes = NoEpisodeWriter.facts(rows: allRows, calendar: noteCalendar) var wrote = false let survivor = GroupOrdering.sortedEntryRows(survivorRows)@@ -1006,6 +1023,10 @@ enum DuplicateReconciler { wrote = true } }+ result.noteActionsChanged = try NoEpisodeWriter.recordNoteTransition(+ before: beforeNotes,+ after: NoEpisodeWriter.facts(rows: allRows, calendar: noteCalendar),+ context: context) || result.noteActionsChanged if wrote { result.outcome.contentWrites += 1 } pending.add(records: allRows.count)@@ -1078,7 +1099,8 @@ enum DuplicateReconciler { _ plans: [DuplicateDeletionPlan], canonicalWorkIDs: [UUID: UUID], context: ModelContext,- saveStrategy: any RepositorySaveStrategy+ saveStrategy: any RepositorySaveStrategy,+ noteCalendar: Calendar = .current ) throws -> [DuplicateSetKey] { guard !plans.isEmpty else { return [] } var rows = try DeletionRows(plans: plans, context: context)@@ -1117,7 +1139,7 @@ enum DuplicateReconciler { plan, rows: &rows, canonicalWorkIDs: canonicalWorkIDs, types: types, distinctPairs: distinctPairs, links: links, creditsByWork: &creditsByWork, creators: creators, placeRows: placeRows, doomedEntries: &doomedEntries,- context: context)+ context: context, noteCalendar: noteCalendar) else { continue } staged.append(plan) }@@ -1153,7 +1175,7 @@ enum DuplicateReconciler { plan, rows: &rows, canonicalWorkIDs: canonicalWorkIDs, types: types, distinctPairs: distinctPairs, links: links, creditsByWork: &creditsByWork, creators: creators, placeRows: replayPlaceRows, doomedEntries: &replayed,- context: context)+ context: context, noteCalendar: noteCalendar) else { continue } delete(entries: replayed, context: context) if try commitDeletion(@@ -1252,7 +1274,8 @@ enum DuplicateReconciler { creators: CreatorDirectory, placeRows: PlaceRepointRows, doomedEntries: inout [Entry],- context: ModelContext+ context: ModelContext,+ noteCalendar: Calendar ) throws -> Bool { switch plan.key.recordType { case .entry:@@ -1275,6 +1298,7 @@ enum DuplicateReconciler { // from synced content like everything else the reconciler writes // (Q56). The rows keep the modification stamp the group already had. let touched = plan.key.memberIDs.flatMap { rows.entries[$0] ?? [] }+ let beforeNotes = NoEpisodeWriter.facts(rows: touched, calendar: noteCalendar) let survivors = Dictionary( uniqueKeysWithValues: plan.loserIDs.map { ($0, plan.survivorID) }) let works = touched.compactMap(\.work)@@ -1289,6 +1313,11 @@ enum DuplicateReconciler { for id in plan.loserIDs { doomedEntries += rows.entries[id] ?? [] }+ let survivingEntries = rows.entries[plan.survivorID] ?? []+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNotes,+ after: NoEpisodeWriter.facts(rows: survivingEntries, calendar: noteCalendar),+ context: context) return true case .work: guard workFingerprint(plan.key.memberIDs, rowsByID: rows.works, types: types)@@ -1303,7 +1332,18 @@ enum DuplicateReconciler { // The move is idempotent: the write phase already did it for // everything it saw. let losers = plan.loserIDs.flatMap { rows.works[$0] ?? [] }+ let affectedEntries = losers.flatMap { $0.entryValues }+ let beforeNotes = NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar) repointEntries(from: losers, to: survivor)+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNotes,+ after: NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar),+ context: context)+ let loserIDs = Set(plan.loserIDs)+ for action in try context.fetch(FetchDescriptor<NoEpisodeAction>())+ where loserIDs.contains(action.workID) {+ action.workID = plan.survivorID+ } carrySeries(from: losers, to: survivor) carryThumbnail(from: losers, to: survivor) carryCatchUp(from: losers, to: survivor)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift b/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swiftindex 1627cd5a..fc42be1b 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- /// `BackupV16Entry`, hand-enumerated nowhere else. With the citations folded+ /// `BackupV17Entry`, 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/IntentAnswers.swift b/Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swiftindex f7fcfce9..6be3afa9 100644--- a/Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swift@@ -57,11 +57,13 @@ public enum IntentAnswers { public static func releasingToday( _ presentation: TodayPresentation, currentDay: CivilDay, calendar: Calendar ) -> [ReleaseAnswer] {- plan(presentation, currentDay: currentDay, calendar: calendar).releases.map { row in- let noted: Bool- if case .notedOnDay = row.line { noted = true } else { noted = false }- return ReleaseAnswer(workID: row.id, title: row.title, notedToday: noted)- }+ plan(presentation, currentDay: currentDay, calendar: calendar).releases+ .filter { $0.releaseState != .noEpisode }+ .map { row in+ let noted: Bool+ if case .notedOnDay = row.line { noted = true } else { noted = false }+ return ReleaseAnswer(workID: row.id, title: row.title, notedToday: noted)+ } } /// The Today plan's noted section for `currentDay`, in order — future-dated
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex 80cb3ef8..303ada39 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift@@ -263,6 +263,10 @@ public protocol LibraryProviding: Sendable { id: UUID, basis: CatchUpRecord, draft: CatchUpDraft ) async throws -> LibraryWriteOutcome + func markNoEpisode(workID: UUID, day: CivilDay, calendar: Calendar) async throws -> LibraryWriteOutcome+ func undoNoEpisode(workID: UUID, day: CivilDay) async throws -> LibraryWriteOutcome+ func prepareNoEpisodeNotes(calendar: Calendar) async throws+ func setReadingStatus( id: UUID, expected: ReadingStatus, to: ReadingStatus ) async throws -> LibraryWriteOutcome@@ -585,6 +589,18 @@ public protocol LibraryProviding: Sendable { } public extension LibraryProviding {+ func markNoEpisode(workID: UUID, day: CivilDay, calendar: Calendar) async throws -> LibraryWriteOutcome {+ throw LibraryRepositoryError.invalidInput(+ operation: "marking no episode", reason: "unavailable in this library")+ }++ func undoNoEpisode(workID: UUID, day: CivilDay) async throws -> LibraryWriteOutcome {+ throw LibraryRepositoryError.invalidInput(+ operation: "undoing no episode", reason: "unavailable in this library")+ }++ func prepareNoEpisodeNotes(calendar: Calendar) async throws {}+ func shutdown() async {} func isBulkOperationInProgress() async -> Bool { false }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swiftindex 7b05ccbe..c310c892 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift@@ -42,6 +42,12 @@ extension LibraryRepository { _ payload: BackupImportPayload, into context: ModelContext ) throws {+ for record in payload.noEpisodeActions {+ let action = try record.action()+ context.insert(NoEpisodeAction(+ workID: action.workID, key: action.key,+ payloadData: try action.canonicalData()))+ } var sitesByHostname: [String: Site] = [:] for record in payload.sites { let site = ArchiveRecordBuilders.makeSite(record)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swiftindex 5cbd8226..58825f80 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.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 117d4bdf..6defb547 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift@@ -2,10 +2,10 @@ import Foundation import OSLog import SwiftData -/// 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+/// Opens the live V18 library after classifying the fixed-path store.+/// The app accepts markers `"16"`, `"17"`, and `"18"`; the extension accepts only `"18"`.+/// V16 and V17 stores migrate through lightweight stages. The app validates+/// before publishing `"18"`, 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@@ -62,6 +62,7 @@ public extension LibraryRepository { capabilities: AsterismCapabilities = .current, clock: any RepositoryClock = SystemRepositoryClock(), saveStrategy: any RepositorySaveStrategy = ModelContextSaveStrategy(),+ noteCalendar: @escaping @Sendable () -> Calendar = { Calendar.current }, mirroring hooks: MirroringOpenHooks = .production ) async throws -> (result: OpeningResult, repository: LibraryRepository) { let fileManager = FileManager.default@@ -91,6 +92,7 @@ public extension LibraryRepository { seedCreatorRoles(in: seedContext) return (certification.result, makeRepository( configuration, container, capabilities, clock, saveStrategy,+ noteCalendar: noteCalendar, quarantined: certification.quarantined, diagnostics: certification.diagnostics, mirroring: attachment)) }@@ -176,7 +178,7 @@ public extension LibraryRepository { let container = try openCertificationContainer(configuration, hooks: hooks) let context = ModelContext(container) bootstrapLogger.debug(- "Marker generation \(generation, privacy: .public) is lagging; certifying the V17 conversion")+ "Marker generation \(generation, privacy: .public) is lagging; certifying the V18 conversion") let diagnostics = try validateStore(context: context) try publishReadiness(at: configuration.readinessMarkerURL) clearResidualEvidence(configuration)@@ -328,7 +330,8 @@ public extension LibraryRepository { _ configuration: LibraryConfiguration, capabilities: AsterismCapabilities = .current, clock: any RepositoryClock = SystemRepositoryClock(),- saveStrategy: any RepositorySaveStrategy = ModelContextSaveStrategy()+ saveStrategy: any RepositorySaveStrategy = ModelContextSaveStrategy(),+ noteCalendar: @escaping @Sendable () -> Calendar = { Calendar.current } ) async throws -> (result: ExtensionResult, repository: LibraryRepository) { let fileManager = FileManager.default @@ -359,6 +362,7 @@ public extension LibraryRepository { let counts = try rowCounts(context: context) return (.ready(counts), makeRepository( configuration, container, capabilities, clock, saveStrategy,+ noteCalendar: noteCalendar, quarantined: diagnostics.quarantineMap(), diagnostics: diagnostics)) } }@@ -384,7 +388,7 @@ extension LibraryRepository { at storeURL: URL, mirroring cloudKitDatabase: ModelConfiguration.CloudKitDatabase = .none ) throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let storeConfiguration = ModelConfiguration( // **Frozen persisted state (Req 3.5).** This names the store // configuration *inside* the container, not the file — `url:` below is@@ -398,7 +402,7 @@ extension LibraryRepository { ) return try ModelContainer( for: schema,- migrationPlan: AsterismV17MigrationPlan.self,+ migrationPlan: AsterismV18MigrationPlan.self, configurations: [storeConfiguration] ) }@@ -547,7 +551,7 @@ extension LibraryRepository { /// convert its store anyway; the recovery is the backup archive, as for any /// unrecognised marker. static let appOpenableMarkerVersions: Set<String> = [- laggingOpenableMarkerVersion, extensionOpenableMarkerVersion,+ laggingOpenableMarkerVersion, "17", extensionOpenableMarkerVersion, ] /// The one lagging generation the app still opens: a library certified by a@@ -560,7 +564,7 @@ extension LibraryRepository { /// installed library (Req 3.5). Both generations the app opens are now /// spelled with two characters, which is why nothing anywhere may assume a /// marker is one character long.- static let extensionOpenableMarkerVersion = "17"+ static let extensionOpenableMarkerVersion = "18" // The app-side counterpart of `validateMarkerContentForExtension` stood // here. It restated the acceptance test the classifier performs, and@@ -636,6 +640,7 @@ extension LibraryRepository { _ capabilities: AsterismCapabilities, _ clock: any RepositoryClock, _ saveStrategy: any RepositorySaveStrategy,+ noteCalendar: @escaping @Sendable () -> Calendar = { Calendar.current }, quarantined: [String: LibraryValidationError] = [:], diagnostics: LibraryDiagnostics = .empty, mirroring: MirroringAttachment = .notRequested@@ -643,6 +648,7 @@ extension LibraryRepository { LibraryRepository( configuration: configuration, container: container, capabilities: capabilities, clock: clock, saveStrategy: saveStrategy,+ noteCalendar: noteCalendar, quarantined: quarantined, diagnostics: diagnostics, mirroring: mirroring) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swiftindex c20ffb16..25efeb6b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift@@ -426,6 +426,8 @@ extension LibraryRepository { } // Apply the update (Req 4.3): only note, rating, lastSharedAt, modifiedAt+ let calendar = noteCalendar()+ let before = Self.noteFacts(group, calendar: calendar) let timestamp = MillisecondInstant.quantize(clock.now()) for row in group.rows { row.note = note@@ -433,6 +435,8 @@ extension LibraryRepository { row.lastSharedAt = timestamp row.modifiedAt = timestamp }+ try NoEpisodeWriter.recordNoteTransition(+ before: before, after: Self.noteFacts(group, calendar: calendar), context: context) // Save (Req 4.11: failure preserves Entry unchanged) do {@@ -502,6 +506,8 @@ extension LibraryRepository { } let timestamp = self.clock.now()+ let calendar = noteCalendar()+ let before = Self.noteFacts(group, calendar: calendar) var wrote = false for row in group.rows where row.lastSharedAt < instant { row.lastSharedAt = instant@@ -513,6 +519,9 @@ extension LibraryRepository { // of an already-newer entry. Both fall out of the rule. guard wrote else { return .committed } + try NoEpisodeWriter.recordNoteTransition(+ before: before, after: Self.noteFacts(group, calendar: calendar), context: context)+ do { try self.saveStrategy.save(context) } catch { // Not `libraryUnavailable`: one record whose save fails must not
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swiftindex 607e1451..7d48c2c4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swift@@ -37,10 +37,12 @@ extension LibraryRepository { ) 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 history = try NoEpisodeIndex(context: context).history(for: group.id) let work = try Self.snapshot( group, canonicalWorkIDs: [:], types: Self.workTypeDirectory(context: context),- series: Self.seriesDirectory(context: context), credits: .empty)+ series: Self.seriesDirectory(context: context), credits: .empty,+ history: history) return CatchUpSheetState( work: work, record: work.catchUp, progress: CatchUpProgress.build(work: work, day: day, calendar: calendar))
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ComposedTeaching.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ComposedTeaching.swiftindex ba3e6963..5b8ff20c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ComposedTeaching.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ComposedTeaching.swift@@ -160,6 +160,10 @@ extension LibraryRepository { // carries no Site-level interpretation or trim column (Req 3.1). // 6. Apply the composed outcome to Entries and Works.+ let noteCalendar = self.noteCalendar()+ let noteRows = try context.fetch(FetchDescriptor<Entry>(+ predicate: #Predicate<Entry> { $0.hostname == hostname }))+ let beforeNoteFacts = NoEpisodeWriter.facts(rows: noteRows, calendar: noteCalendar) try Self.applyComposedOutcome( context: context, hostname: hostname, site: site, outcome: currentOutcome, titleRuleID: titleRuleID,@@ -167,6 +171,9 @@ extension LibraryRepository { titleTrimPrefix: Self.nonEmpty(contract.request.trimPrefix), titleTrimSuffix: Self.nonEmpty(contract.request.trimSuffix), url: resolvedURL.map { ($0.id, $0.definition) }, timestamp: timestamp)+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNoteFacts,+ after: NoEpisodeWriter.facts(rows: noteRows, calendar: noteCalendar), context: context) // 7. Validate the complete prospective graph, then save once (Req 9.1). // The tolerant entry point: an unrelated hostname's tolerated state@@ -300,6 +307,10 @@ extension LibraryRepository { return .noChanges } + let noteCalendar = self.noteCalendar()+ let noteRows = try context.fetch(FetchDescriptor<Entry>(+ predicate: #Predicate<Entry> { $0.hostname == hostname }))+ let beforeNoteFacts = NoEpisodeWriter.facts(rows: noteRows, calendar: noteCalendar) try Self.applyComposedOutcome( context: context, hostname: hostname, site: site, outcome: currentOutcome, titleRuleID: activePattern.id,@@ -307,6 +318,9 @@ extension LibraryRepository { titleTrimPrefix: Self.nonEmpty(contract.request.trimPrefix), titleTrimSuffix: Self.nonEmpty(contract.request.trimSuffix), url: resolvedURL, timestamp: timestamp)+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNoteFacts,+ after: NoEpisodeWriter.facts(rows: noteRows, calendar: noteCalendar), context: context) let diagnoses: [String: LibraryValidationError] do { diagnoses = try LibraryValidator.validate(context: context).quarantineMap() }@@ -533,6 +547,7 @@ extension LibraryRepository { let siteRules = site.urlRuleValues let onHostname = try Self.hostnameWorks(hostname: hostname, context: context) let workGroups = Self.workGroups(onHostname.works, types: types)+ let noEpisode = try NoEpisodeIndex(context: context) if let torn = Self.firstTorn(workGroups, isTorn: \.isTorn) { throw LibraryRepositoryError.unresolvedDuplicate(type: "Work", id: torn) }@@ -541,7 +556,8 @@ extension LibraryRepository { group, canonicalWorkIDs: [:], types: types, series: series, // The teaching basis reads titles, identities and provenance; a // credit is not one of the fields a rule can change.- credits: .empty)+ credits: .empty,+ history: try noEpisode.history(for: group.id)) return ComposedWorkBasis( id: snapshot.id, displayTitle: snapshot.displayTitle, lastParsedTitle: snapshot.lastParsedTitle,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swiftindex f8753494..38dad679 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. `BackupV16Membership`'s+/// The one field the off-host pre-pass rewrites. `BackupV17Membership`'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 BackupV16Membership {- fileprivate func withWorkURLString(_ value: String?) -> BackupV16Membership {- BackupV16Membership(+extension BackupV17Membership {+ fileprivate func withWorkURLString(_ value: String?) -> BackupV17Membership {+ BackupV17Membership( id: id, workID: workID, hostname: hostname, createdAt: createdAt, urlIdentity: urlIdentity, urlIdentityState: urlIdentityState, urlIdentityRuleID: urlIdentityRuleID, workURLString: value)@@ -100,7 +100,8 @@ extension LibraryRepository { try Self.upsert( plan.payload, exportedAt: exportedAt, importedAt: importedAt, context: context,- batchSize: Self.bulkOperationBatchSize, saveStrategy: saveStrategy)+ batchSize: Self.bulkOperationBatchSize, saveStrategy: saveStrategy,+ noteCalendar: noteCalendar()) } clearImportSidecar()@@ -176,8 +177,13 @@ extension LibraryRepository { importedAt: Date, context: ModelContext, batchSize: Int,- saveStrategy: any RepositorySaveStrategy+ saveStrategy: any RepositorySaveStrategy,+ noteCalendar: Calendar = .current ) throws -> (counts: LibraryRecordCounts, report: BackupImportReport) {+ // Validate and union action history before any note-bearing Entry write.+ // The caller's existing save boundaries commit these insertions.+ _ = try NoEpisodeWriter.insertMissing(+ payload.noEpisodeActions.map { try $0.action() }, context: context) // Req 8.4's list, filled by the Work step below and carried out on the // commit result — the only value that reaches the Settings model (Q62). var droppedThumbnails: [String] = []@@ -200,7 +206,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: [BackupV16Site] = []+ var matchedRecords: [BackupV17Site] = [] for record in payload.sites { if sitesByHostname[record.hostname] != nil { matchedRecords.append(record)@@ -399,6 +405,8 @@ extension LibraryRepository { // The group's modification time, not each row's — see the // Works step above for why all-or-none is the requirement. guard record.modifiedAt >= group.modifiedAt else { continue }+ let beforeNoteFacts = NoEpisodeWriter.facts(+ rows: group.rows, calendar: noteCalendar) for existing in group.rows { apply(record, to: existing) // Value-guarded (T-2334): assigning the same Site/Work@@ -407,12 +415,20 @@ extension LibraryRepository { if existing.site !== site { existing.site = site } if existing.work !== work { existing.work = work } }+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNoteFacts,+ after: NoEpisodeWriter.facts(rows: group.rows, calendar: noteCalendar),+ context: context) } else { let entry = ArchiveRecordBuilders.makeEntry(record) context.insert(entry) entry.site = site entry.work = work entryRows[record.id] = [entry]+ try NoEpisodeWriter.recordNoteTransition(+ before: [],+ after: NoEpisodeWriter.facts(rows: [entry], calendar: noteCalendar),+ context: context) } } try saveStrategy.save(context)@@ -491,7 +507,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: BackupV16Site,+ _ record: BackupV17Site, to site: Site, patterns: [TitlePattern], urlRules: [URLRulePattern]@@ -538,7 +554,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: [BackupV16Work],+ _ records: [BackupV17Work], into workRows: inout [UUID: [Work]], types: WorkTypeDirectory, context: ModelContext,@@ -638,7 +654,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: [BackupV16Membership],+ _ records: [BackupV17Membership], workRows: [UUID: [Work]], workTargets: [UUID: Work], appliedWorkIDs: Set<UUID>,@@ -753,10 +769,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: [BackupV16Membership],+ _ records: [BackupV17Membership], existingMembershipIDs: Set<UUID>, appliedWorkIDs: Set<UUID>- ) -> [BackupV16Membership] {+ ) -> [BackupV17Membership] { var indicesByWork: [UUID: [Int]] = [:] for (index, record) in records.enumerated() { guard let workID = record.workID else { continue }@@ -819,7 +835,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: BackupV16Membership,+ _ record: BackupV17Membership, existingMembershipIDs: Set<UUID>, appliedWorkIDs: Set<UUID> ) -> Bool {@@ -843,7 +859,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: [BackupV16Series],+ _ records: [BackupV17Series], context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy@@ -884,7 +900,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: [BackupV16Link],+ _ records: [BackupV17Link], context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy@@ -939,7 +955,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: [BackupV16Credit],+ _ records: [BackupV17Credit], context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy@@ -986,7 +1002,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: [BackupV16DistinctPair],+ _ records: [BackupV17DistinctPair], context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy@@ -1026,7 +1042,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: BackupV16Work, to work: Work, thumbnail: ArchiveThumbnail+ _ record: BackupV17Work, 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@@ -1133,7 +1149,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: BackupV16Membership, to membership: WorkSiteMembership) {+ internal static func apply(_ record: BackupV17Membership, 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 }@@ -1154,7 +1170,7 @@ extension LibraryRepository { if membership.workID != workID { membership.workID = workID } } - internal static func apply(_ record: BackupV16Entry, to entry: Entry) {+ internal static func apply(_ record: BackupV17Entry, 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+Creators.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Creators.swiftindex ddc841fe..cea0590a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Creators.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Creators.swift@@ -196,6 +196,7 @@ extension LibraryRepository { } let workIDs = roleIDsByWork.keys.sorted { $0.uuidString < $1.uuidString } let groups = try Self.workGroups(ofIDs: workIDs, context: context, types: types)+ let noEpisode = try NoEpisodeIndex(context: context) let works = try workIDs.compactMap { workID -> CreatorWorkCredit? in guard let group = groups[workID] else { return nil }@@ -205,7 +206,8 @@ extension LibraryRepository { // The roles beside this snapshot are *this* creator's, // read from the credits already fetched above; a work's // whole credit list is not drawn on a creator screen.- credits: .empty),+ credits: .empty,+ history: try noEpisode.history(for: group.id)), roles: Self.shownRoles(roleIDsByWork[workID] ?? [], in: roles)) } .sorted(by: CreatorWorkOrdering.precedes)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swiftindex 648ae6df..d8d6549b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift@@ -607,6 +607,8 @@ extension LibraryRepository { return (.invalidated(reason: "The chosen copy is not one of this set's."), [], nil) } let allRows = rowsByID.values.flatMap { $0 }+ let noteCalendar = self.noteCalendar()+ let beforeNoteFacts = NoEpisodeWriter.facts(rows: allRows, calendar: noteCalendar) // Q84: the outcome content is copied off the row that carries it, so a // manual chapter title travels with its provenance instead of one being // invented for it.@@ -669,6 +671,10 @@ extension LibraryRepository { context.delete(row) } }+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNoteFacts,+ after: NoEpisodeWriter.facts(rows: survivorRows, calendar: noteCalendar),+ context: context) if let refusal = try commitResolution( context: context, hostnames: [carrier.hostname], operation: "resolution") {@@ -888,9 +894,21 @@ extension LibraryRepository { // an edit to them. let losers = set.members.dropFirst().map(\.id) let losingRows = losers.flatMap { rowsByID[$0] ?? [] }+ let noteCalendar = self.noteCalendar()+ let affectedEntries = losingRows.flatMap { $0.entryValues }+ let beforeNoteFacts = NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar) let survivors = GroupOrdering.sortedWorkRows(survivorRows) CatchUpWriter.apply(electedCatchUp, to: survivors) DuplicateReconciler.repointEntries(from: losingRows, to: survivors)+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNoteFacts,+ after: NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar),+ context: context)+ let losingWorkIDs = Set(losingRows.map(\.id)).subtracting([survivorID])+ for action in try context.fetch(FetchDescriptor<NoEpisodeAction>())+ where losingWorkIDs.contains(action.workID) {+ action.workID = survivorID+ } // 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 // at the survivor. The reader-confirmed path collapses a set under the@@ -902,7 +920,6 @@ extension LibraryRepository { // only ever touch rows naming one of them, so the fetch is scoped to // them rather than reading the whole table (T-2316): a torn group // resolves without touching the credit table at all.- let losingWorkIDs = Set(losingRows.map(\.id)).subtracting([survivorID]) try DuplicateReconciler.collapseMemberships( from: losingRows, to: survivors, distinctPairs: try context.fetch(FetchDescriptor<WorkDistinctPair>()),
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swiftindex 34bab581..897c0439 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift@@ -168,6 +168,7 @@ extension LibraryRepository { entities: [ entity(Place.self), entity(PlaceSuppression.self), entity(WorkLink.self), entity(WorkCredit.self), entity(WorkDistinctPair.self),+ entity(NoEpisodeAction.self), ]), EmptyLibraryPhase(name: "5 works", entities: [entity(Work.self)]), EmptyLibraryPhase(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swiftindex 0d52df68..01b9fc87 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift@@ -25,7 +25,8 @@ extension LibraryRepository { var sites = SiteLookupCache() return try Self.exportInput( for: Self.snapshot(group), includingWork: true, sites: &sites,- context: context, locale: locale)+ context: context, locale: locale,+ noEpisode: NoEpisodeIndex(context: context)) } } @@ -41,12 +42,14 @@ extension LibraryRepository { // (the `snapshot(WorkGroup:)` note). Stated, not defaulted. let types = try Self.workTypeDirectory(context: context) let series = try Self.seriesDirectory(context: context, locale: locale)+ let noEpisode = try NoEpisodeIndex(context: context) let work = try Self.snapshot( group, canonicalWorkIDs: [:], types: types, series: series, // This work group's credits, never the whole table (T-2316) — // `work(id:)`'s scoping, for its reason. credits: try Self.creditIndex(- context: context, workIDs: Set(group.rows.map(\.id) + [workID])))+ context: context, workIDs: Set(group.rows.map(\.id) + [workID])),+ history: try noEpisode.history(for: group.id)) var sites = SiteLookupCache() // Decision 2's order is the Definitions one — earliest // `firstCapturedAt`, lowercased UUID as tie-break — which@@ -63,7 +66,8 @@ extension LibraryRepository { // line (Req 1.9) — expressed by the input it is built with, and // again by the renderer, which never emits one here. try Self.exportInput(- for: $0, includingWork: false, sites: &sites, context: context, locale: locale)+ for: $0, includingWork: false, sites: &sites, context: context, locale: locale,+ noEpisode: noEpisode) } // V11 (Req 12.1, 12.2). Every title here is a **presented** one: // both reads go through `workGroups`, so a member or a linked work@@ -100,7 +104,8 @@ extension LibraryRepository { // Only the position and the title are read off a sibling. try Self.snapshot( $0, canonicalWorkIDs: [:], types: types, series: series,- credits: .empty)+ credits: .empty,+ history: try noEpisode.history(for: $0.id)) } .sorted(by: SeriesMemberOrdering.precedes) .map {@@ -157,7 +162,8 @@ extension LibraryRepository { includingWork: Bool, sites: inout SiteLookupCache, context: ModelContext,- locale: Locale+ locale: Locale,+ noEpisode: NoEpisodeIndex ) throws -> EntryExportInput { // The chapter title where there is one, the cleaned capture title // otherwise (Req 1.2) — the same `presentationTitle` path Recent and@@ -188,7 +194,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 `mapV16WorkRecord`'s+ // An **empty** series directory, for `mapV17WorkRecord`'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@@ -199,7 +205,8 @@ extension LibraryRepository { // An empty credit index for the empty series directory's // reason: an entry block carries a work's title and type // label, never its credits.- credits: .empty)+ credits: .empty,+ history: try noEpisode.history(for: group.id)) workTitle = work.displayTitle // The resolved display name, whatever kind of type it is: a // rename reaches the next export (Req 4.1), a removed or legacy
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swiftindex 208f1ac1..39be56dc 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift@@ -380,11 +380,12 @@ extension LibraryRepository { /// agree about their assignment whatever the map says. internal static func snapshot( _ group: WorkGroup, canonicalWorkIDs: [UUID: UUID], types: WorkTypeDirectory,- series: SeriesDirectory, credits: CreditIndex+ series: SeriesDirectory, credits: CreditIndex, history: NoEpisodeHistory ) throws -> WorkSnapshot { try snapshot( group, entryRows: group.rows.flatMap { $0.entryValues },- canonicalWorkIDs: canonicalWorkIDs, types: types, series: series, credits: credits)+ canonicalWorkIDs: canonicalWorkIDs, types: types, series: series, credits: credits,+ history: history) } /// The same, over Entry rows the caller already holds@@ -402,10 +403,12 @@ extension LibraryRepository { /// (`docs/agent-notes/swiftdata-relationships.md`). internal static func snapshot( _ group: WorkGroup, entryRows: [Entry], canonicalWorkIDs: [UUID: UUID],- types: WorkTypeDirectory, series: SeriesDirectory, credits: CreditIndex+ types: WorkTypeDirectory, series: SeriesDirectory, credits: CreditIndex,+ history: NoEpisodeHistory ) throws -> WorkSnapshot { let base = snapshot(- group.representative, entries: [], types: types, series: series, credits: credits)+ group.representative, entries: [], types: types, series: series, credits: credits,+ history: history) let entries = try entryGroups(entryRows, canonicalWorkIDs: canonicalWorkIDs) .values .map { try snapshot($0) }@@ -425,13 +428,14 @@ extension LibraryRepository { credits: base.credits, thumbnail: base.thumbnail, releaseDays: base.releaseDays, releaseDaysRaw: base.releaseDaysRaw,- catchUp: catchUp)+ catchUp: catchUp, noEpisodeHistory: history) } // 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 // type it presents (Q41). let carried = snapshot(- group.carrier, entries: [], types: types, series: series, credits: credits)+ group.carrier, entries: [], types: types, series: series, credits: credits,+ history: history) return WorkSnapshot( id: base.id, displayTitle: carried.displayTitle,@@ -481,6 +485,6 @@ extension LibraryRepository { // section, presenting the days of the row whose content it presents. releaseDays: carried.releaseDays, releaseDaysRaw: carried.releaseDaysRaw,- catchUp: catchUp)+ catchUp: catchUp, noEpisodeHistory: history) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swiftnew file mode 100644index 00000000..06a96b0e--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift@@ -0,0 +1,128 @@+import Foundation+import SwiftData++internal struct NoEpisodeNoteCheckpoint {+ let token: DefaultHistoryToken+ let timeZoneID: String+}++internal struct NoEpisodeNoteScanStart {+ let shouldScan: Bool+ let token: DefaultHistoryToken?+ let hadPendingChanges: Bool+}++extension LibraryRepository {+ /// History advances for same-count Entry and action changes, including+ /// remote saves. A missing token or pending context edits always scans.+ internal func beginNoEpisodeNoteScan(+ context: ModelContext, calendar: Calendar+ ) -> NoEpisodeNoteScanStart {+ let pending = context.hasChanges+ let token = Self.latestNoEpisodeHistoryToken(context: context)+ let matches = !pending && token != nil+ && noEpisodeNoteCheckpoint?.token == token+ && noEpisodeNoteCheckpoint?.timeZoneID == calendar.timeZone.identifier+ return NoEpisodeNoteScanStart(+ shouldScan: !matches, token: token, hadPendingChanges: pending)+ }++ /// Certify only an unchanged store snapshot. A scan that wrote clears gets+ /// one more pass before it can be cached; this also avoids mistaking an+ /// external transaction racing our save for part of the scanned snapshot.+ internal func finishNoEpisodeNoteScan(+ _ start: NoEpisodeNoteScanStart, wrote: Bool,+ context: ModelContext, calendar: Calendar+ ) {+ guard !wrote, !start.hadPendingChanges, !context.hasChanges,+ let token = start.token,+ Self.latestNoEpisodeHistoryToken(context: context) == token else {+ noEpisodeNoteCheckpoint = nil+ return+ }+ noEpisodeNoteCheckpoint = NoEpisodeNoteCheckpoint(+ token: token, timeZoneID: calendar.timeZone.identifier)+ }++ private static func latestNoEpisodeHistoryToken(context: ModelContext) -> DefaultHistoryToken? {+ var descriptor = HistoryDescriptor<DefaultHistoryTransaction>()+ descriptor.sortBy = [.init(\.transactionIdentifier, order: .reverse)]+ descriptor.fetchLimit = 1+ return try? context.fetchHistory(descriptor).first?.token+ }++ public func markNoEpisode(+ workID: UUID, day: CivilDay, calendar: Calendar+ ) async throws -> LibraryWriteOutcome {+ try await withLockedContext(mode: .exclusive, operation: "marking no episode") { context in+ let group = try self.resolveWorkWriteTarget(id: workID, context: context)+ if let refusal = Self.tornRefusal(group) { return refusal }+ let work = group.carrier+ guard work.workStatus == .ongoing, work.readingStatus == .reading,+ work.releaseDays.contains(day.weekday(calendar: calendar)) else {+ return .conflict(.recordChanged(recordID: workID))+ }+ let entries = try context.fetch(FetchDescriptor<Entry>(+ predicate: #Predicate<Entry> { $0.work?.id == workID }))+ let matchingNote = NoEpisodeWriter.facts(rows: entries, calendar: calendar)+ .contains { $0.workID == workID && $0.day == day }+ guard !matchingNote else { return .conflict(.recordChanged(recordID: workID)) }+ let history = try NoEpisodeIndex(context: context).history(for: workID)+ guard try !history.isMarked(workID: workID, day: day.description) else { return .committed }+ let action = try NoEpisodeHistory.Action(+ workID: workID, key: "mark/\(UUID().uuidString)", day: day.description,+ kind: .mark,+ observedClearKeys: history.clearKeys(workID: workID, day: day.description).sorted())+ try NoEpisodeWriter.insertMissing([action], context: context)+ do { try saveStrategy.save(context) }+ catch {+ throw LibraryRepositoryError.libraryUnavailable(+ operation: "saving no-episode mark", reason: String(describing: error))+ }+ return .committed+ }+ }++ public func undoNoEpisode(workID: UUID, day: CivilDay) async throws -> LibraryWriteOutcome {+ try await withLockedContext(mode: .exclusive, operation: "undoing no episode") { context in+ let group = try self.resolveWorkWriteTarget(id: workID, context: context)+ if let refusal = Self.tornRefusal(group) { return refusal }+ let history = try NoEpisodeIndex(context: context).history(for: workID)+ guard try history.isMarked(workID: workID, day: day.description) else { return .committed }+ let action = try NoEpisodeHistory.Action(+ workID: workID, key: "clear/\(UUID().uuidString)", day: day.description,+ kind: .clear, observedClearKeys: [])+ try NoEpisodeWriter.insertMissing([action], context: context)+ do { try saveStrategy.save(context) }+ catch {+ throw LibraryRepositoryError.libraryUnavailable(+ operation: "saving no-episode undo", reason: String(describing: error))+ }+ return .committed+ }+ }++ public func prepareNoEpisodeNotes(calendar: Calendar) async throws {+ try await withLockedContext(mode: .exclusive, operation: "preparing no-episode notes") { context in+ let scan = self.beginNoEpisodeNoteScan(context: context, calendar: calendar)+ guard scan.shouldScan else { return }+ let wrote = try NoEpisodeWriter.reconcileCurrentNotes(+ context: context, calendar: calendar)+ if wrote {+ do { try saveStrategy.save(context) }+ catch {+ throw LibraryRepositoryError.libraryUnavailable(+ operation: "saving no-episode note clears", reason: String(describing: error))+ }+ }+ self.finishNoEpisodeNoteScan(+ scan, wrote: wrote, context: context, calendar: calendar)+ }+ }++ internal static func noteFacts(+ _ group: EntryGroup, calendar: Calendar+ ) -> Set<NoEpisodeWriter.NoteFact> {+ NoEpisodeWriter.facts(rows: group.rows, calendar: calendar)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swiftindex 9f85725f..888820c3 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift@@ -62,12 +62,14 @@ extension LibraryRepository { let allWorks = try Self.worksOn(hostname: hostname, context: context) let types = try Self.workTypeDirectory(context: context) let series = try Self.seriesDirectory(context: context)+ let noEpisode = try NoEpisodeIndex(context: context) let worksBasis = try Self.workGroups(allWorks, types: types).values .map { group -> WorkBasisEntry in Self.workBasisEntry( from: try Self.snapshot( group, canonicalWorkIDs: [:], types: types, series: series,- credits: .empty))+ credits: .empty,+ history: try noEpisode.history(for: group.id))) }.sorted { $0.id.uuidString < $1.id.uuidString } let basis = ReparseBasis(@@ -128,11 +130,13 @@ extension LibraryRepository { let types = try Self.workTypeDirectory(context: context) let series = try Self.seriesDirectory(context: context) let workGroups = Self.workGroups(allWorks, types: types)+ let noEpisode = try NoEpisodeIndex(context: context) let worksBasis = try workGroups.values.map { group -> WorkBasisEntry in Self.workBasisEntry( from: try Self.snapshot( group, canonicalWorkIDs: [:], types: types, series: series,- credits: .empty))+ credits: .empty,+ history: try noEpisode.history(for: group.id))) }.sorted { $0.id.uuidString < $1.id.uuidString } let currentBasis = ReparseBasis(@@ -156,6 +160,8 @@ extension LibraryRepository { // 4. Apply — allocate IDs/time AFTER equality let timestamp = self.clock.now()+ let noteCalendar = self.noteCalendar()+ let beforeNoteFacts = Self.noteFacts(group, calendar: noteCalendar) let patternID = activePattern.id let plan = contract.outcome.plan@@ -198,6 +204,9 @@ extension LibraryRepository { timestamp: timestamp ) }+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNoteFacts,+ after: Self.noteFacts(group, calendar: noteCalendar), context: context) // Update reused Works for workID in plan.worksToReuse {@@ -408,6 +417,11 @@ extension LibraryRepository { return .invalidated(reason: "capture produced an invalid Entry tuple: \(error)") } + try NoEpisodeWriter.recordNoteTransition(+ before: [],+ after: NoEpisodeWriter.facts(rows: [entry], calendar: noteCalendar()),+ context: context)+ do { try self.saveStrategy.save(context) } catch { // One capture's save failing is not the library going away
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swiftindex f2ddba72..0f66bc25 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift@@ -141,11 +141,13 @@ extension LibraryRepository { let directory = try Self.seriesDirectory(context: context) guard let display = directory[id] else { return nil } let types = try Self.workTypeDirectory(context: context)+ let noEpisode = try NoEpisodeIndex(context: context) let members = try Self.memberGroups(of: id, context: context, types: types) .map { try Self.snapshot( $0, canonicalWorkIDs: [:], types: types, series: directory,- credits: .empty)+ credits: .empty,+ history: try noEpisode.history(for: $0.id)) } .sorted(by: SeriesMemberOrdering.precedes) return SeriesDetail(@@ -199,13 +201,15 @@ extension LibraryRepository { ) throws -> [WorkPickerCandidate] { let directory = try seriesDirectory(context: context) let types = try workTypeDirectory(context: context)+ let noEpisode = try NoEpisodeIndex(context: context) return try workGroups(try context.fetch(FetchDescriptor<Work>()), types: types) .values .filter { $0.id != excluded } .map { group in let work = try snapshot( group, canonicalWorkIDs: [:], types: types, series: directory,- credits: .empty)+ credits: .empty,+ history: try noEpisode.history(for: group.id)) return WorkPickerCandidate(work: work, unavailableReason: reason(work)) } .sorted(by: WorkPickerOrdering.precedes)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swiftindex 2a863ea2..36682e3a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift@@ -43,6 +43,7 @@ extension LibraryRepository { let entryRows = try context.fetch(FetchDescriptor<Entry>()) let works = try context.fetch(FetchDescriptor<Work>()) let sites = try context.fetch(FetchDescriptor<Site>())+ let noEpisode = try NoEpisodeIndex(context: context) // Req 9.1's workload. Rule groups contribute nothing to it (Q39), // so nothing here walks the rule tables.@@ -245,7 +246,8 @@ extension LibraryRepository { // relationship the bucketing below reads. let schedule = try Self.todaySchedule( workGroups: workGroups, entryRows: entryRows,- canonicalWorkIDs: canonicalWorkIDs, types: types, calendar: calendar)+ canonicalWorkIDs: canonicalWorkIDs, types: types, calendar: calendar,+ noEpisode: noEpisode) todayPresentationLogger.debug( "Built Recent presentation with \(sortedEntries.count, privacy: .public) rows and \(actionableCount, privacy: .public) actionable"@@ -310,7 +312,7 @@ extension LibraryRepository { /// `series` and `credits` are empty: `ScheduledWork` reads neither. private static func todaySchedule( workGroups: [UUID: WorkGroup], entryRows: [Entry], canonicalWorkIDs: [UUID: UUID],- types: WorkTypeDirectory, calendar: Calendar+ types: WorkTypeDirectory, calendar: Calendar, noEpisode: NoEpisodeIndex ) throws -> TodaySchedule { let admitted = workGroups.values.filter { group in let carrier = group.carrier@@ -330,7 +332,7 @@ extension LibraryRepository { try snapshot( group, entryRows: entryRowsByWorkID[group.id] ?? [], canonicalWorkIDs: canonicalWorkIDs, types: types, series: .empty,- credits: .empty)+ credits: .empty, history: try noEpisode.history(for: group.id)) } return TodaySchedule.build(works: snapshots, calendar: calendar) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDeletion.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDeletion.swiftindex a28bc17b..560c4d97 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDeletion.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDeletion.swift@@ -136,6 +136,7 @@ extension LibraryRepository { // unchecked — the state the whole membership arm exists to catch. let hostnames = Set(group.rows.flatMap { $0.membershipValues.map(\.hostname) }) let timestamp = MillisecondInstant.quantize(self.clock.now())+ let noteCalendar = self.noteCalendar() // 5. Shared groups are repointed, not deleted (Q25). Relying on // SwiftData's nullify would tear the group: a nil assignment never@@ -144,10 +145,14 @@ extension LibraryRepository { // provenance and timestamps — `DuplicateReconciler.repointEntries`' // rule, for the same reason it has it. for entryGroup in shared {+ let before = Self.noteFacts(entryGroup, calendar: noteCalendar) guard let survivor = entryGroup.rows.compactMap(\.work) .first(where: { $0.id != group.id }) else { continue } for row in entryGroup.rows where row.work?.id == group.id { row.work = survivor }+ try NoEpisodeWriter.recordNoteTransition(+ before: before,+ after: Self.noteFacts(entryGroup, calendar: noteCalendar), context: context) } // 6. The disposition, applied to every row of every owned group@@ -199,6 +204,10 @@ extension LibraryRepository { // which this commit does whenever validation refuses it — crashes // SwiftData in snapshot creation. A fetch returns materialized rows. let deletedWorkIDs = Set(group.rows.map(\.id))+ for action in try context.fetch(FetchDescriptor<NoEpisodeAction>())+ where deletedWorkIDs.contains(action.workID) {+ context.delete(action)+ } for workID in deletedWorkIDs { let memberships = try context.fetch( FetchDescriptor<WorkSiteMembership>(@@ -306,7 +315,8 @@ extension LibraryRepository { // The contract is over the work's own authored fields and the // entries it owns; the credits naming it go with it whatever they // are (`work-creators` Req 7.1).- credits: .empty)+ credits: .empty,+ history: try NoEpisodeIndex(context: context).history(for: group.id)) let (owned, shared) = try entryGroups(ofWorkGroup: group, context: context) var torn: [UUID: [AuthoredVariant<EntryAuthoredContent>]] = [:] for entryGroup in owned where entryGroup.isTorn {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swiftindex 6e47b100..ad9a9225 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift@@ -182,7 +182,8 @@ extension LibraryRepository { let work = try Self.snapshot( group, canonicalWorkIDs: [:], types: types, series: try Self.seriesDirectory(context: context),- credits: credits)+ credits: credits,+ history: try NoEpisodeIndex(context: context).history(for: group.id)) // One snapshot per logical record already, in activity order — // newest `lastSharedAt` first, which is both the list's order (5.4) // and the open-last-noted answer (5.3).
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swiftindex 11759d78..05dd7e24 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift@@ -198,6 +198,7 @@ extension LibraryRepository { // Work, and merging into either writes the same place. let types = try Self.workTypeDirectory(context: context) let series = try Self.seriesDirectory(context: context)+ let noEpisode = try NoEpisodeIndex(context: context) let snapshots = try Self.workGroups( try context.fetch(FetchDescriptor<Work>()).filter { $0.id != sourceWorkID }, types: types)@@ -208,7 +209,8 @@ extension LibraryRepository { .map { try Self.snapshot( $0, canonicalWorkIDs: [:], types: types, series: series,- credits: .empty)+ credits: .empty,+ history: try noEpisode.history(for: $0.id)) } // Req 4.1's ordering lives in `WorkMergePlanner.destinations` and // nowhere else (Q63). This used to restate it here with a different@@ -217,7 +219,8 @@ extension LibraryRepository { return WorkMergePlanner.destinations( for: try Self.snapshot( source, canonicalWorkIDs: [:], types: types, series: series,- credits: .empty),+ credits: .empty,+ history: try noEpisode.history(for: source.id)), from: snapshots) } }@@ -485,6 +488,12 @@ extension LibraryRepository { // target is not, and a hostname-scoped fetch would silently leave // them behind — attached to a Work that is about to be deleted. let sourceEntries = sourceGroup.rows.flatMap { $0.entryValues }+ let noteCalendar = self.noteCalendar()+ let beforeNoteFacts = Set(sourceEntries.compactMap { entry -> NoEpisodeWriter.NoteFact? in+ guard let workID = entry.work?.id else { return nil }+ return .init(entryID: entry.id, workID: workID,+ sharedAt: entry.lastSharedAt, calendar: noteCalendar)+ }) let movedIDs = Set(outcome.movedEntryIDs) for entry in sourceEntries where movedIDs.contains(entry.id) { // A to-one relationship has no other shape (Q80): the pointer@@ -493,6 +502,17 @@ extension LibraryRepository { entry.work = target entry.modifiedAt = timestamp }+ let afterNoteFacts = Set(sourceEntries.compactMap { entry -> NoEpisodeWriter.NoteFact? in+ guard let workID = entry.work?.id else { return nil }+ return .init(entryID: entry.id, workID: workID,+ sharedAt: entry.lastSharedAt, calendar: noteCalendar)+ })+ try NoEpisodeWriter.recordNoteTransition(+ before: beforeNoteFacts, after: afterNoteFacts, context: context)+ for action in try context.fetch(FetchDescriptor<NoEpisodeAction>())+ where action.workID == sourceID {+ action.workID = targetID+ } // Update target entries' modifiedAt (requirement 6.9) for entry in targetGroup.rows.flatMap({ $0.entryValues })@@ -769,11 +789,14 @@ extension LibraryRepository { let creditIndex = CreditIndex( credits: creditRows, creators: creators, roles: try creatorRoleDirectory(context: context))+ let noEpisode = try NoEpisodeIndex(context: context) let sourceBasis = try buildMergeWorkBasis(- sourceGroup, context: context, types: types, series: series, credits: creditIndex)+ sourceGroup, context: context, types: types, series: series, credits: creditIndex,+ noEpisode: noEpisode) let targetBasis = try buildMergeWorkBasis(- targetGroup, context: context, types: types, series: series, credits: creditIndex)+ targetGroup, context: context, types: types, series: series, credits: creditIndex,+ noEpisode: noEpisode) // Derive current rule from Site. Req 2.1: this asserted exactly one row // and threw for two tolerated states, so the reader could not even see@@ -908,11 +931,13 @@ extension LibraryRepository { context: ModelContext, types: WorkTypeDirectory, series: SeriesDirectory,- credits: CreditIndex+ credits: CreditIndex,+ noEpisode: NoEpisodeIndex ) throws -> WorkMergeWorkBasis { let work = group.representative let workSnapshot = try snapshot(- group, canonicalWorkIDs: [:], types: types, series: series, credits: credits)+ group, canonicalWorkIDs: [:], types: types, series: series, credits: credits,+ history: try noEpisode.history(for: group.id)) // One identity **per site** (Req 4.2), read off the memberships. An // identity state this build has no case for reads as `.none` through the
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex 18a57912..a27b2ce1 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -92,6 +92,10 @@ public actor LibraryRepository { internal let capabilities: AsterismCapabilities internal let clock: any RepositoryClock internal let saveStrategy: any RepositorySaveStrategy+ internal let noteCalendar: @Sendable () -> Calendar+ /// The last committed store revision whose notes were reconciled in this+ /// repository, under the calendar zone used to derive their civil days.+ internal var noEpisodeNoteCheckpoint: NoEpisodeNoteCheckpoint? /// In-memory per-Site validation quarantine (Req 9.4, Q15): the Sites whose /// committed state failed validation at open. Recomputed each open from@@ -390,6 +394,7 @@ public actor LibraryRepository { var workTypePass = WorkTypeReconciliationOutcome() var creatorPass = CreatorReconciliationOutcome() var creditPass = CreditReconcileReport()+ var noteClearPrewrite = false let pass = try await withLockedContext( mode: .exclusive, operation: "reconciling Site rows after sync" ) { context in@@ -494,6 +499,18 @@ public actor LibraryRepository { // lock: rule state is what Work identity and citation replay read, // and the Site union has just moved it. Derived here, never // remembered — the same rule the Site work list follows.+ // Preserve note evidence before a duplicate pass can move or remove+ // an Entry. The post-collapse pass below handles its final shape.+ let calendar = noteCalendar()+ let noteScan = self.beginNoEpisodeNoteScan(context: context, calendar: calendar)+ if noteScan.shouldScan {+ noteClearPrewrite = try NoEpisodeWriter.reconcileCurrentNotes(+ context: context, calendar: calendar)+ if noteClearPrewrite { try saveStrategy.save(context) }+ self.finishNoEpisodeNoteScan(+ noteScan, wrote: noteClearPrewrite,+ context: context, calendar: calendar)+ } if runsDuplicatePhase { // One fold of the type table for the whole phase, built here // rather than inside each half: the scan canonicalizes work@@ -509,7 +526,7 @@ public actor LibraryRepository { batchSize: Self.bulkOperationBatchSize, context: context, saveStrategy: self.saveStrategy,- types: types)+ types: types, noteCalendar: noteCalendar()) } return pass }@@ -526,6 +543,7 @@ public actor LibraryRepository { outcome.creators = creatorPass outcome.credits = creditPass outcome.duplicates = duplicatePass.outcome+ outcome.noEpisodeChanged = noteClearPrewrite || duplicatePass.noteActionsChanged outcome.duplicatePhaseRan = runsDuplicatePhase if runsDuplicatePhase { duplicatePhaseSkipped = false@@ -539,6 +557,30 @@ public actor LibraryRepository { } if outcome.duplicates.followUpNeeded { duplicateFollowUpNeeded = true } + // Duplicate collapse may have changed logical note assignments after+ // the first locked pass. Reconcile the resulting groups on both tiers.+ let noteClearPostwrite: Bool+ if duplicatePass.deletions.isEmpty {+ noteClearPostwrite = false+ } else {+ noteClearPostwrite = try await withLockedContext(+ mode: .exclusive, operation: "reconciling no-episode notes"+ ) { context in+ let calendar = noteCalendar()+ let noteScan = self.beginNoEpisodeNoteScan(context: context, calendar: calendar)+ guard noteScan.shouldScan else {+ return false+ }+ let wrote = try NoEpisodeWriter.reconcileCurrentNotes(+ context: context, calendar: calendar)+ if wrote { try saveStrategy.save(context) }+ self.finishNoEpisodeNoteScan(+ noteScan, wrote: wrote, context: context, calendar: calendar)+ return wrote+ }+ }+ outcome.noEpisodeChanged = outcome.noEpisodeChanged || noteClearPostwrite+ // Q46's second half, which only `confirmImport` used to honour. A // reconcile trigger that arrived while this pass held the flag deferred // rather than interleaving with its chunk saves, and nothing re-fired it@@ -625,7 +667,7 @@ public actor LibraryRepository { ) { context in try DuplicateReconciler.commitDeletions( plans, canonicalWorkIDs: canonicalWorkIDs, context: context,- saveStrategy: self.saveStrategy)+ saveStrategy: self.saveStrategy, noteCalendar: noteCalendar()) } let committed = Set(deleted)@@ -905,6 +947,7 @@ public actor LibraryRepository { capabilities: AsterismCapabilities, clock: any RepositoryClock, saveStrategy: any RepositorySaveStrategy,+ noteCalendar: @escaping @Sendable () -> Calendar = { Calendar.current }, quarantined: [String: LibraryValidationError] = [:], diagnostics: LibraryDiagnostics = .empty, mirroring: MirroringAttachment = .notRequested@@ -914,6 +957,7 @@ public actor LibraryRepository { self.capabilities = capabilities self.clock = clock self.saveStrategy = saveStrategy+ self.noteCalendar = noteCalendar self.quarantined = quarantined self.diagnostics = diagnostics self.mirroring = mirroring@@ -1013,6 +1057,8 @@ public actor LibraryRepository { // and its alias are both the immutable raw URL (Q21), so the Entry is // V4-conservative and same-URL re-shares match forever. entry.conservativeIdentityKey = draft.rawURLString+ // This convenience capture leaves the entry unattached. Its later+ // assignment records the work/date clear in that transaction. do { try saveStrategy.save(context) } catch { throw LibraryRepositoryError.libraryUnavailable(@@ -1052,12 +1098,17 @@ public actor LibraryRepository { } if let refusal = Self.tornRefusal(group) { return refusal } + let calendar = noteCalendar()+ let before = Self.noteFacts(group, calendar: calendar)+ let timestamp = clock.now() for row in group.rows { row.note = note row.rating = rating row.modifiedAt = timestamp }+ try NoEpisodeWriter.recordNoteTransition(+ before: before, after: Self.noteFacts(group, calendar: calendar), context: context) do { try saveStrategy.save(context) } catch { throw LibraryRepositoryError.libraryUnavailable(@@ -1110,6 +1161,10 @@ public actor LibraryRepository { } } + let calendar = noteCalendar()+ try NoEpisodeWriter.recordNoteTransition(+ before: Self.noteFacts(group, calendar: calendar), after: [], context: context)+ let timestamp = clock.now() let affectedWorkIDs = Set(group.rows.compactMap { $0.work?.id }) for row in group.rows { context.delete(row) }@@ -1241,7 +1296,8 @@ public actor LibraryRepository { // A Work created this instant carries no credit: credits are // authored on the work's detail, which this snapshot is the way // to (`work-creators` Decision 6).- credits: .empty)+ credits: .empty,+ history: .empty) } /// The Works list and the unattached Entries beside it, both bucketed into@@ -1257,6 +1313,7 @@ public actor LibraryRepository { public func works() async throws -> WorksSnapshot { try await withLockedContext(mode: .shared, operation: "reading Works") { context in let workRows = try context.fetch(FetchDescriptor<Work>())+ let entryRows = try context.fetch(FetchDescriptor<Entry>()) // The Definitions' assignment normalisation, from the rows already // in hand (Q38). Without it this screen reads a group torn that // Recent reads whole, for the same Entries — the disagreement@@ -1278,12 +1335,20 @@ public actor LibraryRepository { // works resolve their credits without a thousand queries // (`work-creators` Req 11.6). let credits = try Self.creditIndex(context: context)+ let noEpisode = try NoEpisodeIndex(context: context)+ var entryRowsByWorkID: [UUID: [Entry]] = [:]+ for row in entryRows {+ guard let workID = row.work?.id else { continue }+ entryRowsByWorkID[workID, default: []].append(row)+ } let workSnapshots = try Self.workGroups(workRows, types: types) .values .map { try Self.snapshot(- $0, canonicalWorkIDs: canonicalWorkIDs, types: types, series: series,- credits: credits)+ $0, entryRows: entryRowsByWorkID[$0.id] ?? [],+ canonicalWorkIDs: canonicalWorkIDs, types: types, series: series,+ credits: credits,+ history: try noEpisode.history(for: $0.id)) } let sortedWorks = workSnapshots.sorted { left, right in let leftNewest = left.entries.first?.lastSharedAt@@ -1304,7 +1369,7 @@ public actor LibraryRepository { // every attached Entry a second time (the Work snapshots already // did) to discard ~95% of the result. let unattached = try Self.entryGroups(- try context.fetch(FetchDescriptor<Entry>()),+ entryRows, canonicalWorkIDs: canonicalWorkIDs) .values .filter { $0.carrier.work == nil }@@ -1328,7 +1393,8 @@ public actor LibraryRepository { // the index is keyed by work, so a fold of every credit in the // library answered the one key this read asks for. credits: try Self.creditIndex(- context: context, workIDs: Set(group.rows.map(\.id) + [id])))+ context: context, workIDs: Set(group.rows.map(\.id) + [id])),+ history: try NoEpisodeIndex(context: context).history(for: group.id)) } } @@ -1345,6 +1411,7 @@ public actor LibraryRepository { id: entryID, context: context, canonicalWorkIDs: [:]).representative let types = try Self.workTypeDirectory(context: context) let series = try Self.seriesDirectory(context: context)+ let noEpisode = try NoEpisodeIndex(context: context) // V8: only Works holding a membership for the Entry's hostname are // move destinations (Req 3.4) — a Work on another site with the same // title is not one of them.@@ -1358,7 +1425,8 @@ public actor LibraryRepository { // sheet never shows. try Self.snapshot( $0, canonicalWorkIDs: [:], types: types, series: series,- credits: .empty)+ credits: .empty,+ history: try noEpisode.history(for: $0.id)) } // The Works list's own collation, through its one home rather // than a second copy of it here.@@ -1432,11 +1500,18 @@ public actor LibraryRepository { 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) })+ let entrySnapshots = try Self.entryGroups(+ entryRows, canonicalWorkIDs: canonicalWorkIDs)+ .values.map { try Self.snapshot($0) }+ let notes = NumberedNote.from(entrySnapshots)+ let notedDays = Set(entrySnapshots.map {+ CivilDay($0.lastSharedAt, calendar: calendar)+ }) if let rebased = CatchUpProgress.rebased( record: storedRecord, notes: notes, releaseDays: stored.releaseDays,+ noEpisodeDays: try NoEpisodeIndex(context: context)+ .history(for: group.id).activeDays(for: group.id)+ .subtracting(notedDays), workStatus: stored.workStatus, now: timestamp, calendar: calendar) { CatchUpWriter.apply(rebased, to: group.rows)@@ -1534,6 +1609,9 @@ public actor LibraryRepository { } if let refusal = Self.tornRefusal(group) { return refusal } + let calendar = noteCalendar()+ let before = Self.noteFacts(group, calendar: calendar)+ let timestamp = MillisecondInstant.quantize(clock.now()) let representative = group.representative let priorWorkIDs = Set(group.rows.compactMap { $0.work?.id })@@ -1617,6 +1695,8 @@ public actor LibraryRepository { } for row in group.rows { Self.applyManualAssignment(to: row, at: timestamp) }+ try NoEpisodeWriter.recordNoteTransition(+ before: before, after: Self.noteFacts(group, calendar: calendar), context: context) do { try saveStrategy.save(context) } catch { throw LibraryRepositoryError.libraryUnavailable(@@ -1794,7 +1874,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 `BackupV16Entry`+ // own `map*Record` family in `BackupArchiveProjection`, over `BackupV17Entry` // and friends, and never used these. internal func withLockedContext<Value: Sendable>(@@ -2061,11 +2141,12 @@ public actor LibraryRepository { /// stored `seriesID` as unresolved, which is the right answer only for a /// caller that genuinely has no series table. internal static func snapshot(- _ work: Work, types: WorkTypeDirectory, series: SeriesDirectory, credits: CreditIndex+ _ work: Work, types: WorkTypeDirectory, series: SeriesDirectory, credits: CreditIndex,+ history: NoEpisodeHistory ) throws -> WorkSnapshot { snapshot( work, entries: try work.entryValues.map(snapshot).sorted(by: entryActivityOrder),- types: types, series: series, credits: credits)+ types: types, series: series, credits: credits, history: history) } /// The fields-only core of the snapshot above: everything the row itself@@ -2079,7 +2160,7 @@ public actor LibraryRepository { /// carrier, whose entries it replaces with the group's own. internal static func snapshot( _ work: Work, entries: [EntrySnapshot], types: WorkTypeDirectory,- series: SeriesDirectory, credits: CreditIndex+ series: SeriesDirectory, credits: CreditIndex, history: NoEpisodeHistory ) -> WorkSnapshot { let membership = GroupOrdering.membership(of: work) return WorkSnapshot(@@ -2119,7 +2200,8 @@ public actor LibraryRepository { // unknown spelling from one the reader left alone. releaseDays: work.releaseDays, releaseDaysRaw: work.releaseDaysRaw,- catchUp: work.catchUpRecord+ catchUp: work.catchUpRecord,+ noEpisodeHistory: history ) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swiftindex 04253670..6a74f11c 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 `BackupV16Exporter`'s decode-validation refuses the file it just wrote.+ /// and `BackupV17Exporter`'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 169562ac..bc1cca6a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Models.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Models.swift@@ -1,66 +1,67 @@ import Foundation import SwiftData -// The live model classes are V16's, nested inside `AsterismSchemaV17`+// The live model classes are V18's, nested inside `AsterismSchemaV18` // (Decision 6, Q20). Top-level typealiases keep every call site (`Entry`, // `Site`, …) unchanged. //-// The nesting is what makes the frozen `AsterismSchemaV17` snapshot possible+// The nesting is what makes the frozen `AsterismSchemaV18` 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 = 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+public typealias Entry = AsterismSchemaV18.Entry+public typealias Work = AsterismSchemaV18.Work+public typealias Site = AsterismSchemaV18.Site+public typealias TitlePattern = AsterismSchemaV18.TitlePattern+public typealias URLRulePattern = AsterismSchemaV18.URLRulePattern+public typealias WorkTypeEntity = AsterismSchemaV18.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 = AsterismSchemaV17.WorkSiteMembership+public typealias WorkSiteMembership = AsterismSchemaV18.WorkSiteMembership /// V8: a reader's "not the same work" over an unordered pair of Works (Q20).-public typealias WorkDistinctPair = AsterismSchemaV17.WorkDistinctPair+public typealias WorkDistinctPair = AsterismSchemaV18.WorkDistinctPair /// V11: a reader-named, ordered collection a Work belongs to at most once /// (`series-and-related-works` Decision 1).-public typealias Series = AsterismSchemaV17.Series+public typealias Series = AsterismSchemaV18.Series /// V11: an undirected, typed connection between two distinct Works /// (`series-and-related-works` Decision 5).-public typealias WorkLink = AsterismSchemaV17.WorkLink+public typealias WorkLink = AsterismSchemaV18.WorkLink /// V12: a person a work is credited to, a reader-managed directory record /// (`work-creators` Decision 2).-public typealias Creator = AsterismSchemaV17.Creator+public typealias Creator = AsterismSchemaV18.Creator /// V12: one entry in the ordered role list credits reference by identity /// (`work-creators` Decision 1).-public typealias CreatorRole = AsterismSchemaV17.CreatorRole+public typealias CreatorRole = AsterismSchemaV18.CreatorRole /// V12: one work-and-creator pairing, carrying the roles that creator holds on /// that work (`work-creators` Decision 6).-public typealias WorkCredit = AsterismSchemaV17.WorkCredit+public typealias WorkCredit = AsterismSchemaV18.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 = AsterismSchemaV17.Character-public typealias CharacterSuppression = AsterismSchemaV17.CharacterSuppression+public typealias CharacterRecord = AsterismSchemaV18.Character+public typealias CharacterSuppression = AsterismSchemaV18.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 = AsterismSchemaV17.Place+public typealias Place = AsterismSchemaV18.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 = AsterismSchemaV17.PlaceSuppression+public typealias PlaceSuppression = AsterismSchemaV18.PlaceSuppression+public typealias NoEpisodeAction = AsterismSchemaV18.NoEpisodeAction /// 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`, `BackupV16Types`, `BackupArchiveProjection` — each+/// `ArchiveRecordBuilders`, `BackupV17Types`, `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. ///@@ -135,7 +136,7 @@ enum JSONBlob { } } -extension AsterismSchemaV17 {+extension AsterismSchemaV18 { @Model public final class Entry {@@ -702,7 +703,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 `AsterismSchemaV17` snapshot, which is frozen by+ // consumer but the frozen `AsterismSchemaV18` snapshot, which is frozen by // reference to it (Q8). public init(hostname: String, displayName: String? = nil) {@@ -1763,7 +1764,7 @@ public final class PlaceSuppression { } } -} // extension AsterismSchemaV17+} // extension AsterismSchemaV18 /// 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/NSItemProvider+ItemProviderLoading.swift b/Packages/AsterismCore/Sources/AsterismCore/NSItemProvider+ItemProviderLoading.swiftindex da98ed17..5c85c036 100644--- a/Packages/AsterismCore/Sources/AsterismCore/NSItemProvider+ItemProviderLoading.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/NSItemProvider+ItemProviderLoading.swift@@ -51,7 +51,10 @@ extension NSItemProvider: ItemProviderLoading { private var textTypeIdentifier: String? { registeredTypeIdentifiers.first { identifier in- UTType(identifier)?.conforms(to: .text) == true+ guard let type = UTType(identifier) else { return false }+ // macOS 27 reports public.plain-text as not conforming to public.text.+ // Match the standard concrete types before asking for broader text conformance.+ return type == .plainText || type == .utf8PlainText || type.conforms(to: .text) } } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swiftnew file mode 100644index 00000000..626730f3--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift@@ -0,0 +1,158 @@+import Foundation++/// Immutable, scoped evidence for a release date. Union is the only merge+/// operation; no arrival time or physical SwiftData row participates.+public struct NoEpisodeHistory: Equatable, Sendable {+ public static let empty = try! NoEpisodeHistory([])+ public enum HistoryError: Error, Equatable {+ case invalidKey(String)+ case invalidDay(String)+ case invalidVersion(Int)+ case invalidAcknowledgement(String)+ case conflictingAction(UUID, String)+ case invalidPayload+ }++ public struct Action: Equatable, Hashable, Sendable {+ public enum Kind: String, Codable, Sendable { case mark, clear }++ public let workID: UUID+ public let key: String+ public let day: String+ public let kind: Kind+ public let observedClearKeys: [String]++ public init(workID: UUID, key: String, day: String, kind: Kind,+ observedClearKeys: [String]) throws {+ guard Self.validKey(key, kind: kind, day: day) else {+ throw HistoryError.invalidKey(key)+ }+ guard Self.civilDay(day) != nil else { throw HistoryError.invalidDay(day) }+ guard kind == .mark || observedClearKeys.isEmpty else {+ throw HistoryError.invalidPayload+ }+ for observed in observedClearKeys where !Self.validKey(+ observed, kind: .clear, day: day+ ) {+ throw HistoryError.invalidAcknowledgement(observed)+ }+ self.workID = workID+ self.key = key+ self.day = day+ self.kind = kind+ self.observedClearKeys = Array(Set(observedClearKeys)).sorted()+ }++ private struct Wire: Codable {+ let version: Int+ let key: String+ let day: String+ let kind: Kind+ let observedClearKeys: [String]+ }++ public func canonicalData() throws -> Data {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]+ return try encoder.encode(Wire(version: 1, key: key, day: day,+ kind: kind, observedClearKeys: observedClearKeys))+ }++ public static func decode(_ data: Data, workID: UUID) throws -> Self {+ let wire = try JSONDecoder().decode(Wire.self, from: data)+ guard wire.version == 1 else { throw HistoryError.invalidVersion(wire.version) }+ return try Self(workID: workID, key: wire.key, day: wire.day,+ kind: wire.kind, observedClearKeys: wire.observedClearKeys)+ }++ private static func validKey(+ _ key: String, kind: Kind, day: String+ ) -> Bool {+ if kind == .clear, key.hasPrefix("note/") {+ let parts = key.split(separator: "/", omittingEmptySubsequences: false)+ guard parts.count == 5, parts[0] == "note",+ let entryID = UUID(uuidString: String(parts[1])),+ parts[1] == entryID.uuidString,+ let originalWorkID = UUID(uuidString: String(parts[2])),+ parts[2] == originalWorkID.uuidString,+ let milliseconds = Int64(parts[3]),+ parts[3] == String(milliseconds),+ parts[4] == day else { return false }+ return true+ }+ let prefix = kind == .mark ? "mark/" : "clear/"+ guard key.hasPrefix(prefix), let id = UUID(uuidString: String(key.dropFirst(prefix.count))) else {+ return false+ }+ return key == prefix + id.uuidString+ }++ public var civilDay: CivilDay {+ // Constructor and decoder validate this spelling.+ Self.civilDay(day)!+ }++ private static func civilDay(_ text: String) -> CivilDay? {+ let parts = text.split(separator: "-", omittingEmptySubsequences: false)+ guard parts.count == 3, parts[0].count == 4, parts[1].count == 2,+ parts[2].count == 2, let year = Int(parts[0]),+ let month = Int(parts[1]), let day = Int(parts[2]),+ year >= 1, year <= 9999 else { return nil }+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(secondsFromGMT: 0)!+ guard let date = calendar.date(from: DateComponents(year: year, month: month, day: day)),+ calendar.component(.year, from: date) == year,+ calendar.component(.month, from: date) == month,+ calendar.component(.day, from: date) == day else { return nil }+ return CivilDay(date, calendar: calendar)+ }+ }++ /// One action per logical `(workID, key)`. Identical physical duplicates+ /// are ignored; contradictory copies are a scoped data error.+ public let actions: [Action]++ public init(_ actions: [Action] = []) throws {+ var byKey: [UUID: [String: Action]] = [:]+ for action in actions {+ if let old = byKey[action.workID]?[action.key], old != action {+ throw HistoryError.conflictingAction(action.workID, action.key)+ }+ byKey[action.workID, default: [:]][action.key] = action+ }+ self.actions = byKey.values.flatMap(\.values).sorted {+ if $0.workID != $1.workID { return $0.workID.uuidString < $1.workID.uuidString }+ if $0.day != $1.day { return $0.day < $1.day }+ return $0.key < $1.key+ }+ }++ public func union(_ other: Self) throws -> Self {+ try Self(actions + other.actions)+ }++ public func clearKeys(workID: UUID, day: String) -> Set<String> {+ let scoped = actions.filter { $0.workID == workID && $0.day == day }+ return Set(scoped.filter { $0.kind == .clear }.map(\.key))+ .union(scoped.flatMap(\.observedClearKeys))+ }++ public func isMarked(workID: UUID, day: String) -> Bool {+ let clears = clearKeys(workID: workID, day: day)+ return actions.contains {+ $0.workID == workID && $0.day == day && $0.kind == .mark+ && clears.isSubset(of: Set($0.observedClearKeys))+ }+ }++ public func activeDays(for workID: UUID) -> Set<CivilDay> {+ let dates = Set(actions.filter { $0.workID == workID }.map(\.day))+ var active: Set<CivilDay> = []+ for date in dates where isMarked(workID: workID, day: date) {+ if let action = actions.first(where: { $0.workID == workID && $0.day == date }) {+ active.insert(action.civilDay)+ }+ }+ return active+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeIndex.swift b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeIndex.swiftnew file mode 100644index 00000000..da146d5e--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeIndex.swift@@ -0,0 +1,36 @@+import Foundation+import SwiftData++/// One table fetch, grouped by logical work identity. Physical duplicate rows+/// are folded by `NoEpisodeHistory`; contradictory copies remain a data error.+public struct NoEpisodeIndex {+ private let rowsByWorkID: [UUID: [NoEpisodeAction]]++ public init(context: ModelContext) throws {+ let rows = try context.fetch(FetchDescriptor<NoEpisodeAction>())+ rowsByWorkID = Dictionary(grouping: rows, by: \.workID)+ }++ public func history(for workID: UUID) throws -> NoEpisodeHistory {+ let actions = try (rowsByWorkID[workID] ?? []).map { row in+ let action = try NoEpisodeHistory.Action.decode(row.payloadData, workID: row.workID)+ guard action.key == row.key else { throw NoEpisodeHistory.HistoryError.invalidPayload }+ return action+ }+ return try NoEpisodeHistory(actions)+ }++ public var allActions: [NoEpisodeHistory.Action] {+ get throws {+ var actions: [NoEpisodeHistory.Action] = []+ for workID in rowsByWorkID.keys {+ actions.append(contentsOf: try history(for: workID).actions)+ }+ return actions.sorted {+ if $0.workID != $1.workID { return $0.workID.uuidString < $1.workID.uuidString }+ if $0.day != $1.day { return $0.day < $1.day }+ return $0.key < $1.key+ }+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swiftnew file mode 100644index 00000000..c78aba30--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift@@ -0,0 +1,162 @@+import Foundation+import SwiftData++/// Storage insertion for the caller's transaction. The caller owns save and+/// rollback; this helper never commits a partially validated history.+public enum NoEpisodeWriter {+ public static func facts(rows: [Entry], calendar: Calendar) -> Set<NoteFact> {+ // Today buckets Entry rows by Work before folding duplicate Entry UUIDs.+ // A split assignment may have a different latest share date on each+ // Work; taking one global max would clear the wrong date on one side.+ var latestByAssignment: [EntryWorkKey: Date] = [:]+ for row in rows {+ guard let workID = row.work?.id else { continue }+ let key = EntryWorkKey(entryID: row.id, workID: workID)+ if let latest = latestByAssignment[key], latest >= row.lastSharedAt { continue }+ latestByAssignment[key] = row.lastSharedAt+ }+ return Set(latestByAssignment.map { key, sharedAt in+ NoteFact(entryID: key.entryID, workID: key.workID,+ sharedAt: sharedAt, calendar: calendar)+ })+ }++ private struct EntryWorkKey: Hashable {+ let entryID: UUID+ let workID: UUID+ }++ @discardableResult+ public static func reconcileCurrentNotes(+ context: ModelContext, calendar: Calendar+ ) throws -> Bool {+ let rows = try context.fetch(FetchDescriptor<Entry>())+ let facts = facts(rows: rows, calendar: calendar)+ return try recordNoteTransition(before: facts, after: facts, context: context)+ }++ public struct NoteFact: Hashable {+ public let entryID: UUID+ public let workID: UUID+ public let sharedAt: Date+ public let day: CivilDay++ public init(entryID: UUID, workID: UUID, sharedAt: Date, calendar: Calendar) {+ self.entryID = entryID+ self.workID = workID+ self.sharedAt = MillisecondInstant.quantize(sharedAt)+ self.day = CivilDay(sharedAt, calendar: calendar)+ }++ public var stableKey: String {+ "note/\(entryID.uuidString)/\(workID.uuidString)/\(MillisecondInstant.milliseconds(sharedAt))/\(day)"+ }+ }++ /// Records both sides of a logical note mutation in the caller's transaction.+ /// A new destination always gets a fresh clear, including a repeated visit.+ @discardableResult+ public static func recordNoteTransition(+ before: Set<NoteFact>, after: Set<NoteFact>, context: ModelContext+ ) throws -> Bool {+ guard !before.isEmpty || !after.isEmpty else { return false }+ let index = try NoEpisodeIndex(context: context)+ let existing = Dictionary(grouping: try index.allActions) {+ ActionKey(workID: $0.workID, key: $0.key)+ }+ var actions: [NoEpisodeHistory.Action] = []+ let facts = before.union(after)+ for fact in facts {+ let key = ActionKey(workID: fact.workID, key: fact.stableKey)+ if let stored = existing[key]?.first {+ guard stored.kind == .clear && stored.day == fact.day.description else {+ throw NoEpisodeHistory.HistoryError.conflictingAction(fact.workID, fact.stableKey)+ }+ continue+ }+ actions.append(try .init(workID: fact.workID, key: fact.stableKey,+ day: fact.day.description, kind: .clear,+ observedClearKeys: []))+ }+ // A mark can have acknowledged the stable key. Clear that overlap before+ // a note leaves, so deleting or moving it never revives the mark.+ let beforeByScope = Dictionary(grouping: before) {+ Scope(workID: $0.workID, day: $0.day.description)+ }+ for (scope, scopedFacts) in beforeByScope {+ let history = try index.history(for: scope.workID)+ var clears = history.clearKeys(workID: scope.workID, day: scope.day)+ clears.formUnion(scopedFacts.map(\.stableKey))+ if history.actions.contains(where: {+ $0.day == scope.day && $0.kind == .mark+ && clears.isSubset(of: Set($0.observedClearKeys))+ }) {+ actions.append(try .init(workID: scope.workID, key: "clear/\(UUID().uuidString)",+ day: scope.day, kind: .clear, observedClearKeys: []))+ }+ }+ let priorAssignments = Set(before.map {+ NoteAssignment(entryID: $0.entryID, workID: $0.workID, day: $0.day)+ })+ for fact in after where !priorAssignments.contains(+ NoteAssignment(entryID: fact.entryID, workID: fact.workID, day: fact.day)) {+ actions.append(try .init(workID: fact.workID, key: "clear/\(UUID().uuidString)",+ day: fact.day.description, kind: .clear,+ observedClearKeys: []))+ }+ // The common unchanged pass has all stable keys and no overlap. It+ // must not re-fetch and decode the action table a second time.+ guard !actions.isEmpty else { return false }+ for action in actions {+ let key = ActionKey(workID: action.workID, key: action.key)+ if let prior = existing[key]?.first {+ guard prior == action else {+ throw NoEpisodeHistory.HistoryError.conflictingAction(action.workID, action.key)+ }+ continue+ }+ context.insert(NoEpisodeAction(workID: action.workID, key: action.key,+ payloadData: try action.canonicalData()))+ }+ return true+ }++ private struct ActionKey: Hashable {+ let workID: UUID+ let key: String+ }++ private struct Scope: Hashable {+ let workID: UUID+ let day: String+ }++ private struct NoteAssignment: Hashable {+ let entryID: UUID+ let workID: UUID+ let day: CivilDay+ }++ @discardableResult+ public static func insertMissing(+ _ actions: [NoEpisodeHistory.Action], context: ModelContext+ ) throws -> Bool {+ let incoming = try NoEpisodeHistory(actions)+ let rows = try context.fetch(FetchDescriptor<NoEpisodeAction>())+ let stored = try rows.map { row in+ let action = try NoEpisodeHistory.Action.decode(row.payloadData, workID: row.workID)+ guard action.key == row.key else { throw NoEpisodeHistory.HistoryError.invalidPayload }+ return action+ }+ let current = try NoEpisodeHistory(stored)+ _ = try current.union(incoming)+ let existing = Set(current.actions.map { "\($0.workID.uuidString)/\($0.key)" })+ var inserted = false+ for action in incoming.actions where !existing.contains("\(action.workID.uuidString)/\(action.key)") {+ context.insert(NoEpisodeAction(workID: action.workID, key: action.key,+ payloadData: try action.canonicalData()))+ inserted = true+ }+ return inserted+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swiftindex fa829b21..08ba0ae5 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: BackupV16Character) -> CharacterRecord {+ public static func make(imported record: BackupV17Character) -> CharacterRecord { ArchiveRecordBuilders.makeCharacter(record) } @@ -238,7 +238,7 @@ extension CharacterSuppression: SuppressionRow { evidence: evidence, status: status, actionAt: actionAt) } - public static func make(imported record: BackupV16Suppression) -> CharacterSuppression {+ public static func make(imported record: BackupV17Suppression) -> CharacterSuppression { ArchiveRecordBuilders.makeSuppression(record) } @@ -296,7 +296,7 @@ extension Place: RecordRow { timestamp: timestamp, workID: work?.id ?? UUID()) } - public static func make(imported record: BackupV16Place) -> Place {+ public static func make(imported record: BackupV17Place) -> Place { ArchiveRecordBuilders.makePlace(record) } @@ -349,7 +349,7 @@ extension PlaceSuppression: SuppressionRow { evidence: evidence, status: status, actionAt: actionAt) } - public static func make(imported record: BackupV16PlaceSuppression) -> PlaceSuppression {+ public static func make(imported record: BackupV17PlaceSuppression) -> PlaceSuppression { ArchiveRecordBuilders.makePlaceSuppression(record) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swiftindex 87634255..d040ab03 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift@@ -188,6 +188,9 @@ public struct WorkSnapshot: Equatable, Sendable { public let releaseDaysRaw: [String] /// Elected progress when read from a group; pristine on value-only fixtures. public let catchUp: CatchUpRecord+ /// Immutable mark/clear history for this logical Work. Repository reads+ /// supply it from the action index; value-only fixtures use `.empty`.+ public let noEpisodeHistory: NoEpisodeHistory public let titleProvenance: TitleProvenance public let createdAt: Date public let modifiedAt: Date@@ -270,7 +273,8 @@ public struct WorkSnapshot: Equatable, Sendable { // hand the editor a snapshot that reads as dirty the moment it loads. releaseDays: [ReleaseDay] = [], releaseDaysRaw: [String]? = nil,- catchUp: CatchUpRecord = .pristine+ catchUp: CatchUpRecord = .pristine,+ noEpisodeHistory: NoEpisodeHistory = .empty ) { // 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@@ -278,6 +282,7 @@ public struct WorkSnapshot: Equatable, Sendable { // — ``releaseDays`` reads back out of it. self.releaseDaysRaw = releaseDaysRaw ?? ReleaseDay.canonical(releaseDays).map(\.rawValue) self.catchUp = catchUp+ self.noEpisodeHistory = noEpisodeHistory self.thumbnail = thumbnail self.credits = credits self.workStatus = workStatus
diff --git a/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift b/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swiftindex 4ae6fbe1..17640691 100644--- a/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift@@ -311,6 +311,9 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { /// 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]+ /// Active marks under this publication's calendar, excluding dates with a+ /// currently matching note. The history itself stays on WorkSnapshot.+ public let noEpisodeDays: Set<CivilDay> /// The first membership's work URL, where it has one and it parses. public let primaryURL: URL? @@ -318,7 +321,7 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { id: UUID, title: String, primaryHostname: String, typeDisplay: WorkTypeDisplay, thumbnail: ThumbnailIdentity?, releaseDays: [ReleaseDay], notedDays: [NotedDay], catchUp: CatchUpRecord, numberedNotes: [NumberedNote], workStatus: WorkStatus,- primaryURL: URL? = nil+ primaryURL: URL? = nil, noEpisodeDays: Set<CivilDay> = [] ) { self.id = id self.title = title@@ -327,6 +330,7 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { self.thumbnail = thumbnail self.releaseDays = releaseDays self.notedDays = notedDays+ self.noEpisodeDays = noEpisodeDays.subtracting(notedDays.map(\.day)) self.catchUp = catchUp self.numberedNotes = numberedNotes self.workStatus = workStatus@@ -346,7 +350,8 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable { catchUp: snapshot.catchUp, numberedNotes: NumberedNote.from(snapshot.entries), workStatus: snapshot.workStatus,- primaryURL: snapshot.primaryURL)+ primaryURL: snapshot.primaryURL,+ noEpisodeDays: snapshot.noEpisodeHistory.activeDays(for: snapshot.id)) } /// One `NotedDay` per civil day, newest first, each naming the day's most@@ -491,8 +496,8 @@ public struct TodayDayPlan: Equatable, Sendable { 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)+ releaseDays: work.releaseDays, noEpisodeDays: work.noEpisodeDays,+ workStatus: work.workStatus, day: day, calendar: calendar) let unknownReadDay = countsReleases && progress.state == .unknown ? progress.readDay : nil let unknownLine: ReleaseRow.Line? =@@ -507,13 +512,16 @@ public struct TodayDayPlan: Equatable, Sendable { id: work.id, title: work.title, primaryHostname: work.primaryHostname, typeDisplay: work.typeDisplay, thumbnail: work.thumbnail, line: unknownLine ?? line(for: work, on: day, calendar: calendar),+ releaseState: work.notedDays.contains(where: { $0.day == day }) ? .noted+ : work.noEpisodeDays.contains(day) ? .noEpisode : .pending, progress: progress, workStatus: work.workStatus, lastChapter: progress.lastRead, lastNotedDay: unknownReadDay ?? latest?.day, releasesSince: countsReleases ? (unknownReadDay ?? latest?.day).flatMap { releaseCount(- of: work.releaseDays, after: $0, through: day, calendar: calendar)+ of: work.releaseDays, after: $0, through: day,+ noEpisodeDays: work.noEpisodeDays, calendar: calendar) } : nil, primaryURL: work.primaryURL) }@@ -527,7 +535,7 @@ public struct TodayDayPlan: Equatable, Sendable { /// counts once. static func releaseCount( of releaseDays: [ReleaseDay], after start: CivilDay, through end: CivilDay,- calendar: Calendar+ noEpisodeDays: Set<CivilDay> = [], calendar: Calendar ) -> Int? { guard !releaseDays.isEmpty else { return nil } let span = end.days(since: start, calendar: calendar)@@ -541,6 +549,9 @@ public struct TodayDayPlan: Equatable, Sendable { where due.contains((startIndex + offset) % 7) { count += 1 }+ count -= noEpisodeDays.filter {+ start < $0 && $0 <= end && due.contains($0.weekday(calendar: calendar).calendarWeekday - 1)+ }.count return count } @@ -588,6 +599,7 @@ public struct TodayDayPlan: Equatable, Sendable { /// One work due or being caught up on for the day being shown. public struct ReleaseRow: Equatable, Sendable, Identifiable {+ public enum ReleaseState: Equatable, Sendable { case pending, noted, noEpisode } /// The row's second line /// ([5.2](../../../../specs/update-schedule/requirements.md#5.2)). The arm /// picks the wording and the accent; the app spells it, because the spelling@@ -607,6 +619,8 @@ public struct ReleaseRow: Equatable, Sendable, Identifiable { public let typeDisplay: WorkTypeDisplay public let thumbnail: ThumbnailIdentity? public let line: Line+ public let releaseState: ReleaseState+ public var isCompleted: Bool { releaseState != .pending } public let progress: CatchUpProgress /// The author's status for the caught-up banner's primary action. public let workStatus: WorkStatus@@ -623,7 +637,8 @@ public struct ReleaseRow: Equatable, Sendable, Identifiable { public init( id: UUID, title: String, primaryHostname: String, typeDisplay: WorkTypeDisplay,- thumbnail: ThumbnailIdentity?, line: Line, progress: CatchUpProgress,+ thumbnail: ThumbnailIdentity?, line: Line,+ releaseState: ReleaseState = .pending, progress: CatchUpProgress, workStatus: WorkStatus, lastChapter: Int? = nil, lastNotedDay: CivilDay? = nil, releasesSince: Int? = nil, primaryURL: URL? = nil@@ -634,6 +649,7 @@ public struct ReleaseRow: Equatable, Sendable, Identifiable { self.typeDisplay = typeDisplay self.thumbnail = thumbnail self.line = line+ self.releaseState = releaseState self.progress = progress self.workStatus = workStatus self.lastChapter = lastChapter
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swiftindex f413330f..317b100d 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let result = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date())) - let decoded = try BackupV16Codec.decode(try Data(contentsOf: result.fileURL))+ let decoded = try BackupV17Codec.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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() 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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV17Metadata(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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV17Metadata(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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV17Metadata(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: BackupV16ExportError.self,+ throws: BackupV17ExportError.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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV17Metadata(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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV17Metadata(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.backupV16Snapshot() }+ let error = try await expectRefusal { _ = try await repository.backupV17Snapshot() } 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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let error = try await expectRefusal { _ = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV17Metadata(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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() 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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let result = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "1", exportedAt: Date()))+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date())) - let decoded = try BackupV16Codec.decode(try Data(contentsOf: result.fileURL))- #expect(decoded.backupFormatVersion == 16)- #expect(decoded.databaseSchemaVersion == 17)+ let decoded = try BackupV17Codec.decode(try Data(contentsOf: result.fileURL))+ #expect(decoded.backupFormatVersion == 17)+ #expect(decoded.databaseSchemaVersion == 18) #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 -> BackupV16ExportError {+ ) async throws -> BackupV17ExportError { do { try await body() Issue.record("expected a named refusal, but the export proceeded") return .snapshotFailed(reason: "no refusal")- } catch let error as BackupV16ExportError {+ } catch let error as BackupV17ExportError { 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: BackupV16Payload) throws -> ModelContext {- let encoded = try BackupV16Codec.encode(+ private static func importIntoEmptyStore(_ payload: BackupV17Payload) throws -> ModelContext {+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch))- let decoded = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch))+ let decoded = try BackupV17Codec.decode(encoded) - let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.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 be9d06c5..a260ea8a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift@@ -4,13 +4,13 @@ import Testing @testable import AsterismCore -/// The byte-for-byte pin on the 16/17 export (`remove-article-mode` Req 5.4).+/// The byte-for-byte pin on the deterministic 17/18 payload. /// /// 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 /// payload that re-encodes to different bytes still decodes to the same values. ///-/// So this suite asserts on the bytes. A library populating **every** payload+/// So this suite asserts on the literal payload's bytes. A library populating **every** payload /// array — including a two-site Work, a dismissed pair, an orphan membership, /// both coverage fingerprints, a series with a fractional position, an /// unresolved membership, an unresolved link, a merged creator, a removed role,@@ -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 16/17 for `remove-article-mode`.** A Site record lost its+/// The earlier 16/17 archive removed `remove-article-mode`'s Site field. 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 16/17 golden export", .serialized)+@Suite("Backup 17/18 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-16-17-golden.json")+ .appending(path: "Fixtures/backup-17-18-golden.json") } - /// Every array the 16/17 payload declares is non-empty, so the golden below is+ /// Every array the 17/18 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")@@ -59,6 +59,7 @@ struct BackupGoldenExportTests { #expect(!payload.entries.isEmpty) #expect(!payload.works.isEmpty)+ #expect(!payload.noEpisodeActions.isEmpty) #expect(!payload.sites.isEmpty) #expect(!payload.titlePatterns.isEmpty) #expect(!payload.urlRules.isEmpty)@@ -190,10 +191,13 @@ struct BackupGoldenExportTests { == 1) } - @Test("The 16/17 export of the golden library is byte-identical to the recorded archive")+ @Test("The literal 17/18 payload is byte-identical to the recorded archive") func exportIsByteIdenticalToTheRecordedArchive() async throws {- let payload = try await Self.exportedPayload()- let encoded = try BackupV16Codec.encode(+ // Importing a note creates a fresh clear UUID. Pin the literal complete+ // payload (including its action array) at the codec boundary; the real+ // export's additional occurrence clears are checked below.+ let payload = BackupGoldenLibrary.payload+ let encoded = try BackupV17Codec.encode( payload: payload, metadata: BackupGoldenLibrary.metadata) // Q22: every generation bump used to re-record the golden by hand from@@ -215,7 +219,7 @@ struct BackupGoldenExportTests { #expect( encoded == golden, """- the 16/17 export of the golden library no longer produces the recorded \+ the 17/18 literal payload 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) \@@ -223,15 +227,15 @@ struct BackupGoldenExportTests { """) } - /// The exported archive still decodes and still plans, so the golden is a+ /// The recorded archive still decodes and still plans, so the golden is a /// valid archive rather than merely a stable byte string. @Test("The recorded archive decodes and plans") func recordedArchiveDecodesAndPlans() throws { let golden = try Data(contentsOf: Self.goldenURL) let plan = try BackupImporter.plan(from: golden) - #expect(plan.metadata.formatVersion == 16)- #expect(plan.metadata.schemaVersion == 17)+ #expect(plan.metadata.formatVersion == 17)+ #expect(plan.metadata.schemaVersion == 18) #expect(plan.counts.entries == plan.metadata.entryCount) #expect(plan.counts.works == plan.metadata.workCount) }@@ -245,28 +249,27 @@ struct BackupGoldenExportTests { // (`rule-citation-by-uuid` Q23). /// Req 9.2, end to end: export, restore into an empty library, export again.- /// Byte-identical is the strongest form of "reproduces every record" there- /// is — a field the import dropped, re-derived or reordered shows up as a- /// different file rather than as a passing assertion about the half a suite- /// remembered to check.+ /// The restore creates new clear evidence for each arriving note, so the+ /// action array grows while every old action and every other record survives+ /// exactly. /// /// It is still only a statement about *record fidelity*: two libraries can /// re-export the same bytes and both be shapes the writer would refuse. So /// the restored library is also put through the strict validator, which is /// the only place in this suite a restored library is held to that bar since /// `recordedArchiveRestoresIntoAV9Library` went away (Q23).- @Test("An export imported into an empty library re-exports the same bytes")+ @Test("An export restored into an empty library retains every record and adds note clears") func exportImportExportIsByteIdentical() async throws {- let first = try BackupV16Codec.encode(- payload: try await Self.exportedPayload(), metadata: BackupGoldenLibrary.metadata)+ let source = try await Self.exportedPayload()+ let first = try BackupV17Codec.encode(+ payload: source, metadata: BackupGoldenLibrary.metadata) let target = try await M5Fixture() try await target.repository.confirmImport(plan: try BackupImporter.plan(from: first))- let second = try BackupV16Codec.encode(- payload: try await target.repository.backupV16Snapshot(),- metadata: BackupGoldenLibrary.metadata)+ let restored = try await target.repository.backupV17Snapshot() - #expect(second == first)+ try BackupV17RestoreAssertions.expectExactRecordsAndFreshNoteClears(+ before: source, after: restored) #expect(try await target.repository.strictDiagnoses().isEmpty) } @@ -275,7 +278,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 BackupV16Codec.encode(+ let archive = try BackupV17Codec.encode( payload: try await Self.exportedPayload(), metadata: BackupGoldenLibrary.metadata) let target = try await M5Fixture()@@ -292,17 +295,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 -> BackupV16Payload {+ private static func exportedPayload() async throws -> BackupV17Payload { let fixture = try await M5Fixture() let plan = try BackupImporter.plan(- from: try BackupV16Codec.encode(+ from: try BackupV17Codec.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.backupV16Snapshot()+ return try await fixture.repository.backupV17Snapshot() } } @@ -441,14 +444,14 @@ enum BackupGoldenLibrary { static let secondSiteWorkURL = "https://plain.example/works/actual-title" static let trimmedTitleSuffix = " - Trimmed Example" - static var metadata: BackupV16Metadata {- BackupV16Metadata(appBuild: "golden", exportedAt: created)+ static var metadata: BackupV17Metadata {+ BackupV17Metadata(appBuild: "golden", exportedAt: created) } // MARK: The archive - static var payload: BackupV16Payload {- BackupV16Payload(+ static var payload: BackupV17Payload {+ BackupV17Payload( entries: [notedEntry, plainEntry, trimmedEntry], works: [typedWork, foldedWork, legacyWork], sites: [taughtSite, plainSite, trimmedSite],@@ -472,7 +475,25 @@ enum BackupGoldenLibrary { links: [resolvedLink, unresolvedLink], creators: creators, creatorRoles: creatorRoles,- credits: credits)+ credits: credits,+ noEpisodeActions: noEpisodeActions)+ }++ static var noEpisodeActions: [BackupV17NoEpisodeAction] {+ let clearKey = "clear/10000000-0000-4000-8000-000000000001"+ let mark = try! NoEpisodeHistory.Action(+ workID: typedWork.id,+ key: "mark/10000000-0000-4000-8000-000000000002",+ day: "2026-09-29", kind: .mark,+ observedClearKeys: [clearKey])+ let clear = try! NoEpisodeHistory.Action(+ workID: typedWork.id, key: clearKey, day: "2026-09-29",+ kind: .clear, observedClearKeys: [])+ let orphan = try! NoEpisodeHistory.Action(+ workID: absentWorkID,+ key: "mark/10000000-0000-4000-8000-000000000003",+ day: "2026-09-30", kind: .mark, observedClearKeys: [])+ return [mark, clear, orphan].map { try! BackupV17NoEpisodeAction($0) } } // MARK: The creators, roles and credits@@ -480,7 +501,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: [BackupV16Creator] {+ private static var creators: [BackupV17Creator] { [ creator(id: creatorID, name: "Mori Ayane", notes: "Also draws."), creator(id: studioID, name: "Studio Lantern"),@@ -494,7 +515,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: [BackupV16CreatorRole] {+ private static var creatorRoles: [BackupV17CreatorRole] { CreatorRoleSeeding.seeds.map { role( id: $0.id, name: $0.name, position: $0.position,@@ -509,7 +530,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: [BackupV16Credit] {+ private static var credits: [BackupV17Credit] { [ credit( id: authorCreditID, workID: typedWorkID, creatorID: creatorID,@@ -526,8 +547,8 @@ enum BackupGoldenLibrary { private static func creator( id: UUID, name: String, notes: String = "", state: CreatorState = .active, canonicalID: UUID? = nil- ) -> BackupV16Creator {- BackupV16Creator(+ ) -> BackupV17Creator {+ BackupV17Creator( id: id, name: name, nameModifiedAt: created, notes: notes, notesModifiedAt: created, stateRaw: state.rawValue, stateModifiedAt: created, canonicalID: canonicalID, createdAt: created, modifiedAt: created)@@ -536,8 +557,8 @@ enum BackupGoldenLibrary { private static func role( id: UUID, name: String, position: Int, state: CreatorRoleState = .active, stamp: Date = created- ) -> BackupV16CreatorRole {- BackupV16CreatorRole(+ ) -> BackupV17CreatorRole {+ BackupV17CreatorRole( id: id, name: name, nameModifiedAt: stamp, position: position, positionModifiedAt: stamp, stateRaw: state.rawValue, stateModifiedAt: stamp, canonicalID: nil, createdAt: stamp, modifiedAt: stamp)@@ -545,40 +566,40 @@ enum BackupGoldenLibrary { private static func credit( id: UUID, workID: UUID, creatorID: UUID, roleIDs: [UUID]- ) -> BackupV16Credit {- BackupV16Credit(+ ) -> BackupV17Credit {+ BackupV17Credit( 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: BackupV16Series {- BackupV16Series(+ private static var series: BackupV17Series {+ BackupV17Series( 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: BackupV16Link {+ private static var resolvedLink: BackupV17Link { let ids = WorkDistinctPair.sortedIDs(typedWorkID, legacyWorkID)- return BackupV16Link(+ return BackupV17Link( 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: BackupV16Link {+ private static var unresolvedLink: BackupV17Link { let ids = WorkDistinctPair.sortedIDs(foldedWorkID, absentWorkID)- return BackupV16Link(+ return BackupV17Link( 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: BackupV16TitlePattern {- BackupV16TitlePattern(+ private static var pattern: BackupV17TitlePattern {+ BackupV17TitlePattern( id: patternID, siteHostname: taughtHost, version: 1, isActive: true, createdAt: created, definition: StoredPatternDefinition(@@ -586,8 +607,8 @@ enum BackupGoldenLibrary { } /// The second taught site's active rule, and the fixture's only `trimSuffix`.- private static var trimmedPattern: BackupV16TitlePattern {- BackupV16TitlePattern(+ private static var trimmedPattern: BackupV17TitlePattern {+ BackupV17TitlePattern( id: trimmedPatternID, siteHostname: trimmedHost, version: 1, isActive: true, createdAt: created, definition: StoredPatternDefinition(@@ -595,35 +616,35 @@ enum BackupGoldenLibrary { } /// A sequence-only query rule extracts "94" from the raw URL.- private static var rule: BackupV16URLRule {- BackupV16URLRule(+ private static var rule: BackupV17URLRule {+ BackupV17URLRule( id: ruleID, version: 1, isCurrent: true, createdAt: created, origin: .readerTaught, definition: .sequence(locator: .query(name: ExactScalarString("chapter"))), siteHostname: taughtHost) } - private static var taughtSite: BackupV16Site {- BackupV16Site(+ private static var taughtSite: BackupV17Site {+ BackupV17Site( hostname: taughtHost, displayName: "Golden", mode: .taught) } - private static var plainSite: BackupV16Site {- BackupV16Site(+ private static var plainSite: BackupV17Site {+ BackupV17Site( 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: BackupV16Site {- BackupV16Site(+ private static var trimmedSite: BackupV17Site {+ BackupV17Site( hostname: trimmedHost, displayName: "Trimmed", mode: .taught) } private static func workType( id: UUID, name: String, state: WorkTypeState = .active, canonicalID: UUID? = nil- ) -> BackupV16WorkType {- BackupV16WorkType(+ ) -> BackupV17WorkType {+ BackupV17WorkType( id: id, name: name, stateRaw: state.rawValue, canonicalID: canonicalID, createdAt: created, modifiedAt: created) }@@ -632,8 +653,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: BackupV16Membership {- BackupV16Membership(+ private static var taughtMembership: BackupV17Membership {+ BackupV17Membership( id: taughtMembershipID, workID: typedWorkID, hostname: taughtHost, createdAt: created, urlIdentity: workIdentity, urlIdentityState: .rule, urlIdentityRuleID: ruleID, workURLString: workURL)@@ -642,22 +663,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: BackupV16Membership {- BackupV16Membership(+ private static var secondSiteMembership: BackupV17Membership {+ BackupV17Membership( id: secondSiteMembershipID, workID: typedWorkID, hostname: plainHost, createdAt: created.addingTimeInterval(1), urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: secondSiteWorkURL) } - private static var plainMembership: BackupV16Membership {- BackupV16Membership(+ private static var plainMembership: BackupV17Membership {+ BackupV17Membership( id: plainMembershipID, workID: foldedWorkID, hostname: plainHost, createdAt: created, urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: nil) } - private static var trimmedMembership: BackupV16Membership {- BackupV16Membership(+ private static var trimmedMembership: BackupV17Membership {+ BackupV17Membership( id: trimmedMembershipID, workID: legacyWorkID, hostname: trimmedHost, createdAt: created, urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: nil)@@ -665,17 +686,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: BackupV16Membership {- BackupV16Membership(+ private static var orphanMembership: BackupV17Membership {+ BackupV17Membership( 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: BackupV16DistinctPair {+ private static var distinctPair: BackupV17DistinctPair { let ids = WorkDistinctPair.sortedIDs(typedWorkID, foldedWorkID)- return BackupV16DistinctPair(+ return BackupV17DistinctPair( id: distinctPairID, lowerWorkID: ids.lower, higherWorkID: ids.higher, recordedAt: created) }@@ -688,8 +709,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: BackupV16Work {- BackupV16Work(+ private static var typedWork: BackupV17Work {+ BackupV17Work( id: typedWorkID, displayTitle: workName, lastParsedTitle: workName, genericNotes: genericNotes, genreTags: ["fantasy"], titleProvenance: .parsed, workStatus: .hiatus, readingStatus: .abandoned,@@ -717,8 +738,8 @@ enum BackupGoldenLibrary { /// 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: BackupV16Work {- BackupV16Work(+ private static var foldedWork: BackupV17Work {+ BackupV17Work( id: foldedWorkID, displayTitle: "Plain Work", lastParsedTitle: nil, genericNotes: "", genreTags: [], titleProvenance: .manual, workStatus: .finished, readingStatus: .finished, verdict: "",@@ -731,8 +752,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: BackupV16Work {- BackupV16Work(+ private static var legacyWork: BackupV17Work {+ BackupV17Work( id: legacyWorkID, displayTitle: "A Standalone", lastParsedTitle: nil, genericNotes: "", genreTags: [], titleProvenance: .manual, workStatus: .ongoing, readingStatus: .reading, verdict: "",@@ -748,14 +769,14 @@ enum BackupGoldenLibrary { // MARK: The entries /// The v3 key embeds host + resolved Work name + sequence.- private static var notedEntry: BackupV16Entry {+ private static var notedEntry: BackupV17Entry { 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 BackupV16Entry(+ return BackupV17Entry( id: notedEntryID, captureTitle: titlePrefix + workName, captureTitleSource: .host, rawURL: rawURL, canonicalURL: nil, hostname: taughtHost, entryIdentityKey: key, conservativeIdentityKey: rawURL,@@ -774,9 +795,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: BackupV16Entry {+ private static var plainEntry: BackupV17Entry { let rawURL = "https://\(plainHost)/read/7"- return BackupV16Entry(+ return BackupV17Entry( id: plainEntryID, captureTitle: "Plain Work", captureTitleSource: .manual, rawURL: rawURL, canonicalURL: nil, hostname: plainHost, entryIdentityKey: rawURL, conservativeIdentityKey: rawURL,@@ -791,9 +812,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: BackupV16Entry {+ private static var trimmedEntry: BackupV17Entry { let rawURL = "https://\(trimmedHost)/posts/hello?utm_source=share"- return BackupV16Entry(+ return BackupV17Entry( id: trimmedEntryID, captureTitle: "A Standalone" + trimmedTitleSuffix, captureTitleSource: .host, rawURL: rawURL, canonicalURL: "https://\(trimmedHost)/posts/hello",@@ -808,8 +829,8 @@ enum BackupGoldenLibrary { // MARK: The characters - private static var guide: BackupV16Character {- BackupV16Character(+ private static var guide: BackupV17Character {+ BackupV17Character( id: guideID, workID: typedWorkID, name: "Grover", nameKey: "grover", aliases: ["Klar"], note: "The guide.", facts: [@@ -822,14 +843,14 @@ enum BackupGoldenLibrary { } /// The sync orphan: a character whose work has not arrived.- private static var orphan: BackupV16Character {- BackupV16Character(+ private static var orphan: BackupV17Character {+ BackupV17Character( id: orphanID, workID: nil, name: "The Stranger", nameKey: "the stranger", aliases: [], note: "", facts: [], createdAt: created, modifiedAt: created) } - private static var candidateSuppression: BackupV16Suppression {- BackupV16Suppression(+ private static var candidateSuppression: BackupV17Suppression {+ BackupV17Suppression( id: candidateSuppressionID, workID: typedWorkID, kindRaw: CharacterSuppressionKind.candidate.rawValue, nameKey: "the crowned one", sourceKindRaw: nil, sourceEntryID: nil, evidence: nil,@@ -837,8 +858,8 @@ enum BackupGoldenLibrary { } /// A fact suppression, which is the shape that carries a source and evidence.- private static var factSuppression: BackupV16Suppression {- BackupV16Suppression(+ private static var factSuppression: BackupV17Suppression {+ BackupV17Suppression( id: factSuppressionID, workID: typedWorkID, kindRaw: CharacterSuppressionKind.fact.rawValue, nameKey: "grover", sourceKindRaw: SourceRef.entry(notedEntryID).kindRaw, sourceEntryID: notedEntryID,@@ -850,8 +871,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: BackupV16Place {- BackupV16Place(+ private static var keep: BackupV17Place {+ BackupV17Place( id: keepID, workID: typedWorkID, name: "The High Keep", nameKey: "high keep", aliases: ["The Keep"], note: "The fortress above the pass.",@@ -866,15 +887,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: BackupV16Place {- BackupV16Place(+ private static var orphanPlace: BackupV17Place {+ BackupV17Place( id: orphanPlaceID, workID: absentWorkID, name: "The Drowned Road", nameKey: "drowned road", aliases: [], note: "", facts: [], createdAt: created, modifiedAt: created) } - private static var placeCandidateSuppression: BackupV16PlaceSuppression {- BackupV16PlaceSuppression(+ private static var placeCandidateSuppression: BackupV17PlaceSuppression {+ BackupV17PlaceSuppression( id: placeCandidateSuppressionID, workID: typedWorkID, kindRaw: CharacterSuppressionKind.candidate.rawValue, nameKey: "low road", sourceKindRaw: nil, sourceEntryID: nil, evidence: nil,@@ -883,8 +904,8 @@ enum BackupGoldenLibrary { /// The place fact suppression, which is the shape that carries a source and /// evidence.- private static var placeFactSuppression: BackupV16PlaceSuppression {- BackupV16PlaceSuppression(+ private static var placeFactSuppression: BackupV17PlaceSuppression {+ BackupV17PlaceSuppression( 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 a176116a..2313d8dd 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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }- let encoded = try BackupV16Codec.encode(+ let payload = try store.read { try LibraryRepository.projectV17Payload(context: $0) }+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ metadata: BackupV17Metadata(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 BackupV16Codec.decode(encoded)+ let decoded = try BackupV17Codec.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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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 BackupV16Codec.encode(+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))- _ = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ _ = try BackupV17Codec.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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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 BackupV16Codec.encode(+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))- _ = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ _ = try BackupV17Codec.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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) } } #expect(payload.count == 1)@@ -268,7 +268,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) } } #expect(payload.count == 2)@@ -288,7 +288,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) } } #expect(payload.count == 1)@@ -321,7 +321,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) } } #expect(payload.count == 1)@@ -357,7 +357,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) } } #expect(payload.count == 2)@@ -393,7 +393,7 @@ struct BackupGroupProjectionTests { try store.commit() let payload = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) } } #expect(payload.count == 2)@@ -414,7 +414,7 @@ struct BackupGroupProjectionTests { try store.commit() _ = try expectTornRefusal {- _ = try store.read { try LibraryRepository.projectV16Payload(context: $0) }+ _ = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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 BackupV16Codec.encode(+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))- _ = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ _ = try BackupV17Codec.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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(context: $0) } #expect(payload.titlePatterns.count == 1) #expect(payload.titlePatterns.first?.isActive == true)- let encoded = try BackupV16Codec.encode(+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))- _ = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+ _ = try BackupV17Codec.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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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.projectV16Payload(context: $0) }+ let payload = try store.read { try LibraryRepository.projectV17Payload(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 BackupV16ExportError {+ } catch let error as BackupV17ExportError { 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 0fbb67fa..d055b316 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() 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.backupV16Snapshot()+ let payload = try await sourceRepository.backupV17Snapshot() 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() 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.backupV16Snapshot()+ let payload = try await sourceRepository.backupV17Snapshot() 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.backupV16Snapshot()+ let exported = try await sourceRepository.backupV17Snapshot() 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: BackupV16Fixtures.entryID)+ let citations = try await targetRepository.citations(entryID: BackupV17Fixtures.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. ///- /// `BackupV16ArchiveTests` stops at a decode, which only proves the reference+ /// `BackupV17ArchiveTests` 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 = BackupV16Fixtures.duplicateVersionsPayload()+ let payload = BackupV17Fixtures.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: BackupV16Payload) -> [RuleRowFacts] {+ private static func expectedPatternRows(_ payload: BackupV17Payload) -> [RuleRowFacts] { payload.titlePatterns .map { RuleRowFacts(@@ -221,7 +221,7 @@ struct BackupGroupRoundTripTests { .sorted { $0.id.uuidString < $1.id.uuidString } } - private static func expectedURLRuleRows(_ payload: BackupV16Payload) -> [RuleRowFacts] {+ private static func expectedURLRuleRows(_ payload: BackupV17Payload) -> [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() -> BackupV16Payload {- let base = BackupV16Fixtures.composedPayload()+ private static func versionSpreadPayload() -> BackupV17Payload {+ let base = BackupV17Fixtures.composedPayload() let host = "example.com"- let retired = BackupV16Fixtures.created.addingTimeInterval(-60)+ let retired = BackupV17Fixtures.created.addingTimeInterval(-60) - let retiredPattern = BackupV16TitlePattern(+ let retiredPattern = BackupV17TitlePattern( id: UUID(uuidString: "cccccccc-cccc-cccc-cccc-ccccccccccc9")!, siteHostname: host, version: 9, isActive: false, createdAt: retired, definition: StoredPatternDefinition(definition: .wholeTitle))- let retiredRule = BackupV16URLRule(+ let retiredRule = BackupV17URLRule( 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 BackupV16Payload(+ return BackupV17Payload( 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: BackupV16Payload) -> BackupImportPlan {+ static func plan(_ payload: BackupV17Payload) -> 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 06b4027e..4fc4d916 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -692,7 +692,7 @@ private func createReadyEmptyV3Store(at configuration: LibraryConfiguration) thr ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV17MigrationPlan.self,+ migrationPlan: AsterismV18MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -706,7 +706,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -715,7 +715,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV17MigrationPlan.self,+ migrationPlan: AsterismV18MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -758,7 +758,7 @@ private func createReadySiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -767,7 +767,7 @@ private func createReadySiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV17MigrationPlan.self,+ migrationPlan: AsterismV18MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -802,7 +802,7 @@ private func createReadyDuplicateSiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -811,7 +811,7 @@ private func createReadyDuplicateSiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV17MigrationPlan.self,+ migrationPlan: AsterismV18MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -840,12 +840,12 @@ private func makeSiteDesignationPlan( patternVersion: Int = 1 ) throws -> BackupImportPlan { let epoch = Date(timeIntervalSince1970: 1_800_000_000)- let site = BackupV16Site(+ let site = BackupV17Site( hostname: hostname, displayName: displayName ?? hostname, mode: mode)- let patterns: [BackupV16TitlePattern] = activePattern+ let patterns: [BackupV17TitlePattern] = activePattern ? [- BackupV16TitlePattern(+ BackupV17TitlePattern( // 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 = BackupV16Site(+ let site = BackupV17Site( hostname: hostname, displayName: hostname, mode: .untaught)- let entries = (0..<entryCount).map { index -> BackupV16Entry in+ let entries = (0..<entryCount).map { index -> BackupV17Entry in let rawURL = "https://\(hostname)/read?chapter=\(index)"- return BackupV16Entry(+ return BackupV17Entry( 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 = BackupV16Entry(+ let entry = BackupV17Entry( id: entryID, captureTitle: "Imported Chapter", captureTitleSource: .networkFetch,@@ -960,7 +960,7 @@ private func makeMinimalImportPlan( workAssignment: .pattern(CitedRule(id: patternID))) ) - let work = BackupV16Work(+ let work = BackupV17Work( 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 = BackupV16Membership(+ let membership = BackupV17Membership( // 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 = BackupV16TitlePattern(+ let pattern = BackupV17TitlePattern( id: patternID, siteHostname: siteHostname, version: 1,@@ -1005,8 +1005,8 @@ private func makeMinimalImportPlan( ignored: [])) ) - let urlRules: [BackupV16URLRule] = includeURLRule ? [- BackupV16URLRule(+ let urlRules: [BackupV17URLRule] = includeURLRule ? [+ BackupV17URLRule( id: urlRuleID, version: 1, isCurrent: true,@@ -1022,7 +1022,7 @@ private func makeMinimalImportPlan( ) ] : [] - let site = BackupV16Site(+ let site = BackupV17Site( hostname: siteHostname, displayName: siteHostname, mode: .taught
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17ArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17ArchiveTests.swiftnew file mode 100644index 00000000..9ab8c091--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17ArchiveTests.swift@@ -0,0 +1,4008 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++// 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 16/17 archive is refused by+// version, naming the pair it declares (Req 5.3).+//+// 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+// also what heals a row whose stored digest had stopped matching its blob+// (Req 1.8). The records are otherwise 12/13's — a place table beside the+// character one, a Work carrying its series membership, its two statuses and its+// verdict, an Entry citation being the cited rule's UUID alone, a Work's site+// presence being a membership record, the reader's dismissed pairs and+// related-work links travelling beside it, the creators, roles and credits+// travelling whole, no parent record naming its children, and the coverage table+// folded onto the records that own it. It **replaces** 12/13 outright (Q5): a+// 12/13 file holds no cover, so the only thing this build could do with one is+// invent the absence of every cover the reader cropped.+//+// A place record is the character record with a **non-optional** `workID`: a+// place names its owner in a column rather than through a relationship, so+// "no owner" is a UUID nothing resolves rather than an absent one (Q60, Q67).+// An unresolvable `workID` is therefore kept on import and exported as it+// stands, where a character naming a work the file does not carry is a refusal.+//+// Three suites, because the generation has three surfaces and they fail+// differently: the codec answers for the wire shape and its refusals, the+// exporter for what the store projects into it, and the importer for what an+// archive does to a live library.++// MARK: - Codec++@Suite("Backup V15 codec")+struct BackupV17CodecTests {++ @Test("V16 encode/decode round-trips 16/17, the multi-site gate, and the seventeen arrays")+ func roundTrip() throws {+ let payload = BackupV17Fixtures.payload()++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.backupFormatVersion == 17)+ #expect(decoded.databaseSchemaVersion == 18)+ #expect(decoded.capabilityGate == "multi-site")+ #expect(decoded.payload == payload)+ #expect(decoded.payload.characters == payload.characters)+ #expect(decoded.payload.suppressions == payload.suppressions)+ #expect(decoded.payload.places == payload.places)+ #expect(decoded.payload.placeSuppressions == payload.placeSuppressions)+ #expect(decoded.payload.memberships == payload.memberships)+ // Req 9.4: the coverage table is gone and the fingerprints ride on the+ // records whose text they describe.+ #expect(+ decoded.payload.entries.first?.characterExtractionFingerprint+ == BackupV17Fixtures.noteFingerprint)+ #expect(+ decoded.payload.works.first?.genericNotesExtractionFingerprint+ == BackupV17Fixtures.genericNotesFingerprint)+ }++ /// Req 8.1. The two statuses travel as the typed enums, exactly as+ /// `titleProvenance` does, and the verdict as the reader's text — asserted+ /// after a real round-trip over a Work carrying all three off their+ /// 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 = BackupV17Fixtures.composedPayload()++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ let record = try #require(+ decoded.payload.works.first { $0.id == BackupV17Fixtures.composedWorkID })+ #expect(record.workStatus == .finished)+ #expect(record.readingStatus == .abandoned)+ #expect(record.verdict == "Dropped it at the timeskip.")+ #expect(decoded.payload.works == payload.works)+ }++ /// Every field of a character is on the wire, including the fact's citation+ /// and its immutable quote — asserted after a real round-trip rather than+ /// trusted to `Codable`.+ @Test("A character's facts, aliases, note and keys survive the round-trip")+ func characterFieldsRoundTrip() throws {+ let facts = [+ BackupV17Fixtures.fact(),+ BackupV17Fixtures.fact(+ statement: "Knows the way through the pass.",+ quote: "knows the way", source: .genericNotes),+ ]+ let payload = BackupV17Fixtures.payload(+ characters: [+ BackupV17Fixtures.character(aliases: ["Klar", "The Guide"], facts: facts)+ ])++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ let character = try #require(decoded.payload.characters.first)+ #expect(character.name == "Grover")+ #expect(character.nameKey == "grover")+ #expect(character.aliases == ["Klar", "The Guide"])+ #expect(character.note == "The guide.")+ #expect(character.facts.count == 2)+ #expect(character.facts.contains { $0.source == .genericNotes })+ #expect(character.facts.contains { $0.source == .entry(BackupV17Fixtures.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 = [+ BackupV17Fixtures.suppression(),+ BackupV17Fixtures.suppression(+ id: BackupV17Fixtures.factSuppressionID, kind: .fact, nameKey: "grover",+ source: .entry(BackupV17Fixtures.entryID), evidence: "promised to guide",+ status: .cleared),+ ]+ let payload = BackupV17Fixtures.payload(suppressions: rows)++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload.suppressions == rows)+ }++ // MARK: The two deliberate exemptions++ /// Q78: the exporter enumerates characters whole, so a character whose work+ /// has not arrived exports with a nil work reference rather than vanishing —+ /// and the validator has to let it through, or the backup refuses over a+ /// tolerated in-flight state (Req 6.7).+ @Test("A character with no work reference validates")+ func orphanCharacterValidates() throws {+ let payload = BackupV17Fixtures.payload(+ characters: [BackupV17Fixtures.character(id: BackupV17Fixtures.orphanID, workID: nil)])++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload.characters.first?.workID == nil)+ }++ /// Decision 2, pinned so it survives refactors: a fact's citation is+ /// tolerated when it dangles. The reader deleted the cited entry, or it has+ /// not synced — neither is corruption, and refusing here would fail the+ /// whole backup over routine curation.+ @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 = BackupV17Fixtures.payload(+ characters: [+ BackupV17Fixtures.character(facts: [BackupV17Fixtures.fact(source: .entry(absent))])+ ],+ suppressions: [+ BackupV17Fixtures.suppression(+ id: BackupV17Fixtures.factSuppressionID, kind: .fact, nameKey: "grover",+ source: .entry(absent), evidence: "gone")+ ])++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload.characters.first?.facts.first?.source == .entry(absent))+ #expect(decoded.payload.suppressions.first?.sourceEntryID == absent)+ }++ /// The other half of the character rule: optional, but **checked when+ /// present** — the `validateEntry` `workID` pattern.+ @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 = BackupV17Fixtures.payload(+ characters: [BackupV17Fixtures.character(workID: absent)])++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.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 = BackupV17Fixtures.payload(+ suppressions: [BackupV17Fixtures.suppression(workID: absent)])++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ // MARK: Payloads that contradict themselves++ @Test("Two records for one character identity refuse")+ func duplicateCharacterIDRefuses() throws {+ let payload = BackupV17Fixtures.payload(+ characters: [BackupV17Fixtures.character(), BackupV17Fixtures.character()])++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ @Test("Two records for one suppression identity refuse")+ func duplicateSuppressionIDRefuses() throws {+ let payload = BackupV17Fixtures.payload(+ suppressions: [BackupV17Fixtures.suppression(), BackupV17Fixtures.suppression()])++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ // MARK: The two place arrays (Req 5.1, 5.3)++ /// The place record is the character record with a non-optional `workID`, so+ /// every field has to survive the round trip the same way — asserted after a+ /// real encode/decode rather than trusted to the shared `Codable` shape.+ @Test("A place's facts, aliases, note and keys survive the round-trip")+ func placeFieldsRoundTrip() throws {+ let facts = [+ BackupV17Fixtures.fact(+ statement: "Sits above the pass.", quote: "above the pass",+ nameKey: "high keep"),+ BackupV17Fixtures.fact(+ statement: "Was abandoned after the siege.", quote: "abandoned after the siege",+ nameKey: "high keep", source: .genericNotes),+ ]+ let payload = BackupV17Fixtures.payload(+ places: [BackupV17Fixtures.place(aliases: ["The Keep"], facts: facts)])++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ let place = try #require(decoded.payload.places.first)+ #expect(place.workID == BackupV17Fixtures.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(BackupV17Fixtures.entryID) })+ }++ @Test("Both place-suppression kinds round-trip with their status and action time")+ func placeSuppressionKindsRoundTrip() throws {+ let rows = [+ BackupV17Fixtures.placeSuppression(),+ BackupV17Fixtures.placeSuppression(+ id: BackupV17Fixtures.placeFactSuppressionID, kind: .fact,+ nameKey: "high keep", source: .entry(BackupV17Fixtures.entryID),+ evidence: "above the pass", status: .cleared),+ ]+ let payload = BackupV17Fixtures.payload(placeSuppressions: rows)++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload.placeSuppressions == rows)+ }++ /// Q60 and Q67, on the wire. A place names its owner in a column, so the+ /// absence a character expresses with `nil` is a UUID nothing resolves —+ /// and the file has to carry it rather than refuse over it, or a sync orphan+ /// (Req 5.5) could never be backed up.+ @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 = BackupV17Fixtures.payload(+ places: [BackupV17Fixtures.place(id: BackupV17Fixtures.orphanPlaceID, workID: absent)],+ placeSuppressions: [BackupV17Fixtures.placeSuppression(workID: absent)])++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload.places.first?.workID == absent)+ #expect(decoded.payload.placeSuppressions.first?.workID == absent)+ }++ /// The half of the character rule the places keep: a payload holding two+ /// 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 = BackupV17Fixtures.payload(+ places: [BackupV17Fixtures.place(), BackupV17Fixtures.place()])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: duplicatePlaces, metadata: BackupV17Fixtures.metadata()))+ }++ let duplicateSuppressions = BackupV17Fixtures.payload(+ placeSuppressions: [+ BackupV17Fixtures.placeSuppression(), BackupV17Fixtures.placeSuppression(),+ ])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: duplicateSuppressions, metadata: BackupV17Fixtures.metadata()))+ }+ }++ /// The fourth thing a schema bump moves (Q66, phase 2 review). The three+ /// others fail loudly when they are forgotten — the store will not open, the+ /// snapshot will not compile, the marker refuses. A forgotten archive+ /// generation is silent: the app keeps exporting a file that *claims* to be+ /// taken from the previous schema and omits whatever the bump added. So the+ /// envelope's numbers are pinned to the live schema rather than restated.+ ///+ /// 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 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+ /// known issues again (Req 7.1).+ @Test("The archive's schema version is the live schema's, and the format is one below")+ func envelopeVersionsFollowTheLiveSchema() throws {+ #expect(+ BackupV17Document.schemaVersion == AsterismSchemaV18.versionIdentifier.major,+ """+ the archive declares schema \(BackupV17Document.schemaVersion) but the store \+ is at V\(AsterismSchemaV18.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(+ BackupV17Document.formatVersion == BackupV17Document.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)++ /// `BackupV17Site.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+ /// never is: restoring an unnameable mode as `untaught` would rewrite what+ /// the file says without saying so.+ ///+ /// 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 16/17 Site carrying a mode this build cannot name fails to decode")+ func siteWithAnUnknownModeRefuses() throws {+ let document = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.unknownSiteModePayloadJSON,+ entryCount: 1, workCount: 1)++ do {+ _ = try BackupV17Codec.decode(document)+ Issue.record("expected a decode refusal, but the document decoded")+ } catch let error as BackupCodecError {+ guard case .decodingFailed = error else {+ Issue.record("expected .decodingFailed, got \(error)")+ return+ }+ }++ // 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 = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.citationVersionFreePayloadJSON,+ entryCount: 1, workCount: 1)+ let site = try #require(try BackupV17Codec.decode(known).payload.sites.first)+ #expect(site.mode == .taught)+ }++ // MARK: The two Req 9.5 membership refusals++ /// Req 9.5, first half. An Entry's Work is in the file and holds no+ /// membership on the Entry's hostname: the restored library would start in+ /// exactly the state reconciliation exists to heal, and an archive has to be+ /// wholly legal on arrival (Q50).+ @Test("An Entry whose present Work has no membership on its hostname refuses")+ func entryWithoutAMembershipOnItsHostnameRefuses() throws {+ let base = BackupV17Fixtures.composedPayload()++ // The premise: with the membership present the payload is legal.+ _ = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: base, metadata: BackupV17Fixtures.metadata()))++ let uncovered = BackupV17Payload(+ 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 BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: uncovered, metadata: BackupV17Fixtures.metadata()))+ }+ guard case .unresolvedReference(let type, _, let reference) = error else {+ Issue.record("expected an unresolved reference, got \(String(describing: error))")+ return+ }+ #expect(type == "Entry")+ #expect(reference.contains("membership"))+ }++ /// Req 9.5, second half. Two memberships on one `(workID, hostname)` is a+ /// file that cannot say which row the Work is on — a state sync produces and+ /// 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 = BackupV17Fixtures.composedPayload()+ let twin = BackupV17Fixtures.membership(+ id: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee2")!,+ workID: BackupV17Fixtures.composedWorkID, hostname: "example.com")+ let payload = BackupV17Payload(+ 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 BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ guard case .invalidStateTuple(let type, _, let reason) = error else {+ Issue.record("expected an invalid state tuple, got \(String(describing: error))")+ return+ }+ #expect(type == "WorkSiteMembership")+ #expect(reason.contains("example.com"))+ }++ /// Req 9.5's tolerance, and Q22's: a membership or a pair naming a Work the+ /// archive does not carry is an orphan, not a contradiction. It imports+ /// unattached and re-attaches when the Work arrives.+ @Test("A membership and a pair naming an absent Work are accepted")+ func unattachedMembershipAndPairValidate() throws {+ let absent = UUID(uuidString: "DEADBEEF-0000-4000-8000-000000000010")!+ let other = UUID(uuidString: "DEADBEEF-0000-4000-8000-000000000011")!+ let base = BackupV17Fixtures.composedPayload()+ let orphan = BackupV17Fixtures.membership(+ id: UUID(uuidString: "0adbea00-0000-4000-8000-000000000001")!,+ workID: absent, hostname: "example.com")+ let ids = WorkDistinctPair.sortedIDs(absent, other)+ let payload = BackupV17Payload(+ entries: base.entries, works: base.works, sites: base.sites,+ titlePatterns: base.titlePatterns, urlRules: base.urlRules,+ workTypes: base.workTypes, memberships: base.memberships + [orphan],+ distinctPairs: [+ BackupV17DistinctPair(+ id: UUID(uuidString: "0adbea00-0000-4000-8000-000000000002")!,+ lowerWorkID: ids.lower, higherWorkID: ids.higher,+ recordedAt: BackupV17Fixtures.created)+ ])++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload.memberships.contains { $0.workID == absent })+ #expect(decoded.payload.distinctPairs.count == 1)+ }++ /// A membership's own tuple is checked whether or not its Work is here: the+ /// identity arms are the Work arm's, moved to the row that now holds the+ /// value (Req 1.2).+ @Test("A membership whose identity tuple contradicts itself refuses")+ func illegalMembershipTupleRefuses() throws {+ let base = BackupV17Fixtures.composedPayload()+ let illegal = BackupV17Membership(+ id: BackupV17Fixtures.composedMembershipID,+ workID: BackupV17Fixtures.composedWorkID, hostname: "example.com",+ createdAt: BackupV17Fixtures.created, urlIdentity: nil, urlIdentityState: .rule,+ urlIdentityRuleID: nil, workURLString: nil)+ let payload = BackupV17Payload(+ 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 BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ /// Q54 retired the membership's `(id, version)` **resolution**, not the+ /// site. A rule the archive carries is one this check can read the hostname+ /// of, and an identity derived on one site by another site's rule is a value+ /// 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 = BackupV17Fixtures.composedPayload()+ let otherHost = "other.example"+ let otherRuleID = UUID(uuidString: "dddddddd-dddd-dddd-dddd-ddddddddddd2")!+ let otherSite = BackupV17Site(+ hostname: otherHost, displayName: "Other", mode: .untaught)+ let otherRule = BackupV17URLRule(+ id: otherRuleID, version: 1, isCurrent: false, createdAt: BackupV17Fixtures.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 = BackupV17Fixtures.membership(+ id: BackupV17Fixtures.composedMembershipID,+ workID: BackupV17Fixtures.composedWorkID, hostname: "example.com",+ urlIdentity: "serial-9", urlIdentityState: .rule, urlIdentityRuleID: otherRuleID)+ let payload = BackupV17Payload(+ 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 BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ guard case .invalidStateTuple(let type, _, let reason) = error else {+ Issue.record("expected an invalid state tuple, got \(String(describing: error))")+ return+ }+ #expect(type == "WorkSiteMembership")+ #expect(reason.contains(otherHost))+ }++ /// The other half of Q54, and Q72: a membership whose cited rule the archive+ /// does not carry at all is **accepted**. There is no version to resolve and+ /// no hostname to compare; the row reads as `legacyUnverified` until the rule+ /// 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 = BackupV17Fixtures.composedPayload()+ let absentRule = UUID(uuidString: "dddddddd-dddd-dddd-dddd-ddddddddddd3")!+ let dangling = BackupV17Fixtures.membership(+ id: BackupV17Fixtures.composedMembershipID,+ workID: BackupV17Fixtures.composedWorkID, hostname: "example.com",+ urlIdentity: "serial-9", urlIdentityState: .rule, urlIdentityRuleID: absentRule)+ let payload = BackupV17Payload(+ entries: base.entries, works: base.works, sites: base.sites,+ titlePatterns: base.titlePatterns, urlRules: base.urlRules,+ workTypes: base.workTypes, memberships: [dangling])++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload.memberships.first?.urlIdentityRuleID == absentRule)+ }++ // MARK: Series and links (`series-and-related-works` Req 13.5)++ /// The whole V12 surface survives a real round trip: the series table, both+ /// works' membership pairs, and the link between them.+ @Test("Series, memberships and links round-trip through the codec")+ func seriesAndLinksRoundTrip() throws {+ let payload = BackupV17Fixtures.seriesPayload()++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload.series == payload.series)+ #expect(decoded.payload.links == payload.links)+ let first = try #require(+ decoded.payload.works.first { $0.id == BackupV17Fixtures.composedWorkID })+ #expect(first.seriesID == BackupV17Fixtures.seriesID)+ #expect(first.seriesPosition == 1)+ let second = try #require(+ decoded.payload.works.first { $0.id == BackupV17Fixtures.secondWorkID })+ #expect(second.seriesPosition == 2.5)+ }++ @Test("Two records for one series identity refuse")+ func duplicateSeriesIDRefuses() throws {+ let payload = BackupV17Fixtures.seriesPayload(+ series: [BackupV17Fixtures.seriesRecord(), BackupV17Fixtures.seriesRecord()])++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ @Test("Two records for one link identity refuse")+ func duplicateLinkIDRefuses() throws {+ let payload = BackupV17Fixtures.seriesPayload(+ links: [BackupV17Fixtures.linkRecord(), BackupV17Fixtures.linkRecord()])++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ /// Req 6.1 forbids a link from a work to itself, so a row saying otherwise+ /// is not a link a reader can have meant. The export filters the shape out+ /// before a file exists; this answers for an archive written elsewhere.+ @Test("A link naming one work twice refuses")+ func selfLinkRefuses() throws {+ let payload = BackupV17Fixtures.seriesPayload(+ links: [+ BackupV17Fixtures.linkRecord(+ a: BackupV17Fixtures.composedWorkID, b: BackupV17Fixtures.composedWorkID)+ ])++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ /// Req 13.2: the archive carries the logical library, so a pair holds one+ /// link. Two would be a file the next reconcile pass would immediately+ /// halve — which is exactly what an archive may not contain.+ @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 = BackupV17Fixtures.seriesPayload(+ links: [+ BackupV17Fixtures.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.+ BackupV17Fixtures.linkRecord(+ id: second, a: BackupV17Fixtures.secondWorkID,+ b: BackupV17Fixtures.composedWorkID, type: "sequel"),+ ])++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ @Test("A series with an empty trimmed name refuses")+ func emptySeriesNameRefuses() throws {+ for name in ["", " ", "\n\t "] {+ let payload = BackupV17Fixtures.seriesPayload(+ series: [BackupV17Fixtures.seriesRecord(name: name)])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }+ }++ /// 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. Neither+ /// half-set shape is one a writer produces — both arrive through CloudKit's+ /// per-field merge — and neither may enter through a file.+ @Test("A half-set membership pair refuses, either half")+ func halfSetMembershipRefuses() throws {+ let halves: [(UUID?, Double?)] = [+ (BackupV17Fixtures.seriesID, nil),+ (nil, 2),+ ]+ for (id, position) in halves {+ let payload = BackupV17Fixtures.payloadWithMembership(+ seriesID: id, position: position)+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }+ }++ /// Q15's storage rule, refused rather than rounded: rounding here would move+ /// a reader's 2.55 to 2.6 inside their own restore.+ @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 = BackupV17Fixtures.payloadWithMembership(+ seriesID: BackupV17Fixtures.seriesID, position: position)+ #expect(throws: (any Error).self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }+ }++ /// The tolerated half (Req 13.5, 11.2): neither reference resolves against+ /// the payload. A work naming a series the archive does not carry and a link+ /// naming a work it does not carry are both states sync produces, and+ /// refusing a whole backup over one would fail it for a library that is+ /// merely mid-hydration.+ @Test("A work naming an absent series and a link naming an absent work validate")+ func unresolvedReferencesValidate() throws {+ let absentSeries = UUID(uuidString: "5E81E5A0-0000-4000-8000-000000000009")!+ let absentWork = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee99")!+ let payload = BackupV17Fixtures.seriesPayload(+ links: [+ BackupV17Fixtures.linkRecord(+ a: BackupV17Fixtures.composedWorkID, b: absentWork, type: "spin-off")+ ],+ firstMembership: (absentSeries, 3))++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(+ decoded.payload.works.contains {+ $0.id == BackupV17Fixtures.composedWorkID && $0.seriesID == absentSeries+ })+ #expect(+ decoded.payload.links.contains {+ $0.lowerWorkID == absentWork || $0.higherWorkID == absentWork+ })+ }++ /// A link's pair is unordered, so it has one spelling — and the payload+ /// imposes it at the door rather than trusting the file, exactly as it does+ /// for a dismissed pair. Without it `dedupeLinks`, which groups on the+ /// sorted form, would never match the row.+ @Test("A link's ids are sorted at the door")+ func linkIDsAreSortedAtTheDoor() throws {+ let ids = WorkDistinctPair.sortedIDs(+ BackupV17Fixtures.composedWorkID, BackupV17Fixtures.secondWorkID)+ let reversed = BackupV17Fixtures.linkRecord(a: ids.higher, b: ids.lower)+ #expect(reversed.lowerWorkID == ids.higher)++ let payload = BackupImportPayload(BackupV17Fixtures.seriesPayload(links: [reversed]))+ #expect(payload.links.map(\.lowerWorkID) == [ids.lower])+ #expect(payload.links.map(\.higherWorkID) == [ids.higher])+ }++ // MARK: Creators, roles and credits (`work-creators` Req 9.1, 9.5)++ /// Req 9.1: every field of the three new record kinds is on the wire —+ /// including the **per-field** modification times the directory fold reads+ /// (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 = BackupV17Fixtures.creditsPayload()++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.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 == BackupV17Fixtures.aliasID })+ #expect(alias.stateRaw == CreatorState.merged.rawValue)+ #expect(alias.canonicalID == BackupV17Fixtures.moriID)++ let mori = try #require(+ decoded.payload.creators.first { $0.id == BackupV17Fixtures.moriID })+ #expect(mori.notes == "Also draws.")+ #expect(mori.nameModifiedAt == BackupV17Fixtures.created)+ #expect(mori.notesModifiedAt == BackupV17Fixtures.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 == BackupV17Fixtures.authorRoleID })+ #expect(author.position == 0)+ #expect(author.nameModifiedAt == BackupV17Fixtures.pristine)+ #expect(author.positionModifiedAt == BackupV17Fixtures.pristine)++ let letterer = try #require(+ decoded.payload.creatorRoles.first { $0.id == BackupV17Fixtures.lettererRoleID })+ #expect(letterer.position == 3)+ let editor = try #require(+ decoded.payload.creatorRoles.first { $0.id == BackupV17Fixtures.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 == BackupV17Fixtures.moriCreditID })+ #expect(credit.roleIDs.contains(BackupV17Fixtures.editorRoleID.uuidString))+ }++ @Test(+ "Two records for one creator, role or credit identity refuse",+ arguments: [0, 1, 2])+ func duplicateDirectoryIDsRefuse(table: Int) throws {+ let payload: BackupV17Payload+ switch table {+ case 0:+ payload = BackupV17Fixtures.creditsPayload(+ creators: BackupV17Fixtures.creatorRecords+ + [BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane")])+ case 1:+ payload = BackupV17Fixtures.creditsPayload(+ creatorRoles: BackupV17Fixtures.creatorRoleRecords+ + [BackupV17Fixtures.creatorRoleRecord(+ id: BackupV17Fixtures.lettererRoleID, name: "letterer", position: 9)])+ default:+ payload = BackupV17Fixtures.creditsPayload(+ credits: BackupV17Fixtures.creditRecords+ + [BackupV17Fixtures.creditRecord(+ id: BackupV17Fixtures.moriCreditID,+ workID: BackupV17Fixtures.secondWorkID,+ creatorID: BackupV17Fixtures.studioID)])+ }++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ /// Req 9.2: the archive carries the logical library, so a name the next+ /// convergence pass would elect over is a file this build never writes and+ /// never accepts. Creators are keyed on *active* records; roles on active+ /// **and removed** ones, because a removed role is what Req 2.2 restores by+ /// name.+ @Test("Two active creators, or two visible roles, with one normalized name refuse")+ func normalizedNameCollisionsRefuse() throws {+ let creators = BackupV17Fixtures.creditsPayload(+ creators: BackupV17Fixtures.creatorRecords+ + [BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.absentCreatorID, name: "MORI AYANE")])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: creators, metadata: BackupV17Fixtures.metadata()))+ }++ // Active against removed: the pair Req 2.2's restore could not choose+ // between.+ let roles = BackupV17Fixtures.creditsPayload(+ creatorRoles: BackupV17Fixtures.creatorRoleRecords+ + [BackupV17Fixtures.creatorRoleRecord(+ id: BackupV17Fixtures.absentRoleID, name: "Editor", position: 5)])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: roles, metadata: BackupV17Fixtures.metadata()))+ }+ }++ /// Req 9.5: a merged record has to name a survivor the file carries, and one+ /// that is not itself merged — a restored library cannot read an alias chain+ /// whose end is missing, and the exporter is required to have collapsed one+ /// whose end is another alias (Q33).+ @Test("A merged record naming an absent or merged survivor refuses")+ func brokenAliasChainsRefuse() throws {+ let absentSurvivor = BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane"),+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.aliasID, name: "mori ayane", state: .merged,+ canonicalID: BackupV17Fixtures.absentCreatorID),+ ])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: absentSurvivor, metadata: BackupV17Fixtures.metadata()))+ }++ let chain = BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane"),+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.studioID, name: "mori ayane 2", state: .merged,+ canonicalID: BackupV17Fixtures.moriID),+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.aliasID, name: "mori ayane", state: .merged,+ canonicalID: BackupV17Fixtures.studioID),+ ])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: chain, metadata: BackupV17Fixtures.metadata()))+ }++ let roleChain = BackupV17Fixtures.creditsPayload(+ creatorRoles: BackupV17Fixtures.creatorRoleRecords+ + [BackupV17Fixtures.creatorRoleRecord(+ id: BackupV17Fixtures.absentRoleID, name: "letters", position: 6,+ state: .merged, canonicalID: BackupV17Fixtures.absentCreatorID)])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: roleChain, metadata: BackupV17Fixtures.metadata()))+ }+ }++ /// Req 9.5, read **as stored**: the pair the file spells, before any alias+ /// chase. Two records over one pair is a file the next dedupe would halve,+ /// and a role identifier held twice is the one shape `dedupeCredits` repairs+ /// and no writer produces (Q65).+ @Test("Two credits over one pair, and a repeated role identifier, refuse")+ func malformedCreditsRefuse() throws {+ let pair = BackupV17Fixtures.creditsPayload(+ credits: BackupV17Fixtures.creditRecords+ + [BackupV17Fixtures.creditRecord(+ id: BackupV17Fixtures.absentRoleID,+ workID: BackupV17Fixtures.composedWorkID,+ creatorID: BackupV17Fixtures.moriID,+ roleIDs: [BackupV17Fixtures.artistRoleID])])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: pair, metadata: BackupV17Fixtures.metadata()))+ }++ let repeated = BackupV17Fixtures.creditsPayload(+ credits: [+ BackupV17Credit(+ id: BackupV17Fixtures.moriCreditID,+ workID: BackupV17Fixtures.composedWorkID,+ creatorID: BackupV17Fixtures.moriID,+ roleIDs: [+ BackupV17Fixtures.authorRoleID.uuidString,+ BackupV17Fixtures.authorRoleID.uuidString,+ ],+ createdAt: BackupV17Fixtures.created,+ modifiedAt: BackupV17Fixtures.created)+ ])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: repeated, metadata: BackupV17Fixtures.metadata()))+ }+ }++ @Test("A creator or role with an empty trimmed name refuses")+ func emptyDirectoryNamesRefuse() throws {+ for name in ["", " ", "\n\t "] {+ let creators = BackupV17Fixtures.creditsPayload(+ creators: [BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: name)],+ credits: [])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: creators, metadata: BackupV17Fixtures.metadata()))+ }++ let roles = BackupV17Fixtures.creditsPayload(+ creatorRoles: [BackupV17Fixtures.creatorRoleRecord(+ id: BackupV17Fixtures.lettererRoleID, name: name, position: 3)],+ credits: [])+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(+ payload: roles, metadata: BackupV17Fixtures.metadata()))+ }+ }+ }++ /// Req 9.5's tolerated half: a credit's work, creator and roles resolve+ /// **nothing**. Each of the three is indistinguishable from a target still+ /// in transit, and refusing a whole backup over one would fail it for a+ /// library that is merely mid-sync (Req 10.2).+ @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 = BackupV17Fixtures.creditsPayload(+ credits: [+ BackupV17Fixtures.creditRecord(+ id: BackupV17Fixtures.orphanCreditID, workID: absentWork,+ creatorID: BackupV17Fixtures.absentCreatorID,+ roleIDs: [BackupV17Fixtures.absentRoleID])+ ])++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ let credit = try #require(decoded.payload.credits.first)+ #expect(credit.workID == absentWork)+ #expect(credit.creatorID == BackupV17Fixtures.absentCreatorID)+ #expect(credit.roleIDs == [BackupV17Fixtures.absentRoleID.uuidString])+ }++ // MARK: The citation arms++ /// Q26: the identity *basis version* is a case now, so the arm the reference+ /// checks open on is the case rather than an integer column. A v3 arm with no+ /// name contributor is the shape the old `identityKeyVersion == 3` branch+ /// refused, and it still refuses.+ @Test("A composed identity with no name contributor refuses")+ func composedIdentityWithoutANameContributorRefuses() throws {+ let payload = BackupV17Fixtures.composedPayload(dropNameContributor: true)++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ /// The other side of the same switch: a `.urlRule` basis whose blob says+ /// `.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 = BackupV17Fixtures.composedPayload()+ let entry = try #require(base.entries.first)+ let stripped = BackupV17Entry(+ id: entry.id, captureTitle: entry.captureTitle,+ captureTitleSource: entry.captureTitleSource, rawURL: entry.rawURL,+ canonicalURL: entry.canonicalURL, hostname: entry.hostname,+ entryIdentityKey: entry.entryIdentityKey,+ conservativeIdentityKey: entry.conservativeIdentityKey,+ identityBasis: .urlRule, urlWorkIdentity: entry.urlWorkIdentity,+ chapterSequence: entry.chapterSequence, chapterTitle: entry.chapterTitle,+ note: entry.note, rating: entry.rating, firstCapturedAt: entry.firstCapturedAt,+ lastSharedAt: entry.lastSharedAt, modifiedAt: entry.modifiedAt,+ workID: entry.workID, intentionallyUnattached: entry.intentionallyUnattached,+ citations: EntryCitations(identity: .rawURL))+ let payload = BackupV17Payload(+ 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 BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))+ }+ }++ @Test("A mismatched version pair around 16/17 is refused by the codec itself")+ func mismatchedPairsRefuse() throws {+ let encoded = try BackupV17Codec.encode(+ payload: BackupV17Fixtures.payload(), metadata: BackupV17Fixtures.metadata())+ var object = try #require(+ try JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ object["databaseSchemaVersion"] = 9++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(try JSONSerialization.data(withJSONObject: object))+ }+ }++ /// `remove-article-mode` Req 5.3 through the codec: a 14/15 envelope is the+ /// pair this generation replaced (Q2, Q12), and it is refused at the door+ /// rather than half-decoded — so nothing it carries can reach a library.+ @Test("A 14/15 envelope is refused by the codec")+ func retiredEnvelopeRefuses() throws {+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(BackupV17Fixtures.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 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 16/17 archive whose citation carries a version fails the checksum")+ func citationVersionFailsTheChecksum() throws {+ let document = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.citationVersionPayloadJSON, entryCount: 1, workCount: 1)++ do {+ _ = try BackupV17Codec.decode(document)+ Issue.record("expected a checksum refusal, but the document decoded")+ } catch let error as BackupCodecError {+ guard case .checksumMismatch = error else {+ Issue.record("expected .checksumMismatch, got \(error)")+ return+ }+ }++ let versionFree = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+ let decoded = try BackupV17Codec.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 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.+ ///+ /// The refusal is a decode failure, not a checksum one — the typed decode+ /// 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 16/17 Work record omitting the three status fields fails to decode")+ func workOmittingTheStatusFieldsRefuses() throws {+ let document = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.statusFieldsOmittedPayloadJSON, entryCount: 1, workCount: 1)++ do {+ _ = try BackupV17Codec.decode(document)+ Issue.record("expected a decode refusal, but the document decoded")+ } catch let error as BackupCodecError {+ guard case .decodingFailed = error else {+ Issue.record("expected .decodingFailed, got \(error)")+ return+ }+ }++ let complete = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+ let record = try #require(try BackupV17Codec.decode(complete).payload.works.first)+ #expect(record.workStatus == .ongoing)+ #expect(record.readingStatus == .reading)+ #expect(record.verdict.isEmpty)+ }++ /// 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 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 16/17 payload without the two place arrays fails to decode")+ func payloadOmittingThePlaceArraysRefuses() throws {+ let document = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.placeArraysOmittedPayloadJSON, entryCount: 1, workCount: 1)++ do {+ _ = try BackupV17Codec.decode(document)+ Issue.record("expected a decode refusal, but the document decoded")+ } catch let error as BackupCodecError {+ guard case .decodingFailed = error else {+ Issue.record("expected .decodingFailed, got \(error)")+ return+ }+ }++ // And the identical literal carrying the two empty arrays decodes, so+ // the refusal is about them rather than about the paste.+ let complete = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+ let decoded = try BackupV17Codec.decode(complete)+ #expect(decoded.payload.places.isEmpty)+ #expect(decoded.payload.placeSuppressions.isEmpty)+ }++ /// Q51's line, from the malformed side: a `thumbnail` field whose base64+ /// does not decode refuses the **whole** archive.+ ///+ /// Req 8.4's tolerance is for bytes that decode as `Data` and are not a+ /// JPEG of the declared shape — a record this build cannot use, imported+ /// without its cover and named in the report. A field that is not base64 at+ /// all never becomes a record: the document does not parse, and there is+ /// nothing to be tolerant about. The two answers are consistent because the+ /// 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 BackupV17Codec.encode(+ payload: BackupV17Fixtures.coveredPayload(),+ metadata: BackupV17Fixtures.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.+ let field = try #require(+ text.range(of: "\"thumbnail\"\\s*:\\s*\"[^\"]+\"", options: .regularExpression))+ let corrupted = text.replacingCharacters(+ in: field, with: "\"thumbnail\":\"not base64 @@@@\"")++ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.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 BackupV17Codec.decode(encoded).payload.works.first?.thumbnail != nil)+ }++ /// Req 3.2: the version invariants are retired, so an archive whose Site+ /// holds two title patterns at version 1 and a current URL rule below a+ /// 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 = BackupV17Fixtures.duplicateVersionsPayload()++ let decoded = try BackupV17Codec.decode(+ try BackupV17Codec.encode(payload: payload, metadata: BackupV17Fixtures.metadata()))++ #expect(decoded.payload == payload)+ #expect(decoded.payload.titlePatterns.map(\.version) == [1, 1])+ #expect(decoded.payload.urlRules.first(where: \.isCurrent)?.version == 2)+ }+}++// MARK: - Export++@Suite("Backup V15 export", .serialized)+struct BackupV17ExportTests {+ 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")!+ private static let characterID = UUID(uuidString: "60000000-0000-4000-8000-000000000003")!+ private static let orphanID = UUID(uuidString: "60000000-0000-4000-8000-000000000004")!+ private static let roleID = UUID(uuidString: "60000000-0000-4000-8000-000000000005")!+ private static let placeID = UUID(uuidString: "60000000-0000-4000-8000-000000000006")!+ private static let orphanPlaceID = UUID(uuidString: "60000000-0000-4000-8000-000000000007")!+ /// The work id an orphan place names and no row answers for — the tolerated+ /// non-resolving owner of Req 5.5, which the archive has to carry verbatim.+ private static let absentWorkID = UUID(uuidString: "60000000-0000-4000-8000-0000000000e1")!+ private static let early = Date(timeIntervalSince1970: 1_000_000)+ 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 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 = BackupV17Fixtures.payload()+ let exporter = BackupV17Exporter(+ repository: MockV15SnapshotProvider(payload: payload), stagingDirectory: tempDir)+ let result = try await exporter.export(metadata: BackupV17Fixtures.metadata())++ #expect(result.fileURL.lastPathComponent.contains("v17"))+ let decoded = try BackupV17Codec.decode(try Data(contentsOf: result.fileURL))+ #expect(decoded.backupFormatVersion == 17)+ #expect(decoded.databaseSchemaVersion == 18)+ #expect(decoded.payload == payload)+ exporter.cleanup(result)+ }++ // MARK: - The cover (`work-thumbnails` Req 8.1, 8.3)++ /// Req 8.1 on the way out: the shape's raw spelling and the bytes reach the+ /// record, and the **digest does not reach the file at all**.+ ///+ /// 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 `BackupV17Work` 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")+ func coverProjectsOntoTheRecord() throws {+ let store = try LibraryStore()+ store.setThumbnail(+ shapeRaw: ThumbnailShape.portrait.rawValue,+ bytes: BackupV17Fixtures.coverBytes, digest: BackupV17Fixtures.coverDigest)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ let record = try #require(payload.works.first { $0.id == Self.workID })+ #expect(record.thumbnailShape == ThumbnailShape.portrait.rawValue)+ #expect(record.thumbnail == BackupV17Fixtures.coverBytes)++ let encoded = try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ let text = try #require(String(data: encoded, encoding: .utf8))+ #expect(!text.contains("thumbnailDigest"))+ #expect(!text.contains(BackupV17Fixtures.coverDigest))+ }++ /// Decision 3: a cover the reader zoomed out on is stored shorter than its+ /// box, and the export has to carry it rather than refuse it. This is the+ /// state that would have refused before — present bytes that are not+ /// 600×900 — and the whole reason the box literal became+ /// `ThumbnailShape.accepts`.+ @Test("A cover stored shorter than its box exports like any other")+ func gappedCoverProjectsOntoTheRecord() throws {+ let store = try LibraryStore()+ store.setThumbnail(+ shapeRaw: ThumbnailShape.portrait.rawValue,+ bytes: BackupV17Fixtures.gappedCoverBytes,+ digest: BackupV17Fixtures.gappedCoverDigest)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ let record = try #require(payload.works.first { $0.id == Self.workID })+ #expect(record.thumbnailShape == ThumbnailShape.portrait.rawValue)+ #expect(record.thumbnail == BackupV17Fixtures.gappedCoverBytes)+ }++ /// Req 8.3 as Q52 amends it, and the one cover state that must **not**+ /// refuse: a row carrying the identity with no bytes behind it — a record+ /// whose asset has not arrived, which Req 1.8 tolerates. There is nothing to+ /// validate and nothing to carry, so the work exports with no cover rather+ /// than making the library unbackupable.+ @Test("A row with an identity and no bytes exports with no cover")+ func anIdentityWithoutBytesExportsWithNoCover() throws {+ let store = try LibraryStore()+ store.setThumbnail(+ shapeRaw: ThumbnailShape.square.rawValue, bytes: nil, digest: "never-arrived")+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ let record = try #require(payload.works.first { $0.id == Self.workID })+ #expect(record.thumbnailShape == nil)+ #expect(record.thumbnail == nil)+ }++ /// Q79, the state reading only the carrier row got wrong: the identity on+ /// the carrier, the bytes on a sibling of the same group.+ ///+ /// It is a **resting** state, not a transient one. The silent fold writes a+ /// cover only onto rows whose identity differs (Req 1.11), so once the+ /// carrier's two presence columns say what the sibling's say, no pass will+ /// ever copy the sibling's blob across — and the row whose asset arrived is+ /// the only row that holds the picture. Exporting the carrier's `nil` here+ /// wrote a coverless work into the backup and said nothing about it.+ @Test("A split group exports the cover from whichever row holds the bytes")+ func splitGroupExportsTheRowThatHoldsTheBytes() throws {+ let store = try LibraryStore()+ store.setThumbnail(+ shapeRaw: ThumbnailShape.portrait.rawValue, bytes: nil,+ digest: BackupV17Fixtures.coverDigest)+ store.insertSiblingRow(+ shapeRaw: ThumbnailShape.portrait.rawValue, bytes: BackupV17Fixtures.coverBytes,+ digest: BackupV17Fixtures.coverDigest)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(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 == BackupV17Fixtures.coverBytes)+ }++ /// The same shape with the carrier holding **stale** bytes: the cover the+ /// reader replaced, or a half-written asset. Two things are pinned at once —+ /// the scan walks past a row whose blob does not hash to the identity's+ /// digest, and the Req 8.3 refusal is asked of the row the scan picks (Q79)+ /// rather than of every row, which is what used to refuse the whole export+ /// over bytes no record was going to carry.+ @Test("Stale bytes on the carrier neither travel nor refuse the export")+ func splitGroupWalksPastStaleCarrierBytes() throws {+ let store = try LibraryStore()+ let stale = Data("the cover this work used to have".utf8)+ store.setThumbnail(+ shapeRaw: ThumbnailShape.portrait.rawValue, bytes: stale,+ digest: BackupV17Fixtures.coverDigest)+ store.insertSiblingRow(+ shapeRaw: ThumbnailShape.portrait.rawValue, bytes: BackupV17Fixtures.coverBytes,+ digest: BackupV17Fixtures.coverDigest)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ let record = try #require(payload.works.first { $0.id == Self.workID })+ #expect(record.thumbnail == BackupV17Fixtures.coverBytes)+ #expect(record.thumbnail != stale)+ }++ /// Req 8.3's first refusable state: bytes that are present and are not a+ /// JPEG of the declared shape.+ ///+ /// The record is named by **title**, not by identifier as every other+ /// refusal in this projection is, because the remedy is for the reader to+ /// find that work in their own list and remove its cover — and the message+ /// says so, which the generic "written by a newer version" tail does not.+ @Test("Present-but-invalid cover bytes refuse the export, naming the work by title")+ func invalidCoverBytesRefuseByTitle() throws {+ let store = try LibraryStore()+ let bytes = Data("not a picture".utf8)+ store.setThumbnail(+ shapeRaw: ThumbnailShape.portrait.rawValue, bytes: bytes,+ digest: Hexadecimal.sha256(bytes))+ try store.context.save()++ let error = #expect(throws: BackupV17ExportError.self) {+ _ = try LibraryRepository.projectV17Payload(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 == BackupV17ExportError.thumbnailField)+ #expect(error?.description.contains("A Work") == true)+ #expect(error?.description.contains("Remove the cover") == true)+ #expect(error?.description.contains("resolve it first") == true)+ }++ /// Req 8.3's second: a shape spelling this build has no case for.+ ///+ /// `thumbnailShape` reads it as `.portrait` so the app can still draw and+ /// remove the cover (Q63) — and that tolerance is exactly why the export may+ /// not be tolerant: writing `portrait` back would record a crop the reader+ /// never chose, inside the file that is supposed to be the copy.+ ///+ /// Truncated **valid-shape** bytes are covered by `ThumbnailCodecTests`;+ /// what this pins is that the export asks `validate` at all.+ @Test("An unknown cover shape refuses the export, naming the work by title")+ func unknownCoverShapeRefusesByTitle() throws {+ let store = try LibraryStore()+ store.setThumbnail(+ shapeRaw: "hexagon", bytes: BackupV17Fixtures.coverBytes,+ digest: BackupV17Fixtures.coverDigest)+ try store.context.save()++ let error = #expect(throws: BackupV17ExportError.self) {+ _ = try LibraryRepository.projectV17Payload(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 == BackupV17ExportError.thumbnailField)+ #expect(value == "hexagon")+ }++ /// `update-schedule` Req 8.3, on the statuses' terms. The accessor drops a+ /// spelling this build has no case for so the app can still draw and edit+ /// the schedule (Req 1.6) — and that tolerance is exactly why the export may+ /// not be tolerant: writing the shorter list back would record a schedule+ /// the reader never typed, inside the file that is supposed to be the copy.+ ///+ /// The refusal names the **work and the value**, so the reader can find the+ /// work in their own list and Save it, which is what rewrites the column.+ @Test("An unknown release-day spelling refuses the export, naming the work and the value")+ func unknownReleaseDayRefusesTheExport() throws {+ let store = try LibraryStore()+ store.setReleaseDaysRaw(["monday", "funday"])+ try store.context.save()++ let error = #expect(throws: BackupV17ExportError.self) {+ _ = try LibraryRepository.projectV17Payload(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(Self.workID.uuidString))+ #expect(field == "release day")+ #expect(value == "funday")+ }++ /// The other side of the same door: a schedule this build can name travels+ /// whole, in canonical order, whatever order the column holds it in.+ @Test("A representable schedule exports canonically")+ func representableReleaseDaysProject() throws {+ let store = try LibraryStore()+ store.setReleaseDaysRaw(["thursday", "monday"])+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ let record = try #require(payload.works.first { $0.id == Self.workID })+ #expect(record.releaseDays == [.monday, .thursday])+ }++ /// Req 6.1: what the store holds is what the archive carries — the character+ /// with its facts, the suppression row, and both coverage shapes.+ @Test("Characters, suppressions and coverage project out of the store")+ func charactersProject() throws {+ let store = try LibraryStore()+ store.insertCharacter(+ id: Self.characterID, name: "Grover", aliases: ["Klar"], note: "The guide.",+ facts: [+ RecordFact(+ statement: "Promised to guide them home.",+ quote: "promised to guide them home", nameKey: "grover",+ source: .entry(Self.entryID))+ ])+ store.insertSuppression(nameKey: "the crowned one")+ store.coverEntry()+ store.coverGenericNotes()+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ let character = try #require(payload.characters.first)+ #expect(character.id == Self.characterID)+ #expect(character.workID == Self.workID)+ #expect(character.nameKey == "grover")+ #expect(character.aliases == ["Klar"])+ #expect(character.facts.map(\.quote) == ["promised to guide them home"])++ let suppression = try #require(payload.suppressions.first)+ #expect(suppression.nameKey == "the crowned one")+ #expect(suppression.workID == Self.workID)+ #expect(suppression.kindRaw == CharacterSuppressionKind.candidate.rawValue)++ // Req 9.4: no coverage table — the fingerprint is on the record whose+ // text it describes.+ #expect(+ payload.entries.first { $0.id == Self.entryID }?.characterExtractionFingerprint+ == CharacterCoverageFingerprint.of(Self.note))+ #expect(+ payload.works.first { $0.id == Self.workID }?.genericNotesExtractionFingerprint+ == CharacterCoverageFingerprint.of(Self.genericNotes))+ }++ /// `wrong-host-work-url-heal` [1.6](../../../../specs/wrong-host-work-url-heal/requirements.md#16),+ /// Q17: the export folds a duplicated `(Work, hostname)` pair to the row+ /// de-duplication would keep, and the discarded row's Work URL comes with+ /// it. A heal-minted row is in identity state `none`, so a later+ /// rule-identity row for the same hostname sorts ahead of it — and without+ /// the carry the address the heal had just preserved would leave the archive+ /// silently, which is what+ /// [4.2](../../../../specs/wrong-host-work-url-heal/requirements.md#42)+ /// depends on.+ ///+ /// The fold is a read (Q54): projecting must leave the context clean.+ @Test("The export fold carries a discarded membership's Work URL")+ func exportFoldCarriesTheWorkURL() throws {+ let store = try LibraryStore()+ let work = try #require(try store.context.fetch(FetchDescriptor<Work>()).first)+ let twin = WorkSiteMembership(+ hostname: Self.host, createdAt: Self.early.addingTimeInterval(60),+ urlIdentityState: .none, workURLString: "https://\(Self.host)/serial",+ workID: work.id, work: work)+ store.context.insert(twin)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ // One record for the pair, and it is the survivor's — carrying the+ // address the discarded row held.+ #expect(payload.memberships.count == 1)+ #expect(payload.memberships.first?.id != twin.id)+ #expect(payload.memberships.first?.workURLString == "https://\(Self.host)/serial")+ #expect(!store.context.hasChanges, "the projection must not dirty its context")+ }++ /// Q78: enumerated whole, never works→children. A character that synced+ /// ahead of its work is inert in the app, but dropping it from the backup+ /// would be losing reader data to a timing accident.+ @Test("A character whose work has not arrived exports with a nil work reference")+ func orphanCharacterExports() throws {+ let store = try LibraryStore()+ store.insertCharacter(id: Self.orphanID, name: "Stranger", attachToWork: false)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(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 BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).payload == payload)+ }++ /// Req 6.5. One character UUID over two rows that disagree about something+ /// the reader wrote is one record with two authored values, and an archive+ /// can hold neither of them honestly.+ @Test("A torn character group refuses the export")+ func tornCharacterRefusesExport() throws {+ let store = try LibraryStore()+ store.insertCharacter(id: Self.characterID, name: "Grover", note: "The guide.")+ store.insertCharacter(id: Self.characterID, name: "Grover", note: "A traitor.")+ try store.context.save()++ #expect(throws: BackupV17ExportError.self) {+ try LibraryRepository.projectV17Payload(context: store.context)+ }+ }++ /// Req 6.2 and Decision 2: the export succeeds while a fact's citation+ /// dangles. Deleting a cited entry is curation, not damage.+ @Test("The export succeeds while a fact's citation dangles")+ func danglingCitationExports() throws {+ let absent = UUID(uuidString: "60000000-0000-4000-8000-0000000000ff")!+ let store = try LibraryStore()+ store.insertCharacter(+ id: Self.characterID, name: "Grover",+ facts: [+ RecordFact(+ statement: "Was there.", quote: "was there", nameKey: "grover",+ source: .entry(absent))+ ])+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ #expect(payload.characters.first?.facts.first?.source == .entry(absent))+ let encoded = try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).payload == payload)+ }++ // MARK: The places (Req 5.1, 5.3, 5.5)++ /// Req 5.1: what the store holds is what the archive carries, over the second+ /// table too — the place with its facts and the place-suppression row, both+ /// enumerated whole rather than through a work walk `Place` has no inverse+ /// for.+ @Test("Places and place suppressions project out of the store")+ func placesProject() throws {+ let store = try LibraryStore()+ store.insertPlace(+ id: Self.placeID, name: "The High Keep",+ facts: [+ RecordFact(+ statement: "Sits above the pass.", quote: "above the pass",+ nameKey: "high keep", source: .entry(Self.entryID))+ ])+ store.insertPlaceSuppression(nameKey: "low road")+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ let place = try #require(payload.places.first)+ #expect(place.id == Self.placeID)+ #expect(place.workID == Self.workID)+ #expect(place.nameKey == "high keep")+ #expect(place.facts.map(\.quote) == ["above the pass"])++ let suppression = try #require(payload.placeSuppressions.first)+ #expect(suppression.nameKey == "low road")+ #expect(suppression.workID == Self.workID)+ #expect(suppression.kindRaw == CharacterSuppressionKind.candidate.rawValue)++ // The character arrays are untouched by any of it: the two kinds share a+ // shape, never a table.+ #expect(payload.characters.isEmpty)+ #expect(payload.suppressions.isEmpty)+ }++ /// Req 5.5 and Q67: a place whose `workID` resolves to nothing is reachable+ /// *only* by the whole-table enumeration, and it exports carrying the id it+ /// names rather than vanishing or being rewritten.+ @Test("A place whose work resolves to nothing exports with the id it names")+ func orphanPlaceExports() throws {+ let store = try LibraryStore()+ store.insertPlace(id: Self.orphanPlaceID, name: "Nowhere", workID: Self.absentWorkID)+ store.insertPlaceSuppression(nameKey: "elsewhere", workID: Self.absentWorkID)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ let orphan = try #require(payload.places.first { $0.id == Self.orphanPlaceID })+ #expect(orphan.workID == Self.absentWorkID)+ #expect(payload.placeSuppressions.first?.workID == Self.absentWorkID)+ // 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 BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).payload == payload)+ }++ /// Req 5.3: a torn place group is the same thing a torn character group is —+ /// one record with two authored values — so it refuses the export on exactly+ /// the same terms.+ @Test("A torn place group refuses the export")+ func tornPlaceRefusesExport() throws {+ let store = try LibraryStore()+ store.insertPlace(id: Self.placeID, name: "The High Keep", note: "Abandoned.")+ store.insertPlace(id: Self.placeID, name: "The High Keep", note: "Still garrisoned.")+ try store.context.save()++ #expect(throws: BackupV17ExportError.self) {+ try LibraryRepository.projectV17Payload(context: store.context)+ }+ }++ // MARK: Series and links (`series-and-related-works` Req 13.1, 13.2)++ /// Req 13.2: the archive carries the **logical** library. One link per pair,+ /// the row `survivorFirstLinks` keeps, and no row naming one work twice —+ /// so an archive never carries a row the next reconcile pass deletes.+ @Test("Links project one per pair by the survivor rule, and no self-link")+ func linksProjectOnePerPair() throws {+ let other = UUID(uuidString: "60000000-0000-4000-8000-00000000000a")!+ let older = UUID(uuidString: "60000000-0000-4000-8000-00000000000b")!+ let newer = UUID(uuidString: "60000000-0000-4000-8000-00000000000c")!+ let selfLink = UUID(uuidString: "60000000-0000-4000-8000-00000000000d")!+ let store = try LibraryStore()+ // Two rows over one pair, and the later modification is the survivor+ // whatever order they sit in the table (Q27).+ store.insertLink(+ id: older, a: Self.workID, b: other, type: "adaptation",+ modifiedAt: Self.early)+ store.insertLink(+ id: newer, a: other, b: Self.workID, type: "sequel",+ modifiedAt: Self.early.addingTimeInterval(60))+ store.insertLink(id: selfLink, a: Self.workID, b: Self.workID, type: "sequel")+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ #expect(payload.links.map(\.id) == [newer])+ #expect(payload.links.map(\.linkType) == ["sequel"])+ let ids = WorkDistinctPair.sortedIDs(Self.workID, other)+ #expect(payload.links.first?.lowerWorkID == ids.lower)+ #expect(payload.links.first?.higherWorkID == ids.higher)+ }++ /// Req 13.1: the series table travels whole and the membership travels on+ /// the work record, off the carrier's columns.+ @Test("The series table and a work's membership project out of the store")+ func seriesAndMembershipProject() throws {+ let seriesID = UUID(uuidString: "5E81E5A0-0000-4000-8000-000000000001")!+ let store = try LibraryStore()+ store.insertSeries(id: seriesID, name: "Ashfall Cycle", notes: "Read 2.5 after 2.")+ store.placeWork(seriesID: seriesID, position: 2.5)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ #expect(payload.series.map(\.id) == [seriesID])+ #expect(payload.series.first?.name == "Ashfall Cycle")+ #expect(payload.series.first?.notes == "Read 2.5 after 2.")+ let work = try #require(payload.works.first)+ #expect(work.seriesID == seriesID)+ #expect(work.seriesPosition == 2.5)+ }++ /// Req 13.5 at the *export* door. The snapshot reads a half-set row as no+ /// membership and an unrounded position as itself, so a backup taken over+ /// one would record "in no series", or a number the format cannot spell,+ /// silently — inside the file that is supposed to be the copy. Named+ /// instead, with the work that holds it.+ @Test("A half-set pair, a non-finite position and an unrounded one refuse the export")+ func illegalMembershipColumnsRefuseTheExport() throws {+ let seriesID = UUID(uuidString: "5E81E5A0-0000-4000-8000-000000000001")!+ let cases: [(UUID?, Double?)] = [+ (seriesID, nil), (nil, 1), (seriesID, 2.55), (seriesID, .infinity),+ ]+ for (id, position) in cases {+ let store = try LibraryStore()+ store.insertSeries(id: seriesID, name: "Ashfall Cycle")+ store.placeWork(seriesID: id, position: position)+ try store.context.save()++ let error = #expect(throws: BackupV17ExportError.self) {+ try LibraryRepository.projectV17Payload(context: store.context)+ }+ guard case .unrepresentableValue(let record, _, _) = error else {+ Issue.record("expected an unrepresentable-value refusal, got \(String(describing: error))")+ continue+ }+ #expect(record.contains(Self.workID.uuidString))+ }+ }++ // MARK: Creators, roles and credits (`work-creators` Req 9.1, 9.2)++ /// Req 9.1: one record per **identity**, whatever rows back it, carrying the+ /// per-field timestamps (Q50) — and a merged record pointing at its final+ /// survivor, so an archive never carries an alias chain (Q33).+ @Test("The creator and role tables project folded, with their field timestamps")+ func creatorDirectoriesProject() throws {+ let store = try LibraryStore()+ let mori = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000001")!+ let alias = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000003")!+ let chained = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000004")!+ // Two rows of one identity, each carrying one reader edit: the shape a+ // single archived `modifiedAt` could not describe.+ store.insertCreator(id: mori, name: "Mori Ayane", nameModifiedAt: Self.early)+ store.insertCreator(+ id: mori, name: "", notes: "Also draws.",+ notesModifiedAt: Self.early.addingTimeInterval(60))+ store.insertCreator(+ id: alias, name: "mori ayane", state: .merged, canonicalID: mori,+ stateModifiedAt: Self.early)+ // An alias of the alias: the chase collapses it to the endpoint.+ store.insertCreator(+ id: chained, name: "MORI AYANE", state: .merged, canonicalID: alias,+ stateModifiedAt: Self.early)+ store.insertCreatorRole(id: Self.roleID, name: "letterer", position: 3)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ #expect(payload.creators.count == 3)+ let record = try #require(payload.creators.first { $0.id == mori })+ #expect(record.name == "Mori Ayane")+ #expect(record.nameModifiedAt == Self.early)+ #expect(record.notes == "Also draws.")+ #expect(record.notesModifiedAt == Self.early.addingTimeInterval(60))+ #expect(record.modifiedAt == Self.early.addingTimeInterval(60))+ #expect(payload.creators.first { $0.id == alias }?.canonicalID == mori)+ #expect(payload.creators.first { $0.id == chained }?.canonicalID == mori)++ let role = try #require(payload.creatorRoles.first { $0.id == Self.roleID })+ #expect(role.position == 3)+ #expect(role.stateRaw == CreatorRoleState.active.rawValue)++ // 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 BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).payload == payload)+ }++ /// Q68: a merged record whose survivor is not in the library reads as+ /// unresolved on every device, and the reference checks refuse a named+ /// survivor the file does not carry. It exports carrying **no** survivor —+ /// the one shape that says the same thing and is still a file.+ @Test("A merged creator whose survivor has not arrived exports with no survivor")+ func danglingAliasProjects() throws {+ let store = try LibraryStore()+ let alias = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000003")!+ let absent = UUID(uuidString: "c8ea1080-0000-4000-8000-00000000000f")!+ store.insertCreator(+ id: alias, name: "mori ayane", state: .merged, canonicalID: absent,+ stateModifiedAt: Self.early)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(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 BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).payload == payload)+ }++ /// Req 9.2: one credit per work-and-creator pair, bucketed on the+ /// **canonical** creator, carrying the union of the bucket's roles and its+ /// latest stamp — the row `dedupeCredits` would keep and the roles it would+ /// write, so an archive never carries a state the next pass changes.+ @Test("Credits project one per pair, on the canonical creator, with the union")+ func creditsProjectOnePerPair() throws {+ let store = try LibraryStore()+ let mori = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000001")!+ let alias = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000003")!+ let head = UUID(uuidString: "c8ed1700-0000-4000-8000-000000000001")!+ let loser = UUID(uuidString: "c8ed1700-0000-4000-8000-000000000002")!+ let author = CreatorRoleSeeding.seeds[0].id+ let artist = CreatorRoleSeeding.seeds[1].id+ store.insertCreator(id: mori, name: "Mori Ayane", nameModifiedAt: Self.early)+ store.insertCreator(+ id: alias, name: "mori ayane", state: .merged, canonicalID: mori,+ stateModifiedAt: Self.early)+ store.insertCredit(+ id: head, workID: Self.workID, creatorID: mori, roleIDs: [author],+ createdAt: Self.early, modifiedAt: Self.early)+ // The same pair through the alias, created later: it loses the head and+ // contributes its role.+ store.insertCredit(+ id: loser, workID: Self.workID, creatorID: alias, roleIDs: [artist],+ createdAt: Self.early.addingTimeInterval(60),+ modifiedAt: Self.early.addingTimeInterval(120))+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ #expect(payload.credits.count == 1)+ let record = try #require(payload.credits.first)+ #expect(record.id == head)+ // As stored (Q27): the head's own column, alias or not.+ #expect(record.creatorID == mori)+ #expect(record.roleIDs == [author.uuidString, artist.uuidString].sorted())+ #expect(record.createdAt == Self.early)+ // The bucket's maximum, never the clock (Q61).+ #expect(record.modifiedAt == Self.early.addingTimeInterval(120))+ }++ /// Req 9.2 and Q71: a library caught between a rename and the reconcile+ /// pass that answers for it holds two visible records spelled the same. The+ /// projection elects across them — `CreatorReconciler`'s own election, read+ /// only — so the file carries one active record and one alias, and the+ /// credits under the loser leave bucketed under the survivor. Before the+ /// election the same library exported a payload its own reference checks+ /// refused.+ @Test("Two records sharing a normalized name export elected, not as a refused file")+ func collidingRecordsElectAtExport() throws {+ let store = try LibraryStore()+ let survivor = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000001")!+ let loser = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000003")!+ let keptRole = UUID(uuidString: "e0000004-0000-4000-8000-000000000004")!+ let losingRole = UUID(uuidString: "e0000005-0000-4000-8000-000000000005")!+ let head = UUID(uuidString: "c8ed1700-0000-4000-8000-000000000001")!+ let other = UUID(uuidString: "c8ed1700-0000-4000-8000-000000000002")!+ let author = CreatorRoleSeeding.seeds[0].id+ let artist = CreatorRoleSeeding.seeds[1].id+ // Equal creation times, so the election falls to the lowest identifier.+ store.insertCreator(id: survivor, name: "Mori Ayane", nameModifiedAt: Self.early)+ store.insertCreator(+ id: loser, name: "mori ayane", nameModifiedAt: Self.early.addingTimeInterval(60))+ store.insertCreatorRole(id: keptRole, name: "letterer", position: 3)+ store.insertCreatorRole(+ id: losingRole, name: "Letterer", position: 4,+ nameModifiedAt: Self.early.addingTimeInterval(60))+ store.insertCredit(+ id: head, workID: Self.workID, creatorID: survivor, roleIDs: [author],+ createdAt: Self.early, modifiedAt: Self.early)+ store.insertCredit(+ id: other, workID: Self.workID, creatorID: loser, roleIDs: [artist],+ createdAt: Self.early.addingTimeInterval(60),+ modifiedAt: Self.early.addingTimeInterval(120))+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(context: store.context)++ #expect(payload.creators.count == 2)+ #expect(+ payload.creators.first { $0.id == survivor }?.stateRaw+ == CreatorState.active.rawValue)+ let alias = try #require(payload.creators.first { $0.id == loser })+ #expect(alias.stateRaw == CreatorState.merged.rawValue)+ #expect(alias.canonicalID == survivor)+ #expect(+ payload.creatorRoles.first { $0.id == keptRole }?.stateRaw+ == CreatorRoleState.active.rawValue)+ let aliasRole = try #require(payload.creatorRoles.first { $0.id == losingRole })+ #expect(aliasRole.stateRaw == CreatorRoleState.merged.rawValue)+ #expect(aliasRole.canonicalID == keptRole)++ // The loser's credit buckets under the elected survivor: one record per+ // pair, carrying the union the dedupe would write.+ #expect(payload.credits.count == 1)+ let credit = try #require(payload.credits.first)+ #expect(credit.id == head)+ #expect(credit.roleIDs == [author.uuidString, artist.uuidString].sorted())++ // The check that used to refuse this library's own archive.+ let encoded = try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).payload == payload)+ }++ /// Req 10.2 at the export door: nothing is pruned for naming a work,+ /// creator or role the library does not hold. A backup is the last place to+ /// drop a value that is merely waiting for its target.+ @Test("A credit naming an absent work, creator and role still exports")+ func unresolvedCreditExports() throws {+ let store = try LibraryStore()+ let absentWork = UUID(uuidString: "60000000-0000-4000-8000-0000000000e1")!+ let absentCreator = UUID(uuidString: "60000000-0000-4000-8000-0000000000e2")!+ let absentRole = UUID(uuidString: "60000000-0000-4000-8000-0000000000e3")!+ store.insertCredit(+ id: UUID(uuidString: "60000000-0000-4000-8000-0000000000e4")!,+ workID: absentWork, creatorID: absentCreator, roleIDs: [absentRole],+ createdAt: Self.early, modifiedAt: Self.early)+ try store.context.save()++ let payload = try LibraryRepository.projectV17Payload(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 BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).payload == payload)+ }++ // MARK: - Fixture++ /// An in-memory V16 store holding one taught-enough Site, one Work with+ /// generic notes and one noted Entry. The container is retained for the+ /// test's lifetime: a `ModelContext` does not keep its container alive.+ private final class LibraryStore {+ let container: ModelContainer+ let context: ModelContext+ /// The Work row `init` creates, held rather than re-fetched: a split+ /// group (`insertSiblingRow`) puts a second row under the same UUID and+ /// `fetch(…).first` would then answer either of them.+ private var carrier: Work!++ init() throws {+ let schema = Schema(versionedSchema: AsterismSchemaV18.self)+ container = try ModelContainer(+ for: schema,+ configurations: [+ ModelConfiguration(+ schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ ])+ context = ModelContext(container)+ let site = Site(hostname: BackupV17ExportTests.host, displayName: "Characters")+ site.mode = .untaught+ context.insert(site)++ let work = Work.create(+ in: context, id: BackupV17ExportTests.workID, title: "A Work",+ hostname: BackupV17ExportTests.host, site: site,+ timestamp: BackupV17ExportTests.early)+ work.genericNotes = BackupV17ExportTests.genericNotes+ carrier = work++ let rawURL = "https://\(BackupV17ExportTests.host)/read/1"+ let entry = Entry(+ id: BackupV17ExportTests.entryID, captureTitle: "Chapter 1",+ captureTitleSource: .host, rawURLString: rawURL,+ hostname: BackupV17ExportTests.host, entryIdentityKey: rawURL,+ timestamp: BackupV17ExportTests.early, note: BackupV17ExportTests.note)+ entry.conservativeIdentityKey = rawURL+ entry.editCitations { $0.workAssignment = .manual }+ context.insert(entry)+ entry.site = site+ entry.work = work+ }++ private var work: Work? { carrier }++ func insertCharacter(+ id: UUID, name: String, aliases: [String] = [], note: String = "",+ facts: [RecordFact] = [], attachToWork: Bool = true+ ) {+ let character = CharacterRecord(+ id: id, name: name, nameKey: RecordNameKey.normalize(name),+ aliases: aliases, note: note, facts: facts,+ timestamp: BackupV17ExportTests.early)+ context.insert(character)+ if attachToWork { character.work = work }+ }++ func insertSuppression(nameKey: String) {+ let row = CharacterSuppression(+ kind: .candidate, nameKey: nameKey, actionAt: BackupV17ExportTests.early)+ context.insert(row)+ row.work = work+ }++ /// The place twin. Ownership is a **column**, so the caller names the+ /// work id rather than handing over a row — which is the only way to+ /// seed the non-resolving owner of Req 5.5.+ func insertPlace(+ id: UUID, name: String, aliases: [String] = [], note: String = "",+ facts: [RecordFact] = [], workID: UUID = BackupV17ExportTests.workID+ ) {+ context.insert(+ Place(+ id: id, name: name, nameKey: RecordNameKey.normalize(name),+ aliases: aliases, note: note, facts: facts,+ timestamp: BackupV17ExportTests.early, workID: workID))+ }++ func insertPlaceSuppression(+ nameKey: String, workID: UUID = BackupV17ExportTests.workID+ ) {+ context.insert(+ PlaceSuppression(+ workID: workID, kind: .candidate, nameKey: nameKey,+ actionAt: BackupV17ExportTests.early))+ }++ /// The three cover columns, written straight onto the work row.+ ///+ /// Deliberately not `updateWork`: every state these export tests are+ /// about — bytes that are not a JPEG, a shape spelling this build has no+ /// case for, an identity whose asset never arrived — is one no writer of+ /// ours produces, and the export has to answer for it anyway.+ func setThumbnail(shapeRaw: String?, bytes: Data?, digest: String?) {+ work?.thumbnailShapeRaw = shapeRaw+ work?.thumbnailData = bytes+ work?.thumbnailDigest = digest+ }++ /// A second row under the work's own UUID, carrying its own three cover+ /// columns: Req 1.8's split group, where the identity and the bytes+ /// behind it can sit on different rows (Q79).+ ///+ /// Every field the variant ordering reads is copied from the carrier, so+ /// the group is **split and not torn** — a torn group refuses the export+ /// whatever its covers look like, which would prove nothing about which+ /// row the bytes came from. The later `createdAt` is what keeps the+ /// original row the carrier.+ func insertSiblingRow(shapeRaw: String?, bytes: Data?, digest: String?) {+ let sibling = Work.create(+ in: context, id: BackupV17ExportTests.workID, title: carrier.displayTitle,+ hostname: BackupV17ExportTests.host, site: carrier.primaryMembership?.site,+ timestamp: BackupV17ExportTests.early.addingTimeInterval(60))+ sibling.lastParsedTitle = carrier.lastParsedTitle+ sibling.titleProvenanceRaw = carrier.titleProvenanceRaw+ sibling.genericNotes = carrier.genericNotes+ sibling.genreTags = carrier.genreTags+ sibling.workStatusRaw = carrier.workStatusRaw+ sibling.readingStatusRaw = carrier.readingStatusRaw+ sibling.verdict = carrier.verdict+ sibling.seriesID = carrier.seriesID+ sibling.seriesPosition = carrier.seriesPosition+ sibling.thumbnailShapeRaw = shapeRaw+ sibling.thumbnailData = bytes+ sibling.thumbnailDigest = digest+ }++ func coverEntry() {+ try? context.fetch(FetchDescriptor<Entry>()).first?+ .characterExtractionFingerprint = CharacterCoverageFingerprint.of(+ BackupV17ExportTests.note)+ }++ func coverGenericNotes() {+ work?.genericNotesExtractionFingerprint = CharacterCoverageFingerprint.of(+ BackupV17ExportTests.genericNotes)+ }++ // `series-and-related-works` Req 13.++ func insertSeries(+ id: UUID, name: String, notes: String = "",+ createdAt: Date = BackupV17ExportTests.early,+ modifiedAt: Date = BackupV17ExportTests.early+ ) {+ context.insert(+ Series(+ id: id, name: name, notes: notes, createdAt: createdAt,+ modifiedAt: modifiedAt))+ }++ /// One link row, ids as given — a caller passing them equal writes the+ /// self-link no writer produces and the projection drops.+ func insertLink(+ id: UUID, a: UUID, b: UUID, type: String,+ modifiedAt: Date = BackupV17ExportTests.early+ ) {+ let sorted = WorkDistinctPair.sortedIDs(a, b)+ context.insert(+ WorkLink(+ id: id, lowerWorkID: sorted.lower, higherWorkID: sorted.higher,+ linkType: type, createdAt: BackupV17ExportTests.early,+ modifiedAt: modifiedAt))+ }++ func placeWork(seriesID: UUID?, position: Double?) {+ work?.seriesID = seriesID+ work?.seriesPosition = position+ }++ /// The **raw** column, because a spelling this build has no case for is+ /// exactly what `update-schedule` Req 8.3 is about and the accessor+ /// cannot write one.+ func setReleaseDaysRaw(_ raw: [String]) {+ work?.releaseDaysRaw = raw+ }++ // `work-creators` Req 9. Rows rather than repository calls, because the+ // shapes these suites are about — two rows of one identity each carrying+ // a different reader edit, an alias chain, a credit naming nothing — are+ // states sync produces and no write path does.++ func insertCreator(+ id: UUID, name: String, notes: String = "", state: CreatorState = .active,+ canonicalID: UUID? = nil,+ nameModifiedAt: Date = CreatorDirectory.epoch,+ notesModifiedAt: Date = CreatorDirectory.epoch,+ stateModifiedAt: Date = CreatorDirectory.epoch+ ) {+ let row = Creator(+ id: id, name: name, notes: notes, stateRaw: state.rawValue,+ canonicalID: canonicalID)+ row.createdAt = BackupV17ExportTests.early+ row.nameModifiedAt = nameModifiedAt+ row.notesModifiedAt = notesModifiedAt+ row.stateModifiedAt = stateModifiedAt+ row.modifiedAt = max(nameModifiedAt, max(notesModifiedAt, stateModifiedAt))+ context.insert(row)+ }++ func insertCreatorRole(+ id: UUID, name: String, position: Int, state: CreatorRoleState = .active,+ canonicalID: UUID? = nil,+ nameModifiedAt: Date = BackupV17ExportTests.early,+ positionModifiedAt: Date = BackupV17ExportTests.early,+ stateModifiedAt: Date = BackupV17ExportTests.early+ ) {+ let row = CreatorRole(+ id: id, name: name, position: position, stateRaw: state.rawValue,+ canonicalID: canonicalID)+ row.createdAt = BackupV17ExportTests.early+ row.nameModifiedAt = nameModifiedAt+ row.positionModifiedAt = positionModifiedAt+ row.stateModifiedAt = stateModifiedAt+ row.modifiedAt = max(nameModifiedAt, max(positionModifiedAt, stateModifiedAt))+ context.insert(row)+ }++ func insertCredit(+ id: UUID, workID: UUID, creatorID: UUID, roleIDs: [UUID],+ createdAt: Date, modifiedAt: Date+ ) {+ context.insert(+ WorkCredit(+ id: id, workID: workID, creatorID: creatorID,+ roleIDs: roleIDs.map(\.uuidString).sorted(),+ createdAt: createdAt, modifiedAt: modifiedAt))+ }+ }+}++// MARK: - Import++@Suite("Backup 16/17 import", .serialized)+struct BackupV17ImportTests {++ // MARK: One accepted pair (Decision 2)++ @Test("The importer accepts 16/17")+ func acceptedGeneration() throws {+ let data = try BackupV17Codec.encode(+ payload: BackupV17Fixtures.payload(), metadata: BackupV17Fixtures.metadata())++ let plan = try BackupImporter.plan(from: data)+ #expect(plan.metadata.formatVersion == 17)+ #expect(plan.metadata.schemaVersion == 18)+ #expect(plan.payload == BackupImportPayload(BackupV17Fixtures.payload()))+ }++ /// The retired generations refuse **by version**, and the refusal names the+ /// pair the file declares.+ ///+ /// The distinction matters: a 9/10 envelope is well-formed JSON with a+ /// well-formed payload and a valid checksum, so a build that had merely+ /// deleted the 9/10 record types would fail it somewhere inside a decode and+ /// tell the reader their backup is corrupt. It is not corrupt; it is old,+ /// and the message has to say so (Req 13.1, Q13).+ ///+ /// (14, 15) leads the list: it is the generation this one replaced, and the+ /// one a reader upgrading across `remove-article-mode` is holding+ /// (`remove-article-mode` Req 5.3, Q2).+ @Test(+ "A retired generation refuses by version, naming the pair",+ arguments: [+ (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 = BackupV17Fixtures.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)++ let error = #expect(throws: BackupImportError.self) {+ try BackupImporter.plan(from: data)+ }+ guard case .unsupportedFormat(let reason) = error else {+ Issue.record("expected an unsupported-format refusal, got \(String(describing: error))")+ return+ }+ #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("(\(BackupV17Document.formatVersion)/\(BackupV17Document.schemaVersion))"))+ }++ @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: [+ "backupFormatVersion": format,+ "databaseSchemaVersion": schema,+ ])+ #expect(throws: BackupImportError.self) {+ try BackupImporter.plan(from: data)+ }+ }+ }++ // MARK: What lands (Req 6.1)++ @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: BackupV17Fixtures.plan(BackupV17Fixtures.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 == BackupV17Fixtures.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(BackupV17Fixtures.entryID))+ #expect(grover.workID == BackupV17Fixtures.workID, "the character joins its work")++ let suppressions = try await fixture.repository.m5SuppressionRows()+ let row = try #require(suppressions.first { $0.id == BackupV17Fixtures.suppressionID })+ #expect(row.nameKey == "the crowned one")+ #expect(row.kind == .candidate)+ #expect(row.status == .active)+ #expect(row.workID == BackupV17Fixtures.workID)++ #expect(+ try await fixture.repository.m5EntryCoverage(BackupV17Fixtures.entryID)+ == BackupV17Fixtures.noteFingerprint)+ #expect(+ try await fixture.repository.m5WorkCoverage(BackupV17Fixtures.workID)+ == BackupV17Fixtures.genericNotesFingerprint)+ }++ /// Req 6.7 through the archive: a character with no work is a tolerated+ /// in-flight state on the way out (Q78) and on the way in.+ @Test("An orphan character imports and stays unattached")+ func orphanCharacterImports() async throws {+ let fixture = try await M5Fixture()++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ characters: [+ BackupV17Fixtures.character(id: BackupV17Fixtures.orphanID, workID: nil)+ ])))++ let characters = try await fixture.repository.m5AllCharacters()+ let orphan = try #require(characters.first { $0.id == BackupV17Fixtures.orphanID })+ #expect(orphan.workID == nil)+ }++ /// Q81: coverage carries no timestamp to value-guard with, and needs none —+ /// a pair is kept exactly where the archived fingerprint still describes the+ /// source's current text, and dropped otherwise.+ @Test("Coverage is self-validating: a stale fingerprint is dropped")+ func coverageIsSelfValidating() async throws {+ let fixture = try await M5Fixture()++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(entryFingerprint: "not-this-note")))++ #expect(try await fixture.repository.m5EntryCoverage(BackupV17Fixtures.entryID) == nil)+ #expect(+ try await fixture.repository.m5WorkCoverage(BackupV17Fixtures.workID)+ == BackupV17Fixtures.genericNotesFingerprint)+ }++ // MARK: Value guards and idempotence (Req 6.1, 7.7's shape)++ /// Over the four tables an archive can move that are not the Work and Entry+ /// 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 16/17 archive twice changes nothing the second time")+ func importingTwiceChangesNothing() async throws {+ let fixture = try await M5Fixture()+ let base = BackupV17Fixtures.payload()+ let stranger = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee99")!+ let ids = WorkDistinctPair.sortedIDs(BackupV17Fixtures.workID, stranger)+ let plan = BackupV17Fixtures.plan(+ BackupV17Payload(+ entries: base.entries, works: base.works, sites: base.sites,+ titlePatterns: base.titlePatterns, urlRules: base.urlRules,+ workTypes: base.workTypes, memberships: base.memberships,+ distinctPairs: [+ BackupV17DistinctPair(+ id: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee98")!,+ lowerWorkID: ids.lower, higherWorkID: ids.higher,+ recordedAt: BackupV17Fixtures.created)+ ],+ characters: base.characters, suppressions: base.suppressions,+ places: base.places, placeSuppressions: base.placeSuppressions))++ try await fixture.repository.confirmImport(plan: plan)+ let charactersAfterFirst = try await fixture.repository.m5AllCharacters()+ let suppressionsAfterFirst = try await fixture.repository.m5SuppressionRows()+ let membershipsAfterFirst = try await fixture.repository.m5MembershipRows()+ let pairsAfterFirst = try await fixture.repository.m5DistinctPairRows()++ try await fixture.repository.confirmImport(plan: plan)++ #expect(try await fixture.repository.m5AllCharacters() == charactersAfterFirst)+ #expect(try await fixture.repository.m5SuppressionRows() == suppressionsAfterFirst)+ #expect(try await fixture.repository.m5MembershipRows() == membershipsAfterFirst)+ #expect(try await fixture.repository.m5DistinctPairRows() == pairsAfterFirst)+ #expect(membershipsAfterFirst.count == 1)+ #expect(pairsAfterFirst.count == 1)+ }++ @Test("An archive older than the stored character writes nothing")+ func olderArchiveDoesNotRegressACharacter() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.payload()))++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ characters: [+ BackupV17Fixtures.character(+ name: "Renamed by an older device", note: "older",+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(-1_000))+ ])))++ let grover = try #require(+ try await fixture.repository.m5AllCharacters()+ .first { $0.id == BackupV17Fixtures.groverID })+ #expect(grover.name == "Grover")+ #expect(grover.note == "The guide.")+ }++ // MARK: The cover (`work-thumbnails` Req 8.1, 8.2, 8.4)++ /// Req 8.1 end to end: export, import into an empty library, and the bytes+ /// on the row are the bytes that went into the file — with the digest+ /// **re-derived** from them, because the file never carried one (Q5).+ ///+ /// The bytes go through the real codec rather than straight from the payload+ /// value, so the base64 encoding is part of what is under test: a codec that+ /// mangled a byte would still produce a `Data` of the right length.+ @Test("An archived cover restores byte-identical, with the digest re-derived")+ func archivedCoverRestoresWithTheDigestReDerived() async throws {+ let fixture = try await M5Fixture()+ let archive = try BackupV17Codec.encode(+ payload: BackupV17Fixtures.coveredPayload(),+ metadata: BackupV17Fixtures.metadata())++ try await fixture.repository.confirmImport(plan: try BackupImporter.plan(from: archive))++ #expect(+ try await fixture.repository.thumbnailColumns(of: BackupV17Fixtures.workID)+ == [ThumbnailColumns(+ byteCount: BackupV17Fixtures.coverBytes.count,+ shapeRaw: ThumbnailShape.portrait.rawValue,+ digest: BackupV17Fixtures.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: BackupV17Fixtures.workID, digest: BackupV17Fixtures.coverDigest)+ == BackupV17Fixtures.coverBytes)+ }++ /// Decision 3 through the whole archive: a cover stored shorter than its box+ /// round-trips like any other and is **not** one of Req 8.4's dropped+ /// records. The per-record validation on import asks the same+ /// `ThumbnailShape.accepts` the export does, so the two cannot disagree+ /// about what a thumbnail is.+ @Test("A gapped cover round-trips and is not dropped on import")+ func gappedCoverRoundTrips() async throws {+ let fixture = try await M5Fixture()+ let archive = try BackupV17Codec.encode(+ payload: BackupV17Fixtures.coveredPayload(+ bytes: BackupV17Fixtures.gappedCoverBytes),+ metadata: BackupV17Fixtures.metadata())++ let result = try await fixture.repository.confirmImport(+ plan: try BackupImporter.plan(from: archive))++ guard case .committed(_, let report) = result else {+ Issue.record("expected committed, got \(result)")+ return+ }+ #expect(report.droppedThumbnails.isEmpty)+ #expect(+ try await fixture.repository.thumbnailBytes(+ workID: BackupV17Fixtures.workID,+ digest: BackupV17Fixtures.gappedCoverDigest)+ == BackupV17Fixtures.gappedCoverBytes)+ }++ /// Req 8.4 on the **insert** path: a record whose bytes decode as `Data` and+ /// not as a JPEG imports its work *without* a cover, and the report names+ /// the work by title.+ ///+ /// Refusing would be the wrong trade (Q14): a reader cannot edit an archive,+ /// so a refusal blocks the whole restore over one picture. The malformed+ /// states that still refuse the file whole — bad base64, a bad checksum —+ /// are the codec's and are unchanged (Q51).+ @Test("An undecodable archived cover imports the work without one and names it")+ func undecodableCoverImportsWithoutACoverAndNamesTheWork() async throws {+ let fixture = try await M5Fixture()++ let result = try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.coveredPayload(+ bytes: BackupV17Fixtures.undecodableCoverBytes)))++ guard case .committed(let counts, let report) = result else {+ Issue.record("expected committed, got \(result)")+ return+ }+ // The work is in the library — that is the point of dropping rather+ // than refusing.+ #expect(counts.works >= 1)+ #expect(report.droppedThumbnails == ["Actual Title"])+ #expect(+ try await fixture.repository.thumbnailColumns(of: BackupV17Fixtures.workID)+ == [ThumbnailColumns.empty])+ }++ /// Q71, the **update** path, which is the half that could go either way. The+ /// record has already passed Req 8.2's modification guard, so it is the+ /// newer state of this work and it carries no usable cover: keeping the+ /// local one would restore a picture the archive says is gone. All three+ /// columns go together, so the row is not left claiming a cover nothing can+ /// draw.+ @Test("An undecodable archived cover clears the local one it is newer than")+ func undecodableCoverClearsALocalCover() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.coveredPayload()))+ #expect(+ try await fixture.repository.thumbnailColumns(of: BackupV17Fixtures.workID)+ != [ThumbnailColumns.empty])++ let result = try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.coveredPayload(+ bytes: BackupV17Fixtures.undecodableCoverBytes,+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(1_000))))++ guard case .committed(_, let report) = result else {+ Issue.record("expected committed, got \(result)")+ return+ }+ #expect(report.droppedThumbnails == ["Actual Title"])+ #expect(+ try await fixture.repository.thumbnailColumns(of: BackupV17Fixtures.workID)+ == [ThumbnailColumns.empty])+ }++ /// Req 8.2: the cover is part of the modification-guarded upsert and gets no+ /// exemption from it. An archive older than the local record does not+ /// replace the cover the reader picked since — and the report stays empty,+ /// because nothing was dropped: the record never reached the library at all.+ @Test("An older archive does not replace a newer local cover")+ func olderArchiveDoesNotReplaceANewerLocalCover() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.coveredPayload(+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(1_000))))++ let result = try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.coveredPayload(+ shapeRaw: ThumbnailShape.square.rawValue,+ bytes: BackupV17Fixtures.undecodableCoverBytes,+ modifiedAt: BackupV17Fixtures.created)))++ guard case .committed(_, let report) = result else {+ Issue.record("expected committed, got \(result)")+ return+ }+ #expect(report.droppedThumbnails.isEmpty)+ #expect(+ try await fixture.repository.thumbnailColumns(of: BackupV17Fixtures.workID)+ == [ThumbnailColumns(+ byteCount: BackupV17Fixtures.coverBytes.count,+ shapeRaw: ThumbnailShape.portrait.rawValue,+ digest: BackupV17Fixtures.coverDigest)])+ }++ /// Req 1.11's argument, applied to import: importing the same archive twice+ /// leaves the cover exactly as the first import wrote it, and the second+ /// pass writes nothing at all.+ ///+ /// The value guard matters here in a way it does not for the scalar columns+ /// beside it. Assigning `thumbnailData` rewrites an external-storage sidecar+ /// on disk and re-uploads a CloudKit asset, so an unguarded re-import would+ /// push every cover in the library back through the mirror for no change.+ /// The observable half is here; the "writes nothing" half is+ /// `reapplyingTheSameCoverWritesNothing` below, which can watch the context.+ @Test("Importing the same archive twice leaves the cover untouched")+ func importingTwiceLeavesTheCoverUntouched() async throws {+ let fixture = try await M5Fixture()+ let plan = BackupV17Fixtures.plan(BackupV17Fixtures.coveredPayload())++ try await fixture.repository.confirmImport(plan: plan)+ let columnsAfterFirst = try await fixture.repository+ .thumbnailColumns(of: BackupV17Fixtures.workID)++ try await fixture.repository.confirmImport(plan: plan)++ #expect(+ try await fixture.repository.thumbnailColumns(of: BackupV17Fixtures.workID)+ == columnsAfterFirst)+ #expect(+ try await fixture.repository.thumbnailBytes(+ workID: BackupV17Fixtures.workID, digest: BackupV17Fixtures.coverDigest)+ == BackupV17Fixtures.coverBytes)+ }++ /// The half the repository API cannot show: whether the second application+ /// of one archive cover *writes*.+ ///+ /// Three states, in one context so the store itself answers. A cover the row+ /// already holds dirties nothing; a clear over a row with nothing to clear+ /// dirties nothing; and — the reason the guard is not on the digest+ /// alone — a row whose digest is right while its blob is not is **healed**,+ /// 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: AsterismSchemaV18.self)+ let container = try ModelContainer(+ for: schema,+ configurations: [+ ModelConfiguration(+ schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ ])+ let context = ModelContext(container)+ context.autosaveEnabled = false+ let work = Work.create(+ in: context, title: "Covered", hostname: "a.example",+ timestamp: BackupV17Fixtures.created)+ let cover = ArchiveThumbnail.value(+ shapeRaw: ThumbnailShape.portrait.rawValue,+ bytes: BackupV17Fixtures.coverBytes,+ digest: BackupV17Fixtures.coverDigest)+ LibraryRepository.applyThumbnail(cover, to: work)+ try context.save()+ #expect(work.thumbnailDigest == BackupV17Fixtures.coverDigest)++ LibraryRepository.applyThumbnail(cover, to: work)+ #expect(!context.hasChanges, "a second import of the same cover must write nothing")++ // Req 1.8's tolerated row: the presence columns say one thing and the+ // blob says another. The restore is what heals it, so this one *must*+ // write.+ work.thumbnailData = Data("half an asset".utf8)+ 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 == BackupV17Fixtures.coverBytes)+ try context.save()++ // The clearing arm, both ways round.+ LibraryRepository.applyThumbnail(.none, to: work)+ #expect(context.hasChanges)+ try context.save()+ #expect(work.thumbnailShapeRaw == nil)+ LibraryRepository.applyThumbnail(.dropped, to: work)+ #expect(!context.hasChanges, "clearing a row that carries no cover must write nothing")+ }++ /// An ordinary import says nothing, which is what makes the list above worth+ /// showing when it is not empty.+ @Test("An import with nothing to drop reports an empty list")+ func anOrdinaryImportReportsNothing() async throws {+ let fixture = try await M5Fixture()++ let result = try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.coveredPayload()))++ guard case .committed(_, let report) = result else {+ Issue.record("expected committed, got \(result)")+ return+ }+ #expect(report.isEmpty)+ }++ @Test("An archive newer than the stored character updates every row of it")+ func newerArchiveUpdatesACharacter() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.payload()))++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ characters: [+ BackupV17Fixtures.character(+ name: "Grover Underwood", note: "Still the guide.",+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(1_000))+ ])))++ let grover = try #require(+ try await fixture.repository.m5AllCharacters()+ .first { $0.id == BackupV17Fixtures.groverID })+ #expect(grover.name == "Grover Underwood")+ #expect(grover.note == "Still the guide.")+ // The retained key never moves with a rename (Q19/Q46) — including a+ // rename that arrives through an archive.+ #expect(grover.nameKey == "grover")+ }++ /// Req 6.6: suppression convergence is the reader's most recent action, and+ /// an archive is not exempt from it.+ @Test("A suppression older than the stored row does not undo a clear")+ func olderSuppressionDoesNotUndoAClear() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ suppressions: [+ BackupV17Fixtures.suppression(+ status: .cleared,+ actionAt: BackupV17Fixtures.created.addingTimeInterval(1_000))+ ])))++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(suppressions: [BackupV17Fixtures.suppression()])))++ let row = try #require(+ try await fixture.repository.m5SuppressionRows()+ .first { $0.id == BackupV17Fixtures.suppressionID })+ #expect(row.status == .cleared)+ }++ // MARK: An archive carrying no characters (Req 6.1)++ /// The other half of Req 6.1: the three character arrays are legitimately+ /// empty, and an archive of a library that has never run an extraction pass+ /// imports with nothing created.+ ///+ /// 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 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 BackupV17Codec.encode(+ payload: BackupV17Fixtures.composedPayload(),+ metadata: BackupV17Fixtures.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(BackupV17Fixtures.entryID) == nil)+ }++ // MARK: The places (Req 5.1, 5.3, 5.5)++ /// 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 16/17 archive commits its places and place suppressions")+ func archiveCommitsPlaces() async throws {+ let fixture = try await M5Fixture()++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.payload()))++ let places = try await fixture.repository.m5AllPlaces()+ let keep = try #require(places.first { $0.id == BackupV17Fixtures.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 == BackupV17Fixtures.workID, "the place joins its work")++ let rows = try await fixture.repository.m5PlaceSuppressionRows()+ let row = try #require(rows.first { $0.id == BackupV17Fixtures.placeSuppressionID })+ #expect(row.nameKey == "low road")+ #expect(row.kind == .candidate)+ #expect(row.status == .active)+ #expect(row.workID == BackupV17Fixtures.workID)+ }++ /// Req 5.5 and Q60: an owner the archive names and this library cannot+ /// resolve is **kept**, not dropped and not rewritten — and the row+ /// re-exports naming the same work, so a restore of a half-synced library+ /// loses nothing.+ @Test("A place whose work resolves to nothing imports and re-exports as it stands")+ func orphanPlaceImportsAndReExports() async throws {+ let absent = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee97")!+ let fixture = try await M5Fixture()++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ places: [+ BackupV17Fixtures.place(+ id: BackupV17Fixtures.orphanPlaceID, workID: absent)+ ],+ placeSuppressions: [BackupV17Fixtures.placeSuppression(workID: absent)])))++ let orphan = try #require(+ try await fixture.repository.m5AllPlaces()+ .first { $0.id == BackupV17Fixtures.orphanPlaceID })+ #expect(orphan.workID == absent)+ #expect(+ try await fixture.repository.m5PlaceSuppressionRows()+ .first { $0.id == BackupV17Fixtures.placeSuppressionID }?.workID == absent)++ let payload = try await fixture.repository.backupV17Snapshot()+ #expect(payload.places.first { $0.id == BackupV17Fixtures.orphanPlaceID }?.workID == absent)+ #expect(payload.placeSuppressions.contains { $0.workID == absent })+ }++ /// Req 5.5 on the **update** path, which is the other side of the orphan the+ /// test above admits: the archive holds place P naming a work this library+ /// does not have, while the reader's own P sits on a work it does.+ ///+ /// Ownership carries no timestamp — `workID` moves without touching+ /// `modifiedAt` — so the merge's `modifiedAt >=` guard cannot see the move,+ /// and writing the archived id would take P off its work and leave it+ /// displayed nowhere. The archive's *content* still applies; only the owner+ /// it names and this library cannot resolve is refused.+ @Test("An archived orphan place does not move a local place off the work it has")+ func archivedOrphanDoesNotMoveALocalPlace() async throws {+ let localWorkID = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee96")!+ let absent = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee97")!+ let older = BackupV17Fixtures.created.addingTimeInterval(-1_000)+ let fixture = try await M5Fixture()+ try await fixture.repository.seedM5Rows(+ sites: [M5SeedSite(hostname: "b.example")],+ works: [+ M5SeedWork(+ id: localWorkID, displayTitle: "The Reader's Own", hostname: "b.example")+ ],+ places: [+ M5SeedPlace(+ id: BackupV17Fixtures.keepID, name: "The Keep", nameKey: "high keep",+ workID: localWorkID, createdAt: older, modifiedAt: older)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(places: [BackupV17Fixtures.place(workID: absent)])))++ let keep = try #require(+ try await fixture.repository.m5AllPlaces()+ .first { $0.id == BackupV17Fixtures.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")+ }++ /// The half the narrowing keeps: a local place whose own `workID` resolves+ /// to nothing has no owner to lose, so it **adopts** the archived one — which+ /// is how a row that synced ahead of its work heals from a restore.+ @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 = BackupV17Fixtures.created.addingTimeInterval(-1_000)+ let fixture = try await M5Fixture()+ try await fixture.repository.seedM5Rows(+ places: [+ M5SeedPlace(+ id: BackupV17Fixtures.keepID, name: "The Keep", nameKey: "high keep",+ workID: unresolvable, createdAt: older, modifiedAt: older)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.payload()))++ let keep = try #require(+ try await fixture.repository.m5AllPlaces()+ .first { $0.id == BackupV17Fixtures.keepID })+ #expect(keep.workID == BackupV17Fixtures.workID)+ #expect(keep.name == "The High Keep")+ }++ /// The suppression twin of the two above (Q76). A suppression's owner has no+ /// timestamp either — `actionAt` moves with the reader's action, not with+ /// ownership — so an archived row naming a work this library cannot resolve+ /// would take a local suppression off the work it is on, and a suppression+ /// displaced from its work suppresses nothing: the name the reader refused+ /// comes back at the next pass.+ @Test("An archived orphan place suppression does not move a local one off its work")+ func archivedOrphanDoesNotMoveAPlaceSuppression() async throws {+ let localWorkID = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee94")!+ let absent = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee97")!+ let older = BackupV17Fixtures.created.addingTimeInterval(-1_000)+ let fixture = try await M5Fixture()+ try await fixture.repository.seedM5Rows(+ sites: [M5SeedSite(hostname: "b.example")],+ works: [+ M5SeedWork(+ id: localWorkID, displayTitle: "The Reader's Own", hostname: "b.example")+ ],+ placeSuppressions: [+ M5SeedPlaceSuppression(+ id: BackupV17Fixtures.placeSuppressionID, workID: localWorkID,+ nameKey: "old key", actionAt: older)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ placeSuppressions: [BackupV17Fixtures.placeSuppression(workID: absent)])))++ let row = try #require(+ try await fixture.repository.m5PlaceSuppressionRows()+ .first { $0.id == BackupV17Fixtures.placeSuppressionID })+ #expect(+ row.workID == localWorkID,+ "an owner that resolves to nothing never moves a suppression")+ #expect(row.nameKey == "low road", "the archive's content still applies")+ }++ /// The idempotence half, over the two arrays this generation adds: a second+ /// import of the same file writes nothing.+ @Test("Importing the same 16/17 archive twice leaves the places untouched")+ func importingTwiceLeavesPlacesUntouched() async throws {+ let fixture = try await M5Fixture()+ let plan = BackupV17Fixtures.plan(BackupV17Fixtures.payload())++ try await fixture.repository.confirmImport(plan: plan)+ let placesAfterFirst = try await fixture.repository.m5AllPlaces()+ let suppressionsAfterFirst = try await fixture.repository.m5PlaceSuppressionRows()++ try await fixture.repository.confirmImport(plan: plan)++ #expect(try await fixture.repository.m5AllPlaces() == placesAfterFirst)+ #expect(try await fixture.repository.m5PlaceSuppressionRows() == suppressionsAfterFirst)+ #expect(placesAfterFirst.count == 1)+ #expect(suppressionsAfterFirst.count == 1)+ }++ /// Req 5.1's value guard: `modifiedAt` decides, both ways, so an older+ /// archive cannot regress a newer edit and a newer one applies.+ @Test("The place guard is modifiedAt, in both directions")+ func placeModificationGuard() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.payload()))++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ places: [+ BackupV17Fixtures.place(+ name: "Renamed by an older device", note: "older",+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(-1_000))+ ])))++ var keep = try #require(+ try await fixture.repository.m5AllPlaces()+ .first { $0.id == BackupV17Fixtures.keepID })+ #expect(keep.name == "The High Keep")+ #expect(keep.note == "The fortress above the pass.")++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ places: [+ BackupV17Fixtures.place(+ name: "The Keep Above the Pass", note: "Still standing.",+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(1_000))+ ])))++ keep = try #require(+ try await fixture.repository.m5AllPlaces()+ .first { $0.id == BackupV17Fixtures.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.+ #expect(keep.nameKey == "high keep")+ }++ /// Req 5.1's other guard: a place suppression converges on `actionAt`, so an+ /// archived row cannot undo a newer clear — the character rule, applied to+ /// the table that keeps it separate (Decision 2).+ @Test("A place suppression older than the stored row does not undo a clear")+ func olderPlaceSuppressionDoesNotUndoAClear() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ placeSuppressions: [+ BackupV17Fixtures.placeSuppression(+ status: .cleared,+ actionAt: BackupV17Fixtures.created.addingTimeInterval(1_000))+ ])))++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.payload(+ placeSuppressions: [BackupV17Fixtures.placeSuppression()])))++ let row = try #require(+ try await fixture.repository.m5PlaceSuppressionRows()+ .first { $0.id == BackupV17Fixtures.placeSuppressionID })+ #expect(row.status == .cleared)+ }++ // MARK: Series and links (`series-and-related-works` Req 13.3, 13.4)++ /// Req 13.3: a restore into an empty library reproduces the series, the+ /// memberships and the links exactly, and running it again changes nothing.+ @Test("An import into an empty library reproduces series, memberships and links")+ func seriesAndLinksImportWhole() async throws {+ let fixture = try await M5Fixture()+ let plan = BackupV17Fixtures.plan(BackupV17Fixtures.seriesPayload())++ try await fixture.repository.confirmImport(plan: plan)++ let series = try await fixture.repository.seriesRowValues()+ #expect(series.map(\.id) == [BackupV17Fixtures.seriesID])+ #expect(series.first?.name == "Ashfall Cycle")+ #expect(series.first?.notes == "Read 2.5 after 2.")+ #expect(+ try await fixture.repository.membershipColumns(of: BackupV17Fixtures.composedWorkID)+ == [SeriesColumns(seriesID: BackupV17Fixtures.seriesID, position: 1)])+ #expect(+ try await fixture.repository.membershipColumns(of: BackupV17Fixtures.secondWorkID)+ == [SeriesColumns(seriesID: BackupV17Fixtures.seriesID, position: 2.5)])+ let links = try await fixture.repository.workLinkRowValues()+ #expect(links.map(\.id) == [BackupV17Fixtures.linkID])+ #expect(links.first?.linkType == "adaptation")++ // A repeated import writes the same values back and removes nothing.+ try await fixture.repository.confirmImport(plan: plan)+ #expect(try await fixture.repository.seriesRowValues() == series)+ #expect(try await fixture.repository.workLinkRowValues() == links)+ }++ /// Req 13.4's guard, both halves. A record at least as recent as the row+ /// wins; an older one writes nothing. Neither ever deletes: a series or a+ /// link the library holds and the archive does not is one the reader made on+ /// another device.+ @Test("commitSeries and commitLinks respect the modification guard and delete nothing")+ func seriesAndLinkGuards() async throws {+ let fixture = try await M5Fixture()+ let local = UUID(uuidString: "5E81E5A0-0000-4000-8000-0000000000ff")!+ let localLink = UUID(uuidString: "11115E51-0000-4000-8000-0000000000ff")!+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.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: BackupV17Fixtures.composedWorkID,+ b: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee97")!, type: "prequel")+ ])+ try await fixture.repository.updateSeries(+ id: BackupV17Fixtures.seriesID, name: "Renamed here", notes: "later")+ try await fixture.repository.retypeLink(+ id: BackupV17Fixtures.linkID, type: "retyped here")++ // The same archive again: its records are now older than both rows.+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.seriesPayload()))++ let afterOlder = try await fixture.repository.seriesRowValues()+ #expect(afterOlder.first { $0.id == BackupV17Fixtures.seriesID }?.name == "Renamed here")+ #expect(+ try await fixture.repository.workLinkRowValues()+ .first { $0.id == BackupV17Fixtures.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))++ // A newer archive does win, on both tables.+ // Later than the *local* edits, which the fixture clock stamped at its+ // own epoch — not merely later than the archive's own `created`.+ let later = M5Fixture.epoch.addingTimeInterval(3_600)+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.seriesPayload(+ series: [+ BackupV17Fixtures.seriesRecord(name: "Renamed there", modifiedAt: later)+ ],+ links: [BackupV17Fixtures.linkRecord(type: "retyped there", modifiedAt: later)])))++ #expect(+ try await fixture.repository.seriesRowValues()+ .first { $0.id == BackupV17Fixtures.seriesID }?.name == "Renamed there")+ #expect(+ try await fixture.repository.workLinkRowValues()+ .first { $0.id == BackupV17Fixtures.linkID }?.linkType == "retyped there")+ }++ /// Req 13.5's tolerated half, at the store rather than on the wire: a work+ /// naming a series this library does not hold keeps the id, and a link+ /// naming an absent work keeps both ends. Neither is cleared by the+ /// reconcile pass the import fires.+ @Test("An unresolved membership and an unresolved link survive the import")+ func unresolvedReferencesSurviveTheImport() async throws {+ let fixture = try await M5Fixture()+ let absentSeries = UUID(uuidString: "5E81E5A0-0000-4000-8000-000000000009")!+ let absentWork = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee99")!+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.seriesPayload(+ links: [+ BackupV17Fixtures.linkRecord(+ a: BackupV17Fixtures.composedWorkID, b: absentWork, type: "spin-off")+ ],+ firstMembership: (absentSeries, 3))))++ #expect(+ try await fixture.repository.membershipColumns(of: BackupV17Fixtures.composedWorkID)+ == [SeriesColumns(seriesID: absentSeries, position: 3)])+ let links = try await fixture.repository.workLinkRowValues()+ #expect(links.count == 1)+ #expect(links.first?.linkType == "spin-off")+ }++ // MARK: Creators, roles and credits (`work-creators` Req 9.3, 9.4)++ /// Req 9.3: a restore into a library holding no record a reader has touched+ /// — three seeded roles and nothing else — reproduces the archive's+ /// creators, roles, states, list order and credits exactly, seeded records+ /// yielding to the archive's records of the same defaults (Q28). Running it+ /// again changes nothing.+ @Test("An import into a seeds-only library reproduces creators, roles and credits")+ func creatorsImportWhole() async throws {+ let fixture = try await M5Fixture()+ let plan = BackupV17Fixtures.plan(BackupV17Fixtures.creditsPayload())++ try await fixture.repository.confirmImport(plan: plan)++ let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+ let mori = try #require(creators[BackupV17Fixtures.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 == BackupV17Fixtures.created)+ #expect(mori.notesModifiedAt == BackupV17Fixtures.created)+ let alias = try #require(creators[BackupV17Fixtures.aliasID])+ #expect(alias.state == .merged)+ #expect(alias.canonicalID == BackupV17Fixtures.moriID)+ // A credit naming the alias reads as its survivor on arrival.+ #expect(creators.canonicalID(of: BackupV17Fixtures.aliasID) == BackupV17Fixtures.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[BackupV17Fixtures.lettererRoleID]?.position == 3)+ #expect(roles[BackupV17Fixtures.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[BackupV17Fixtures.authorRoleID]?.isPristine == true)++ let credits = try await fixture.repository.creditRows()+ #expect(credits.count == 3)+ let credit = try #require(credits.first { $0.id == BackupV17Fixtures.moriCreditID })+ #expect(+ credit.roleIDs+ == [+ BackupV17Fixtures.authorRoleID.uuidString,+ BackupV17Fixtures.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 == BackupV17Fixtures.orphanCreditID })++ let creatorsAfterFirst = try await fixture.repository.creatorRowValues()+ let rolesAfterFirst = try await fixture.repository.creatorRoleRowValues()+ let creditsAfterFirst = try await fixture.repository.creditRows()++ try await fixture.repository.confirmImport(plan: plan)++ #expect(try await fixture.repository.creatorRowValues() == creatorsAfterFirst)+ #expect(try await fixture.repository.creatorRoleRowValues() == rolesAfterFirst)+ #expect(try await fixture.repository.creditRows() == creditsAfterFirst)+ }++ /// Req 9.4's identifier match, field by field (Q50). The archive's name is+ /// older than the local one and does not stand; its notes are the only thing+ /// that has ever been written to that field and do.+ @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 = BackupV17Fixtures.created.addingTimeInterval(1_000)+ try await fixture.repository.seedCreators([+ SeedCreator(+ id: BackupV17Fixtures.moriID, name: "Renamed here",+ nameModifiedAt: later, createdAt: BackupV17Fixtures.created)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.creditsPayload()))++ let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+ let mori = try #require(creators[BackupV17Fixtures.moriID])+ #expect(mori.name == "Renamed here")+ #expect(mori.nameModifiedAt == later)+ #expect(mori.notes == "Also draws.")+ #expect(mori.notesModifiedAt == BackupV17Fixtures.created)+ }++ /// The other half of the rule: an archive field nobody has ever touched+ /// never overrides a local one a reader has (Q28, Q31). The archive's record+ /// of a default is pristine; the local one has been renamed.+ @Test("A pristine archive field never overrides a reader-touched local one")+ func pristineArchiveFieldNeverStands() async throws {+ let fixture = try await M5Fixture()+ let touched = BackupV17Fixtures.created.addingTimeInterval(1_000)+ // A second row of the seeded identity, carrying the reader's rename.+ try await fixture.repository.seedCreatorRoles([+ SeedCreatorRole(+ id: BackupV17Fixtures.authorRoleID, name: "writer", position: 0,+ nameModifiedAt: touched)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.creditsPayload()))++ let roles = CreatorRoleDirectory(+ rows: try await fixture.repository.creatorRoleRowValues())+ #expect(roles[BackupV17Fixtures.authorRoleID]?.name == "writer")+ }++ /// Req 9.4: `merged` is terminal on the **local** side. An identity that+ /// merged into something is not a state an archive can undo, however late+ /// the archive's stamp — while an archived merge naming a survivor this+ /// library can read is applied, and the chain it makes is collapsed in the+ /// same commit (Q40).+ ///+ /// Both arms are decided by the archive's stamp being the *later* one, so+ /// the terminality is what keeps `mori` merged rather than the ordinary+ /// per-field guard agreeing by accident.+ @Test("A merged state is terminal on the local side of an identifier match")+ func mergedStateIsTerminal() async throws {+ let fixture = try await M5Fixture()+ let survivor = UUID(uuidString: "c8ea1080-0000-4000-8000-0000000000a1")!+ let later = BackupV17Fixtures.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: BackupV17Fixtures.created),+ SeedCreator(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane", state: .merged,+ canonicalID: survivor,+ nameModifiedAt: BackupV17Fixtures.created,+ stateModifiedAt: BackupV17Fixtures.created),+ // Locally active, and the archive says it merged into `mori`, which+ // resolves here to `survivor`: the archive's later stamp applies.+ SeedCreator(+ id: BackupV17Fixtures.aliasID, name: "mori ayane",+ nameModifiedAt: BackupV17Fixtures.created.addingTimeInterval(2_000),+ stateModifiedAt: BackupV17Fixtures.created),+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ notes: "Also draws.", stateModifiedAt: later),+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.studioID, name: "Studio Lantern"),+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.aliasID, name: "mori ayane",+ state: .merged, canonicalID: BackupV17Fixtures.moriID,+ stateModifiedAt: later),+ ])))++ let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+ let mori = try #require(creators[BackupV17Fixtures.moriID])+ #expect(mori.state == .merged)+ #expect(mori.canonicalID == survivor)+ let alias = try #require(creators[BackupV17Fixtures.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.+ #expect(alias.canonicalID == survivor)+ }++ /// The blocker Q71 answers. Q68 exports a merged record whose chain this+ /// archive cannot end with **no** survivor; applying that to a creator the+ /// library still holds would leave it merged into nothing — hidden and+ /// unresolved everywhere, with no un-merge to undo it.+ @Test("An archived merge carrying no survivor leaves a live creator active")+ func survivorlessArchivedMergeLeavesTheCreatorActive() async throws {+ let fixture = try await M5Fixture()+ let later = BackupV17Fixtures.created.addingTimeInterval(3_000)+ try await fixture.repository.seedCreators([+ SeedCreator(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ nameModifiedAt: BackupV17Fixtures.created,+ stateModifiedAt: BackupV17Fixtures.created)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ state: .merged, canonicalID: nil, stateModifiedAt: later)+ ])))++ let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+ #expect(creators[BackupV17Fixtures.moriID]?.state == .active)+ #expect(creators.options.contains { $0.name == "Mori Ayane" })+ }++ /// Q68's other half. The guard above is about a record the library still+ /// holds; where it holds **none**, there is nothing to leave alone, and the+ /// insert arm writes the record exactly as the file carries it — merged,+ /// with no survivor. That is what makes a repeated import a no-op instead of+ /// a state that changes on every pass.+ @Test("An archive-only merged record carrying no survivor is inserted as it stands")+ func survivorlessArchivedMergeIsInsertedPreserved() async throws {+ let fixture = try await M5Fixture()++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ state: .merged, canonicalID: nil)+ ])))++ let rows = try await fixture.repository.creatorRowValues()+ let row = try #require(rows.first { $0.id == BackupV17Fixtures.moriID })+ #expect(row.stateRaw == CreatorState.merged.rawValue)+ #expect(row.canonicalID == nil, "the survivorless pointer is kept, not invented")+ #expect(+ CreatorDirectory(rows: rows)[BackupV17Fixtures.moriID]?.state == .merged,+ "and the same commit's reconcile leaves it there — there is no chain to collapse")+ }++ /// The same guard over a survivor that is merely *absent*: a merge is a+ /// state and a survivor together, and a pointer nothing here resolves is+ /// not one this library can act on (Req 9.4, Q71).+ @Test("An archived merge naming an absent survivor leaves a live creator active")+ func archivedMergeNamingAnAbsentSurvivorIsSkipped() async throws {+ let fixture = try await M5Fixture()+ let later = BackupV17Fixtures.created.addingTimeInterval(3_000)+ try await fixture.repository.seedCreators([+ SeedCreator(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ nameModifiedAt: BackupV17Fixtures.created,+ stateModifiedAt: BackupV17Fixtures.created)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ state: .merged, canonicalID: BackupV17Fixtures.absentCreatorID,+ stateModifiedAt: later)+ ])))++ let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+ #expect(creators[BackupV17Fixtures.moriID]?.state == .active)+ }++ /// And the positive case: a survivor the archive itself carries, on a+ /// record whose state stamp beats the local one, merges as recorded.+ @Test("An archived merge naming a present survivor and stamped later applies")+ func archivedMergeWithAPresentSurvivorApplies() async throws {+ let fixture = try await M5Fixture()+ let later = BackupV17Fixtures.created.addingTimeInterval(3_000)+ try await fixture.repository.seedCreators([+ SeedCreator(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ nameModifiedAt: BackupV17Fixtures.created,+ stateModifiedAt: BackupV17Fixtures.created)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ state: .merged, canonicalID: BackupV17Fixtures.studioID,+ stateModifiedAt: later),+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.studioID, name: "Studio Lantern"),+ ])))++ let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+ let mori = try #require(creators[BackupV17Fixtures.moriID])+ #expect(mori.state == .merged)+ #expect(mori.canonicalID == BackupV17Fixtures.studioID)+ }++ /// The stamp rule holds for a merge like any other field: an archive older+ /// than the local state writes nothing, so a creator the reader has used+ /// since the archive was taken is not merged out from under them.+ @Test("An archived merge older than the local state writes nothing")+ func archivedMergeOlderThanTheLocalStateIsIgnored() async throws {+ let fixture = try await M5Fixture()+ let touched = BackupV17Fixtures.created.addingTimeInterval(3_000)+ try await fixture.repository.seedCreators([+ SeedCreator(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ nameModifiedAt: touched, stateModifiedAt: touched)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.moriID, name: "Mori Ayane",+ state: .merged, canonicalID: BackupV17Fixtures.studioID),+ BackupV17Fixtures.creatorRecord(+ id: BackupV17Fixtures.studioID, name: "Studio Lantern"),+ ])))++ let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+ #expect(creators[BackupV17Fixtures.moriID]?.state == .active)+ }++ /// Q54: an archive record matching a local one **by name only** is inserted+ /// as recorded, and the same commit runs the creator reconciler, whose+ /// election is Req 10.3's. Both records survive; one of them is an alias+ /// afterwards, and nothing was written twice.+ @Test("A name-only match inserts as recorded and the same commit elects")+ func nameOnlyMatchElectsInTheSameCommit() async throws {+ let fixture = try await M5Fixture()+ let local = UUID(uuidString: "c8ea1080-0000-4000-8000-0000000000b1")!+ try await fixture.repository.seedCreators([+ SeedCreator(+ id: local, name: "Mori Ayane",+ nameModifiedAt: BackupV17Fixtures.created.addingTimeInterval(-1_000),+ createdAt: BackupV17Fixtures.created.addingTimeInterval(-1_000))+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.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[BackupV17Fixtures.moriID] != nil)+ // The earliest-created non-pristine identity survives, and the other+ // reads as it (Req 10.3).+ #expect(creators.canonicalID(of: BackupV17Fixtures.moriID) == local)+ #expect(creators.options.count(where: { $0.name == "Mori Ayane" }) == 1)+ }++ /// Req 9.4's list rule (Q38). The reader has an order here, so an+ /// archive-only role is appended **after** it rather than dropped into the+ /// middle of it, and its placement is stamped at import time so a+ /// later-arriving sync row carrying the archive's own position cannot undo+ /// it.+ @Test("An archive-only role is appended after a reader-touched list, stamped at import")+ func archiveOnlyRoleIsAppended() async throws {+ let fixture = try await M5Fixture()+ let colorist = UUID(uuidString: "e0000006-0000-4000-8000-000000000006")!+ try await fixture.repository.seedCreatorRoles([+ SeedCreatorRole(+ id: colorist, name: "colorist", position: 3,+ nameModifiedAt: BackupV17Fixtures.created,+ positionModifiedAt: BackupV17Fixtures.created,+ createdAt: BackupV17Fixtures.created)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.creditsPayload()))++ let roles = CreatorRoleDirectory(+ rows: try await fixture.repository.creatorRoleRowValues())+ let letterer = try #require(roles[BackupV17Fixtures.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"])+ }++ /// Req 9.4's per-field rule over a role's **state**, both ways round: an+ /// archived removal later than the local row hides the role, and an+ /// archived `active` later than a local removal brings it back+ /// ([2.2](../../../../specs/work-creators/requirements.md#2.2)).+ @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 = BackupV17Fixtures.created.addingTimeInterval(1_000)+ try await fixture.repository.seedCreatorRoles([+ SeedCreatorRole(+ id: BackupV17Fixtures.lettererRoleID, name: "letterer", position: 3,+ nameModifiedAt: BackupV17Fixtures.created,+ positionModifiedAt: BackupV17Fixtures.created,+ stateModifiedAt: BackupV17Fixtures.created,+ createdAt: BackupV17Fixtures.created),+ SeedCreatorRole(+ id: BackupV17Fixtures.editorRoleID, name: "editor", position: 4,+ state: .removed,+ nameModifiedAt: BackupV17Fixtures.created,+ positionModifiedAt: BackupV17Fixtures.created,+ stateModifiedAt: BackupV17Fixtures.created,+ createdAt: BackupV17Fixtures.created),+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ creatorRoles: BackupV17Fixtures.seededRoleRecords + [+ BackupV17Fixtures.creatorRoleRecord(+ id: BackupV17Fixtures.lettererRoleID, name: "letterer",+ position: 3, state: .removed, stateModifiedAt: later),+ BackupV17Fixtures.creatorRoleRecord(+ id: BackupV17Fixtures.editorRoleID, name: "editor",+ position: 4, stateModifiedAt: later),+ ])))++ let roles = CreatorRoleDirectory(+ rows: try await fixture.repository.creatorRoleRowValues())+ #expect(roles[BackupV17Fixtures.lettererRoleID]?.state == .removed)+ #expect(roles[BackupV17Fixtures.lettererRoleID]?.stateModifiedAt == later)+ #expect(roles[BackupV17Fixtures.editorRoleID]?.state == .active)+ #expect(roles[BackupV17Fixtures.editorRoleID]?.stateModifiedAt == later)+ }++ /// The other half: an archived state older than the local one writes+ /// nothing, so a removal the reader made after the archive was taken is not+ /// undone by restoring it.+ @Test("An archived role state older than the local one writes nothing")+ func archivedRoleStateOlderThanTheLocalOneIsIgnored() async throws {+ let fixture = try await M5Fixture()+ let touched = BackupV17Fixtures.created.addingTimeInterval(2_000)+ try await fixture.repository.seedCreatorRoles([+ SeedCreatorRole(+ id: BackupV17Fixtures.lettererRoleID, name: "letterer", position: 3,+ state: .removed,+ nameModifiedAt: BackupV17Fixtures.created,+ positionModifiedAt: BackupV17Fixtures.created,+ stateModifiedAt: touched,+ createdAt: BackupV17Fixtures.created)+ ])++ // The archive's `letterer` is active, stamped at `created`.+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.creditsPayload()))++ let roles = CreatorRoleDirectory(+ rows: try await fixture.repository.creatorRoleRowValues())+ #expect(roles[BackupV17Fixtures.lettererRoleID]?.state == .removed)+ #expect(roles[BackupV17Fixtures.lettererRoleID]?.stateModifiedAt == touched)+ }++ /// Req 9.4's append, over **every** archive-only role rather than the+ /// active ones only, and after the maximum of every non-merged local place.+ /// A removed role keeps its position so that restoring it returns it to the+ /// list; an append that ignored it would land on top of it.+ @Test("An archive-only role appends past a removed local role, whatever its own state")+ func archiveOnlyRolesAppendPastRemovedOnes() async throws {+ let fixture = try await M5Fixture()+ let colorist = UUID(uuidString: "e0000006-0000-4000-8000-000000000006")!+ try await fixture.repository.seedCreatorRoles([+ SeedCreatorRole(+ id: colorist, name: "colorist", position: 3, state: .removed,+ nameModifiedAt: BackupV17Fixtures.created,+ positionModifiedAt: BackupV17Fixtures.created,+ stateModifiedAt: BackupV17Fixtures.created,+ createdAt: BackupV17Fixtures.created)+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.creditsPayload()))++ let roles = CreatorRoleDirectory(+ rows: try await fixture.repository.creatorRoleRowValues())+ let letterer = try #require(roles[BackupV17Fixtures.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[BackupV17Fixtures.editorRoleID])+ #expect(editor.state == .removed)+ #expect(editor.position == 5)+ #expect(editor.positionModifiedAt == M5Fixture.epoch)+ let places = roles.identities.filter { $0.state != .merged }.map(\.position)+ #expect(Set(places).count == places.count, "no two visible roles share a place")+ }++ /// Req 9.4's credit guard, `commitLinks`' with Q67's tie. A record older+ /// than the row writes nothing; a newer one wins outright; on an **equal**+ /// stamp only a superset stands, so an archive taken before a collapse+ /// cannot narrow the union that collapse left behind.+ @Test("commitCredits respects the modification guard, and a tie only widens")+ func creditGuardHoldsBothWays() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.creditsPayload()))+ let stored = [+ BackupV17Fixtures.authorRoleID.uuidString,+ BackupV17Fixtures.editorRoleID.uuidString,+ ].sorted()++ func reimport(roleIDs: [UUID], modifiedAt: Date) async throws {+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ credits: [+ BackupV17Fixtures.creditRecord(+ id: BackupV17Fixtures.moriCreditID,+ workID: BackupV17Fixtures.composedWorkID,+ creatorID: BackupV17Fixtures.moriID,+ roleIDs: roleIDs, modifiedAt: modifiedAt)+ ])))+ }++ func roleIDs() async throws -> [String] {+ try await fixture.repository.creditRows()+ .first { $0.id == BackupV17Fixtures.moriCreditID }?.roleIDs ?? []+ }++ // Older: nothing moves.+ try await reimport(+ roleIDs: [BackupV17Fixtures.artistRoleID],+ modifiedAt: BackupV17Fixtures.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: [BackupV17Fixtures.authorRoleID], modifiedAt: BackupV17Fixtures.created)+ #expect(try await roleIDs() == stored)++ // Equal, and a superset: the archive widens it.+ try await reimport(+ roleIDs: [+ BackupV17Fixtures.authorRoleID, BackupV17Fixtures.editorRoleID,+ BackupV17Fixtures.translatorRoleID,+ ], modifiedAt: BackupV17Fixtures.created)+ #expect(try await roleIDs().contains(BackupV17Fixtures.translatorRoleID.uuidString))++ // Strictly later: the archive wins outright, narrowing included.+ try await reimport(+ roleIDs: [BackupV17Fixtures.artistRoleID],+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(1_000))+ #expect(try await roleIDs() == [BackupV17Fixtures.artistRoleID.uuidString])+ }++ /// Req 9.4's last clause: a pair the import leaves held twice converges per+ /// Req 10.5 **in the same commit**, on the canonical creator — so a credit+ /// naming an alias and the archive's credit naming its survivor end as one+ /// row carrying both role sets, without waiting for the next sync.+ @Test("A pair held twice after the import converges in the same commit")+ func duplicatePairConvergesInTheImport() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.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: BackupV17Fixtures.composedWorkID,+ creatorID: BackupV17Fixtures.aliasID,+ roleIDs: [BackupV17Fixtures.translatorRoleID.uuidString])+ ])++ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.creditsPayload()))++ let rows = try await fixture.repository.creditRows()+ .filter { $0.workID == BackupV17Fixtures.composedWorkID }+ #expect(rows.map(\.id) == [BackupV17Fixtures.moriCreditID])+ #expect(+ rows.first?.roleIDs+ == [+ BackupV17Fixtures.authorRoleID.uuidString,+ BackupV17Fixtures.editorRoleID.uuidString,+ BackupV17Fixtures.translatorRoleID.uuidString,+ ].sorted())+ }++ /// Q70, amended: the dedupe runs whenever the archive carried creators or+ /// roles, not only when it carried credits. An archived **rename** can+ /// collide two local creators, the election merges one into the other in+ /// this same commit, and two credits the library already held then name one+ /// pair — a state the file's own empty credit table says nothing about.+ @Test("An archive with no credits still converges a pair its rename collided")+ func renameCollisionConvergesCreditsWithoutArchivedCredits() async throws {+ let fixture = try await M5Fixture()+ let kept = UUID(uuidString: "c8ea1080-0000-4000-8000-0000000000d1")!+ let renamed = UUID(uuidString: "c8ea1080-0000-4000-8000-0000000000d2")!+ let keptCredit = UUID(uuidString: "c8ed1700-0000-4000-8000-0000000000d1")!+ let otherCredit = UUID(uuidString: "c8ed1700-0000-4000-8000-0000000000d2")!+ try await fixture.repository.seedCreators([+ SeedCreator(+ id: kept, name: "Mori Ayane",+ nameModifiedAt: BackupV17Fixtures.created,+ createdAt: BackupV17Fixtures.created),+ SeedCreator(+ id: renamed, name: "Ayane Mori",+ nameModifiedAt: BackupV17Fixtures.created,+ createdAt: BackupV17Fixtures.created.addingTimeInterval(1_000)),+ ])+ try await fixture.repository.seedCredits([+ SeedCredit(+ id: keptCredit, workID: BackupV17Fixtures.composedWorkID, creatorID: kept,+ roleIDs: [BackupV17Fixtures.authorRoleID.uuidString],+ createdAt: BackupV17Fixtures.created,+ modifiedAt: BackupV17Fixtures.created),+ SeedCredit(+ id: otherCredit, workID: BackupV17Fixtures.composedWorkID,+ creatorID: renamed,+ roleIDs: [BackupV17Fixtures.artistRoleID.uuidString],+ createdAt: BackupV17Fixtures.created.addingTimeInterval(1_000),+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(1_000)),+ ])++ // Creators only: no roles, and no credits at all.+ try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.creditsPayload(+ creators: [+ BackupV17Fixtures.creatorRecord(+ id: renamed, name: "Mori Ayane",+ nameModifiedAt: BackupV17Fixtures.created+ .addingTimeInterval(2_000),+ createdAt: BackupV17Fixtures.created.addingTimeInterval(1_000))+ ],+ creatorRoles: [], credits: [])))++ let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+ #expect(creators.canonicalID(of: renamed) == kept)++ let rows = try await fixture.repository.creditRows()+ .filter { $0.workID == BackupV17Fixtures.composedWorkID }+ #expect(rows.map(\.id) == [keptCredit])+ #expect(+ rows.first?.roleIDs+ == [+ BackupV17Fixtures.authorRoleID.uuidString,+ BackupV17Fixtures.artistRoleID.uuidString,+ ].sorted())+ }++ // MARK: The round trip (Req 6.1)++ /// The two halves meeting through the real exporter, the real codec and the+ /// real gate: a library holding characters, places, both suppression tables,+ /// coverage and **a cover**, exported and restored into a different one.+ ///+ /// Req 8.1's round trip is byte identity, and only this test crosses every+ /// 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 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: BackupV17Fixtures.plan(BackupV17Fixtures.coveredPayload()))++ let payload = try await source.repository.backupV17Snapshot()+ let plan = try BackupImporter.plan(+ from: try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.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 == BackupV17Fixtures.groverID })+ #expect(grover.name == "Grover")+ #expect(grover.facts.map(\.quote) == ["promised to guide them home"])+ #expect(grover.workID == BackupV17Fixtures.workID)+ #expect(+ try await target.repository.m5SuppressionRows()+ .contains { $0.id == BackupV17Fixtures.suppressionID })+ #expect(+ try await target.repository.m5EntryCoverage(BackupV17Fixtures.entryID)+ == BackupV17Fixtures.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 == BackupV17Fixtures.keepID })+ #expect(keep.name == "The High Keep")+ #expect(keep.facts.map(\.quote) == ["above the pass"])+ #expect(keep.workID == BackupV17Fixtures.workID)+ #expect(+ try await target.repository.m5PlaceSuppressionRows()+ .contains { $0.id == BackupV17Fixtures.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: BackupV17Fixtures.workID)+ == [ThumbnailColumns(+ byteCount: BackupV17Fixtures.coverBytes.count,+ shapeRaw: ThumbnailShape.portrait.rawValue,+ digest: BackupV17Fixtures.coverDigest)])+ #expect(+ try await target.repository.thumbnailBytes(+ workID: BackupV17Fixtures.workID, digest: BackupV17Fixtures.coverDigest)+ == BackupV17Fixtures.coverBytes)+ }++ /// `catch-up-mode` Q6: the fourth reading status is vocabulary, not+ /// 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+ /// the projection or the commit dropped would land back as the column's+ /// 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 16/17")+ func catchingUpRoundTrips() async throws {+ let source = try await M5Fixture()+ try await source.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.composedPayload(readingStatus: .catchingUp)))++ let payload = try await source.repository.backupV17Snapshot()+ #expect(+ payload.works.first { $0.id == BackupV17Fixtures.composedWorkID }?.readingStatus+ == .catchingUp)++ let encoded = try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).backupFormatVersion == 17)++ let target = try await M5Fixture()+ try await target.repository.confirmImport(plan: try BackupImporter.plan(from: encoded))++ #expect(+ try await target.repository.work(id: BackupV17Fixtures.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** 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 16/17")+ func toReadRoundTrips() async throws {+ let source = try await M5Fixture()+ try await source.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.composedPayload(readingStatus: .toRead)))++ let payload = try await source.repository.backupV17Snapshot()+ #expect(+ payload.works.first { $0.id == BackupV17Fixtures.composedWorkID }?.readingStatus+ == .toRead)++ let encoded = try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Fixtures.metadata())+ #expect(try BackupV17Codec.decode(encoded).backupFormatVersion == 17)++ let target = try await M5Fixture()+ try await target.repository.confirmImport(plan: try BackupImporter.plan(from: encoded))++ let restored = try await target.repository.work(id: BackupV17Fixtures.composedWorkID)+ #expect(restored.readingStatus == .toRead)+ #expect(restored.entries.count == 1)+ }++ // MARK: - T-2334: a no-op re-import dirties nothing++ /// The bug T-2334 tracks: the upsert's `apply` functions wrote every+ /// scalar column unconditionally, so a second import of an archive the+ /// library already matches reported pending changes at every save while+ /// writing back identical values — dirtying every row of a re-imported+ /// archive and, under mirroring, re-exporting every one of them for+ /// nothing.+ ///+ /// Driven over `BackupGoldenLibrary.payload`, which carries one record of+ /// 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+ /// happens to cover.+ ///+ /// `hasChanges` is read immediately **before** each armed save, since+ /// `ModelContext.save()` clears whatever it reports; a context that goes+ /// into a save already clean is one the second import wrote nothing into.+ @Test("A second import of an unchanged archive dirties no save")+ func aSecondImportOfAnUnchangedArchiveDirtiesNoSave() async throws {+ let strategy = ChangeRecordingSaveStrategy()+ let fixture = try await M5Fixture(saveStrategy: strategy)+ let payload = BackupGoldenLibrary.payload++ try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(payload))+ let firstImport = try await fixture.repository.backupV17Snapshot()++ strategy.arm()+ try await fixture.repository.confirmImport(plan: BackupV17Fixtures.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.backupV17Snapshot() == firstImport)+ }++ /// The citation arm of the guard above, in one context so the store itself+ /// answers, on the cover test's shape. Four states: a blob that decodes to+ /// what the archive carries dirties nothing; bytes that will not decode are+ /// **rewritten** — the reason the guard is a decode-and-compare rather than+ /// a byte comparison, and the row `drop-superseded-columns` Q24 promises a+ /// restore heals; a **nil** blob is converted even against an archive+ /// carrying the default, because `citations` reads it as the default and+ /// the validator promises the archive repairs it (`drop-superseded-columns`+ /// Q25); and bytes that decode to something *different* are written, so+ /// the guard's `!=` cannot be flipped without a test noticing. Each arm is+ /// pinned here rather than traced through `editCitations` by hand, because+ /// 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: AsterismSchemaV18.self)+ let container = try ModelContainer(+ for: schema,+ configurations: [+ ModelConfiguration(+ schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ ])+ let context = ModelContext(container)+ context.autosaveEnabled = false+ let record = try #require(BackupV17Fixtures.minimalTaughtPayload().entries.first)+ #expect(record.citations != EntryCitations(), "the arm needs a non-default value to compare")+ let entry = ArchiveRecordBuilders.makeEntry(record)+ context.insert(entry)+ try context.save()+ #expect(try entry.citations == record.citations)++ LibraryRepository.apply(record, to: entry)+ #expect(!context.hasChanges, "a second import of the same citations must write nothing")++ // Req 1.8's tolerated row: bytes are present and will not decode. The+ // restore is what heals it, so this one *must* write.+ entry.citationsData = Data("not json".utf8)+ try context.save()+ LibraryRepository.apply(record, to: entry)+ #expect(context.hasChanges, "a restore must heal a row whose citations will not decode")+ #expect(try entry.citations == record.citations)+ try context.save()++ // The same row against an archive carrying the *default* citations: a+ // 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 = BackupV17Entry(+ id: record.id, captureTitle: record.captureTitle,+ captureTitleSource: record.captureTitleSource, rawURL: record.rawURL,+ canonicalURL: record.canonicalURL, hostname: record.hostname,+ entryIdentityKey: record.entryIdentityKey,+ conservativeIdentityKey: record.conservativeIdentityKey,+ identityBasis: record.identityBasis, urlWorkIdentity: record.urlWorkIdentity,+ chapterSequence: record.chapterSequence, chapterTitle: record.chapterTitle,+ note: record.note, rating: record.rating, firstCapturedAt: record.firstCapturedAt,+ lastSharedAt: record.lastSharedAt, modifiedAt: record.modifiedAt,+ workID: record.workID, intentionallyUnattached: record.intentionallyUnattached,+ citations: EntryCitations(),+ characterExtractionFingerprint: record.characterExtractionFingerprint)+ entry.citationsData = Data("not json".utf8)+ try context.save()+ LibraryRepository.apply(defaulted, to: entry)+ #expect(+ context.hasChanges,+ "undecodable bytes must be rewritten even where the archive carries the default")+ #expect(try entry.citations == EntryCitations())+ try context.save()++ // No bytes at all — a pre-V9 row the drop stage reached before anything+ // converted it — against that same defaulted archive. `citations` reads+ // a nil blob as the default, so a guard over the decoded value alone+ // sees nothing to write; the archive is what the validator and the+ // diagnosis promise repairs the row, so this arm *must* leave bytes+ // behind. Once it has, a second pass is a no-op like any other.+ entry.citationsData = nil+ try context.save()+ #expect(entry.citationsAreAbsent)+ LibraryRepository.apply(defaulted, to: entry)+ #expect(+ context.hasChanges,+ "a nil blob must be converted even where the archive carries the default")+ #expect(!entry.citationsAreAbsent)+ #expect(try entry.citations == EntryCitations())+ try context.save()+ LibraryRepository.apply(defaulted, to: entry)+ #expect(!context.hasChanges, "a converted blob re-imported against the same archive writes nothing")++ // Decodable bytes that differ from the archive: the plain arm of the+ // comparison. Every arm above would still pass on a guard that only+ // ever wrote over broken or absent bytes.+ #expect(try entry.citations != record.citations)+ LibraryRepository.apply(record, to: entry)+ #expect(context.hasChanges, "citations that decode and differ from the archive must be written")+ #expect(try entry.citations == record.citations)+ }++ /// The record twin of `reapplyingTheSameCitationsWritesNothing`, for the+ /// same reason: `BackupImportRecords.apply(_:to:)` guards `facts` by+ /// comparing canonical bytes rather than through the tolerant `facts`+ /// accessor (`RecordFactCodec.decode` reads undecodable bytes as `[]`, Req+ /// 6.7), so undecodable bytes are always rewritten and equal bytes never+ /// are — a guard written over the accessor instead would see "no facts"+ /// 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: AsterismSchemaV18.self)+ let container = try ModelContainer(+ for: schema,+ configurations: [+ ModelConfiguration(+ schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ ])+ let context = ModelContext(container)+ context.autosaveEnabled = false+ let record = BackupV17Fixtures.character()+ #expect(!record.facts.isEmpty, "the arm needs a non-empty value to compare")+ let character = ArchiveRecordBuilders.makeCharacter(record)+ context.insert(character)+ try context.save()+ #expect(character.facts.map(\.quote) == record.facts.map(\.quote))++ LibraryRepository.apply(record, to: character)+ #expect(!context.hasChanges, "a second import of the same facts must write nothing")++ // Bytes that are present and will not decode: `facts` reads them as+ // `[]`, matching neither the archive's facts nor an empty archive by+ // accident, so the row must still be rewritten.+ character.factsData = Data("not json".utf8)+ try context.save()+ LibraryRepository.apply(record, to: character)+ #expect(context.hasChanges, "a restore must heal a row whose facts will not decode")+ #expect(character.facts.map(\.quote) == record.facts.map(\.quote))+ try context.save()+ LibraryRepository.apply(record, to: character)+ #expect(!context.hasChanges, "a healed row re-imported against the same archive writes nothing")+ }+}++// MARK: - Test Doubles++private final class MockV15SnapshotProvider: BackupV17SnapshotProviding, @unchecked Sendable {+ let payload: BackupV17Payload+ init(payload: BackupV17Payload) { self.payload = payload }+ func backupV17Snapshot() async throws -> BackupV17Payload { payload }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17Fixtures.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17Fixtures.swiftnew file mode 100644index 00000000..98cab8c8--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17Fixtures.swift@@ -0,0 +1,1136 @@+import CoreGraphics+import CryptoKit+import Foundation++@testable import AsterismCore++/// Shared builders for 15/16 payloads — the only archive shape the app reads or+/// writes. 15/16 drops the junk-suffix rule from the Site record (T-2336), over+/// a V16 store; 12/13 added a place table and a place-suppression table+/// (T-2276).+///+/// It absorbed the 4/4, 5/6, 6/7, 7/8, 8/9, 9/10, 10/11 and 11/12 fixture enums+/// as each generation's read and write paths were deleted. 7/8 changed the+/// records themselves: a Work names no site, a membership record names the Work,+/// the citations travel as one blob, and the coverage table is gone — so a+/// payload here is built site-first, membership-second, and every Entry's Work+/// holds a membership on that Entry's hostname. 8/9 changed what a citation *is*+/// (T-2281): the rule's UUID and nothing else. 9/10 added a Work's work status,+/// reading status and verdict (T-2306). 10/11 added a series table, a link table+/// 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 BackupV17Fixtures {+ static let created = Date(timeIntervalSince1970: 1_000_000)++ // MARK: - The cover (`work-thumbnails` Req 8.1)++ /// The committed golden JPEG: 600×900, portrait, no Exif — the same file+ /// `ThumbnailCodecTests` and `ThumbnailIdentityTests` pin the digest of+ /// (Q54). Every archive suite that needs a *valid* cover uses it, so "valid"+ /// means here exactly what it means in the codec's own suite.+ static let coverBytes: Data = {+ let url = URL(fileURLWithPath: #filePath)+ .deletingLastPathComponent()+ .appending(path: "Fixtures/thumbnail-golden-600x900.jpg")+ // Force-unwrapped deliberately: a missing fixture is a broken checkout,+ // and every assertion over these bytes would otherwise pass over none.+ return try! Data(contentsOf: url)+ }()++ /// What import will re-derive from `coverBytes` — never in the file itself+ /// (Q5).+ static var coverDigest: String { Hexadecimal.sha256(coverBytes) }++ /// A cover from a crop the reader zoomed out on (Q89): **600×700**, inside+ /// the portrait box and filling it on the width, which Decision 3 stores+ /// short rather than padding out to 600×900. Built through the encoder+ /// rather than committed, because what the archive suites pin with it is+ /// that the export's own validation admits what the encoder writes.+ static let gappedCoverBytes: Data = {+ guard let space = CGColorSpace(name: CGColorSpace.sRGB),+ let context = CGContext(+ data: nil, width: 600, height: 700, bitsPerComponent: 8,+ bytesPerRow: 0, space: space,+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)+ else { preconditionFailure("a test bitmap must be constructible") }+ context.setFillColor(CGColor(colorSpace: space, components: [0.8, 0.4, 0.2, 1]) ?? .white)+ context.fill(CGRect(x: 0, y: 0, width: 600, height: 700))+ guard let image = context.makeImage() else {+ preconditionFailure("a filled bitmap must make an image")+ }+ // The frame is the full 600×900 box; the source covers 700 of it.+ return ThumbnailCodec.encode(+ image, crop: CGRect(x: 0, y: -100, width: 600, height: 900), shape: .portrait).bytes+ }()++ static var gappedCoverDigest: String { Hexadecimal.sha256(gappedCoverBytes) }++ /// Bytes that decode as `Data` and not as a JPEG: Req 8.4's dropped record,+ /// which is imported *without* a cover and named in the report rather than+ /// refusing the whole archive (Q14, Q51).+ static let undecodableCoverBytes = Data("this is not a picture".utf8)++ /// `payload()` with its one Work carrying the cover the arguments describe.+ ///+ /// The halves are taken separately so a suite can build the states no+ /// exporter of ours writes — bytes that are not a JPEG, a shape spelling+ /// this build has no case for, or half a pair.+ static func coveredPayload(+ shapeRaw: String? = ThumbnailShape.portrait.rawValue,+ bytes: Data? = coverBytes,+ modifiedAt: Date = created+ ) -> BackupV17Payload {+ let base = payload()+ return BackupV17Payload(+ entries: base.entries,+ works: base.works.map { record in+ BackupV17Work(+ id: record.id, displayTitle: record.displayTitle,+ lastParsedTitle: record.lastParsedTitle,+ genericNotes: record.genericNotes, genreTags: record.genreTags,+ titleProvenance: record.titleProvenance,+ workStatus: record.workStatus, readingStatus: record.readingStatus,+ verdict: record.verdict,+ releaseDays: [],+ workTypeID: record.workTypeID, typeName: record.typeName,+ createdAt: record.createdAt, modifiedAt: modifiedAt,+ genericNotesExtractionFingerprint:+ record.genericNotesExtractionFingerprint,+ seriesID: record.seriesID, seriesPosition: record.seriesPosition,+ thumbnailShape: shapeRaw, thumbnail: bytes)+ },+ 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)+ }++ static let novelTypeID = UUID(uuidString: "00000000-0000-0000-0000-0000000000a1")!+ static let webtoonTypeID = UUID(uuidString: "00000000-0000-0000-0000-0000000000a2")!++ /// The Work identity `composedPayload` describes, named once so an import+ /// suite can read the rows it landed on without restating the fixture.+ static let composedWorkID = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee")!+ static let workID = composedWorkID+ /// That Work's one membership.+ static let composedMembershipID = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee1")!+ /// The composed fixture's one Entry.+ static let entryID = UUID(uuidString: "22222222-2222-2222-2222-222222222222")!++ static let note = "Grover promised to guide them home."+ static let genericNotes = "The guide is not what he seems."+ static let noteFingerprint = CharacterCoverageFingerprint.of(note)+ static let genericNotesFingerprint = CharacterCoverageFingerprint.of(genericNotes)++ static let groverID = UUID(uuidString: "C4A2ACE0-0000-4000-8000-000000000001")!+ static let orphanID = UUID(uuidString: "C4A2ACE0-0000-4000-8000-000000000002")!+ static let strangerID = UUID(uuidString: "C4A2ACE0-0000-4000-8000-000000000003")!+ static let suppressionID = UUID(uuidString: "5099E5ED-0000-4000-8000-000000000001")!+ static let factSuppressionID = UUID(uuidString: "5099E5ED-0000-4000-8000-000000000002")!++ /// The place the 15/16 fixtures carry, and the one whose `workID` resolves to+ /// nothing — the tolerated orphan of Req 5.5, which a place expresses with a+ /// dangling id rather than with `nil` (Q60, Q67).+ static let keepID = UUID(uuidString: "91ACE000-0000-4000-8000-000000000001")!+ static let orphanPlaceID = UUID(uuidString: "91ACE000-0000-4000-8000-000000000002")!+ static let placeSuppressionID = UUID(uuidString: "5099E5ED-0000-4000-8000-000000000011")!+ static let placeFactSuppressionID = UUID(uuidString: "5099E5ED-0000-4000-8000-000000000012")!++ // MARK: - Work types++ static func workTypeRecord(+ id: UUID,+ name: String,+ state: WorkTypeState = .active,+ canonicalID: UUID? = nil,+ createdAt: Date = created,+ modifiedAt: Date = created+ ) -> BackupV17WorkType {+ BackupV17WorkType(+ id: id, name: name, stateRaw: state.rawValue, canonicalID: canonicalID,+ createdAt: createdAt, modifiedAt: modifiedAt)+ }++ // MARK: - Memberships++ /// A membership in state `none` — what a Work with no rule-derived identity+ /// holds, which is every fixture Work here bar the golden one.+ static func membership(+ id: UUID,+ workID: UUID?,+ hostname: String,+ createdAt: Date = created,+ urlIdentity: String? = nil,+ urlIdentityState: WorkURLIdentityState = .none,+ urlIdentityRuleID: UUID? = nil,+ workURLString: String? = nil+ ) -> BackupV17Membership {+ BackupV17Membership(+ id: id, workID: workID, hostname: hostname, createdAt: createdAt,+ urlIdentity: urlIdentity, urlIdentityState: urlIdentityState,+ urlIdentityRuleID: urlIdentityRuleID, workURLString: workURLString)+ }++ // MARK: - Minimal taught (conservative Entry)++ static let minimalHost = "example.com"+ static let minimalWorkID = UUID(uuidString: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")!+ static let minimalMembershipID = UUID(uuidString: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa1")!+ static let minimalEntryID = UUID(uuidString: "11111111-1111-1111-1111-111111111111")!++ /// A taught Site with one segment title rule and one conservative-basis+ /// Entry. `activePattern: false` breaks the closed tuple; `brokenAlias: true`+ /// breaks the conservative-key alias invariant.+ static func minimalTaughtPayload(+ activePattern: Bool = true,+ brokenAlias: Bool = false,+ workTypeID: UUID? = novelTypeID,+ typeName: String? = "novel",+ workTypes: [BackupV17WorkType] = [workTypeRecord(id: novelTypeID, name: "novel")]+ ) -> BackupV17Payload {+ let host = minimalHost+ let patternID = UUID(uuidString: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")!+ let rawURL = "https://example.com/read/7"++ let pattern = BackupV17TitlePattern(+ id: patternID, siteHostname: host, version: 1, isActive: activePattern,+ createdAt: created,+ definition: StoredPatternDefinition(+ definition: .segment(+ work: try! SegmentRangeSpec(origin: .start, offset: 0, length: 1),+ ignored: [])))++ let site = BackupV17Site(+ hostname: host, displayName: "Example", mode: .taught)++ let work = BackupV17Work(+ id: minimalWorkID, displayTitle: "Constellation", lastParsedTitle: "Constellation",+ genericNotes: "", genreTags: [], titleProvenance: .parsed,+ workStatus: .ongoing, readingStatus: .reading, verdict: "",+ releaseDays: [],+ workTypeID: workTypeID, typeName: typeName,+ createdAt: created, modifiedAt: created)++ let entry = BackupV17Entry(+ id: minimalEntryID, captureTitle: "Chapter 7", captureTitleSource: .host,+ rawURL: rawURL, canonicalURL: nil, hostname: host,+ entryIdentityKey: rawURL,+ conservativeIdentityKey: brokenAlias ? "not-the-url" : rawURL,+ identityBasis: .conservative,+ urlWorkIdentity: nil, chapterSequence: nil, chapterTitle: nil,+ note: "", rating: nil, firstCapturedAt: created, lastSharedAt: created,+ modifiedAt: created, workID: minimalWorkID, intentionallyUnattached: false,+ citations: EntryCitations(workAssignment: .manual))++ return BackupV17Payload(+ entries: [entry], works: [work], sites: [site],+ titlePatterns: [pattern], urlRules: [], workTypes: workTypes,+ memberships: [+ membership(id: minimalMembershipID, workID: minimalWorkID, hostname: host)+ ])+ }++ // MARK: - Composed (whole-title trims + sequence rule + v3 key)++ /// A taught Site whose title rule is a trimmed whole-title rule and whose URL+ /// rule is sequence-only, with one v3-basis (sequence+name) Entry. The URL+ /// extraction, whole-title naming, and v3 key are mutually consistent so the+ /// payload passes the full store-level `LibraryValidator`, not only the+ /// codec-level reference validator. `dropNameContributor: true` removes the+ /// required name contributor.+ static func composedPayload(+ dropNameContributor: Bool = false,+ releaseDays: [ReleaseDay] = [],+ readingStatus: ReadingStatus = .abandoned,+ workTypeID: UUID? = novelTypeID,+ typeName: String? = "novel",+ workTypes: [BackupV17WorkType] = [workTypeRecord(id: novelTypeID, name: "novel")]+ ) -> BackupV17Payload {+ let host = "example.com"+ let patternID = UUID(uuidString: "cccccccc-cccc-cccc-cccc-cccccccccccc")!+ let ruleID = UUID(uuidString: "dddddddd-dddd-dddd-dddd-dddddddddddd")!+ let rawURL = "https://example.com/read?chapter=94&x=1"+ let workName = "Actual Title"++ // The whole-title rule names the Work by trimming the boilerplate prefix.+ let pattern = BackupV17TitlePattern(+ 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 = BackupV17URLRule(+ id: ruleID, version: 1, isCurrent: true, createdAt: created,+ origin: .readerTaught,+ definition: .sequence(locator: .query(name: ExactScalarString("chapter"))),+ siteHostname: host)++ let site = BackupV17Site(+ 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 = BackupV17Work(+ id: composedWorkID, displayTitle: workName, lastParsedTitle: workName,+ genericNotes: "", genreTags: [], titleProvenance: .parsed,+ workStatus: .finished, readingStatus: readingStatus,+ verdict: "Dropped it at the timeskip.",+ releaseDays: releaseDays,+ workTypeID: workTypeID, typeName: typeName,+ createdAt: created, modifiedAt: created)++ // The v3 key embeds host + resolved Work name + sequence (Req 4.2).+ let v3Key = EntryIdentityKeyV3Codec.encode(+ try! URLSequenceNameIdentity(+ hostname: ExactScalarString(host), workName: ExactScalarString(workName),+ chapterSequence: ExactScalarString("94")))++ let entry = BackupV17Entry(+ id: entryID, captureTitle: "TtH • Story • Actual Title", captureTitleSource: .host,+ rawURL: rawURL, canonicalURL: nil, hostname: host,+ entryIdentityKey: v3Key, conservativeIdentityKey: rawURL,+ identityBasis: .urlRule,+ urlWorkIdentity: nil, chapterSequence: "94", chapterTitle: nil,+ note: "", rating: nil, firstCapturedAt: created, lastSharedAt: created,+ modifiedAt: created, workID: composedWorkID, intentionallyUnattached: false,+ citations: EntryCitations(+ identity: .composed(+ url: CitedRule(id: ruleID),+ nameTitle: dropNameContributor ? nil : CitedRule(id: patternID)),+ chapterSequence: CitedRule(id: ruleID),+ workAssignment: .pattern(CitedRule(id: patternID))))++ return BackupV17Payload(+ entries: [entry], works: [work], sites: [site],+ titlePatterns: [pattern], urlRules: [rule], workTypes: workTypes,+ memberships: [+ membership(id: composedMembershipID, workID: composedWorkID, hostname: host)+ ])+ }++ // MARK: - Series and links (`series-and-related-works` Req 13)++ static let seriesID = UUID(uuidString: "5E81E5A0-0000-4000-8000-000000000001")!+ static let secondWorkID = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee02")!+ static let secondMembershipID = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee12")!+ static let linkID = UUID(uuidString: "11115E51-0000-4000-8000-000000000001")!++ static func seriesRecord(+ id: UUID = seriesID,+ name: String = "Ashfall Cycle",+ notes: String = "Read 2.5 after 2.",+ createdAt: Date = created,+ modifiedAt: Date = created+ ) -> BackupV17Series {+ BackupV17Series(+ id: id, name: name, notes: notes, createdAt: createdAt, modifiedAt: modifiedAt)+ }++ /// One link, with its ids in whatever order the caller gave them — the+ /// payload sorts at the door, which is what several suites are about.+ static func linkRecord(+ id: UUID = linkID,+ a: UUID = composedWorkID,+ b: UUID = secondWorkID,+ type: String = "adaptation",+ createdAt: Date = created,+ modifiedAt: Date = created+ ) -> BackupV17Link {+ BackupV17Link(+ id: id, lowerWorkID: a, higherWorkID: b, linkType: type,+ createdAt: createdAt, modifiedAt: modifiedAt)+ }++ /// `composedPayload` plus a second Work on the same site, a series holding+ /// both, and a link between them: the smallest payload that exercises every+ /// V12 shape at once.+ static func seriesPayload(+ series: [BackupV17Series] = [seriesRecord()],+ links: [BackupV17Link] = [linkRecord()],+ firstMembership: (series: UUID, position: Double)? = (seriesID, 1),+ secondMembership: (series: UUID, position: Double)? = (seriesID, 2.5)+ ) -> BackupV17Payload {+ let base = composedPayload()+ let host = "example.com"+ let second = BackupV17Work(+ 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 BackupV17Payload(+ entries: base.entries,+ works: base.works.map { placed($0, membership: firstMembership) } + [second],+ sites: base.sites,+ titlePatterns: base.titlePatterns,+ urlRules: base.urlRules,+ workTypes: base.workTypes,+ memberships: base.memberships+ + [membership(id: secondMembershipID, workID: secondWorkID, hostname: host)],+ distinctPairs: base.distinctPairs,+ characters: base.characters,+ suppressions: base.suppressions,+ series: series,+ links: links)+ }++ /// The composed Work with a membership pair. `BackupV17Work`'s fields are+ /// `let`, so a copy is a full restatement.+ static func placed(+ _ record: BackupV17Work, membership: (series: UUID, position: Double)?+ ) -> BackupV17Work {+ BackupV17Work(+ id: record.id, displayTitle: record.displayTitle,+ lastParsedTitle: record.lastParsedTitle, genericNotes: record.genericNotes,+ genreTags: record.genreTags, titleProvenance: record.titleProvenance,+ workStatus: record.workStatus, readingStatus: record.readingStatus,+ verdict: record.verdict, releaseDays: [], workTypeID: record.workTypeID, typeName: record.typeName,+ createdAt: record.createdAt, modifiedAt: record.modifiedAt,+ genericNotesExtractionFingerprint: record.genericNotesExtractionFingerprint,+ seriesID: membership?.series, seriesPosition: membership?.position)+ }++ /// A Work carrying exactly the two raw column values given — including the+ /// 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: [BackupV17Series] = [seriesRecord()]+ ) -> BackupV17Payload {+ let base = composedPayload()+ return BackupV17Payload(+ entries: base.entries,+ works: base.works.map {+ BackupV17Work(+ id: $0.id, displayTitle: $0.displayTitle,+ lastParsedTitle: $0.lastParsedTitle, genericNotes: $0.genericNotes,+ genreTags: $0.genreTags, titleProvenance: $0.titleProvenance,+ workStatus: $0.workStatus, readingStatus: $0.readingStatus,+ verdict: $0.verdict, releaseDays: [], workTypeID: $0.workTypeID, typeName: $0.typeName,+ createdAt: $0.createdAt, modifiedAt: $0.modifiedAt,+ genericNotesExtractionFingerprint: $0.genericNotesExtractionFingerprint,+ seriesID: seriesID, seriesPosition: position)+ },+ sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules,+ workTypes: base.workTypes, memberships: base.memberships,+ series: series)+ }++ // MARK: - Creators, roles and credits (`work-creators` Req 9)++ /// The pristine sentinel every seeded record wears, named here so a fixture+ /// reads as "nobody has touched this" rather than as a magic date.+ static let pristine = CreatorDirectory.epoch++ static let moriID = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000001")!+ static let studioID = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000002")!+ /// Merged into `moriID`: the loser of a name collision, hidden everywhere,+ /// and the id a credit may still name.+ static let aliasID = UUID(uuidString: "c8ea1080-0000-4000-8000-000000000003")!+ static let absentCreatorID = UUID(uuidString: "c8ea1080-0000-4000-8000-00000000000f")!++ /// The three the app seeds into every library it opens.+ static var authorRoleID: UUID { CreatorRoleSeeding.seeds[0].id }+ static var artistRoleID: UUID { CreatorRoleSeeding.seeds[1].id }+ static var translatorRoleID: UUID { CreatorRoleSeeding.seeds[2].id }+ /// A role the reader added, and one they removed — both reader-touched, so+ /// both out-date a seed in every election.+ static let lettererRoleID = UUID(uuidString: "e0000004-0000-4000-8000-000000000004")!+ static let editorRoleID = UUID(uuidString: "e0000005-0000-4000-8000-000000000005")!+ static let absentRoleID = UUID(uuidString: "e000000f-0000-4000-8000-00000000000f")!++ static let moriCreditID = UUID(uuidString: "c8ed1700-0000-4000-8000-000000000001")!+ static let studioCreditID = UUID(uuidString: "c8ed1700-0000-4000-8000-000000000002")!+ static let orphanCreditID = UUID(uuidString: "c8ed1700-0000-4000-8000-000000000003")!++ static func creatorRecord(+ id: UUID,+ name: String,+ notes: String = "",+ state: CreatorState = .active,+ canonicalID: UUID? = nil,+ nameModifiedAt: Date = created,+ notesModifiedAt: Date = created,+ stateModifiedAt: Date = created,+ createdAt: Date = created+ ) -> BackupV17Creator {+ BackupV17Creator(+ id: id, name: name, nameModifiedAt: nameModifiedAt, notes: notes,+ notesModifiedAt: notesModifiedAt, stateRaw: state.rawValue,+ stateModifiedAt: stateModifiedAt, canonicalID: canonicalID,+ createdAt: createdAt,+ modifiedAt: max(nameModifiedAt, max(notesModifiedAt, stateModifiedAt)))+ }++ static func creatorRoleRecord(+ id: UUID,+ name: String,+ position: Int,+ state: CreatorRoleState = .active,+ canonicalID: UUID? = nil,+ nameModifiedAt: Date = created,+ positionModifiedAt: Date = created,+ stateModifiedAt: Date = created,+ createdAt: Date = created+ ) -> BackupV17CreatorRole {+ BackupV17CreatorRole(+ id: id, name: name, nameModifiedAt: nameModifiedAt, position: position,+ positionModifiedAt: positionModifiedAt, stateRaw: state.rawValue,+ stateModifiedAt: stateModifiedAt, canonicalID: canonicalID,+ createdAt: createdAt,+ modifiedAt: max(nameModifiedAt, max(positionModifiedAt, stateModifiedAt)))+ }++ /// 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) -> BackupV17CreatorRole {+ creatorRoleRecord(+ id: seed.id, name: seed.name, position: seed.position,+ nameModifiedAt: pristine, positionModifiedAt: pristine,+ stateModifiedAt: pristine, createdAt: pristine)+ }++ /// The three seeds, in list order.+ static var seededRoleRecords: [BackupV17CreatorRole] {+ CreatorRoleSeeding.seeds.map(seededRoleRecord)+ }++ static func creditRecord(+ id: UUID,+ workID: UUID,+ creatorID: UUID,+ roleIDs: [UUID] = [],+ createdAt: Date = created,+ modifiedAt: Date = created+ ) -> BackupV17Credit {+ BackupV17Credit(+ id: id, workID: workID, creatorID: creatorID,+ roleIDs: roleIDs.map(\.uuidString).sorted(),+ createdAt: createdAt, modifiedAt: modifiedAt)+ }++ /// 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: [BackupV17Creator] {+ [+ creatorRecord(id: moriID, name: "Mori Ayane", notes: "Also draws."),+ creatorRecord(id: studioID, name: "Studio Lantern"),+ creatorRecord(+ id: aliasID, name: "mori ayane", state: .merged, canonicalID: moriID),+ ]+ }++ static var creatorRoleRecords: [BackupV17CreatorRole] {+ seededRoleRecords + [+ creatorRoleRecord(id: lettererRoleID, name: "letterer", position: 3),+ creatorRoleRecord(+ id: editorRoleID, name: "editor", position: 4, state: .removed),+ ]+ }++ /// Four credits over the two works of `seriesPayload`: one holding two roles+ /// 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: [BackupV17Credit] {+ [+ creditRecord(+ id: moriCreditID, workID: composedWorkID, creatorID: moriID,+ roleIDs: [authorRoleID, editorRoleID]),+ creditRecord(+ id: studioCreditID, workID: secondWorkID, creatorID: studioID,+ roleIDs: [artistRoleID, absentRoleID]),+ creditRecord(+ id: orphanCreditID,+ workID: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee99")!,+ creatorID: moriID, roleIDs: [authorRoleID]),+ ]+ }++ /// `seriesPayload` plus the whole V12 surface: the creator table, the role+ /// list and the credits over both works.+ static func creditsPayload(+ creators: [BackupV17Creator]? = nil,+ creatorRoles: [BackupV17CreatorRole]? = nil,+ credits: [BackupV17Credit]? = nil+ ) -> BackupV17Payload {+ let base = seriesPayload()+ return BackupV17Payload(+ entries: base.entries, works: base.works, sites: base.sites,+ titlePatterns: base.titlePatterns, urlRules: base.urlRules,+ workTypes: base.workTypes, memberships: base.memberships,+ distinctPairs: base.distinctPairs, characters: base.characters,+ suppressions: base.suppressions, places: base.places,+ placeSuppressions: base.placeSuppressions,+ series: base.series, links: base.links,+ creators: creators ?? creatorRecords,+ creatorRoles: creatorRoles ?? creatorRoleRecords,+ credits: credits ?? creditRecords)+ }++ // MARK: - Unanchored locators (Req 1.3)++ /// A taught Site whose current rule brackets a path component with the given+ /// anchoring. With `leftAnchored: false` the locator leaves **both** sides+ /// 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) -> BackupV17Payload {+ let host = "unanchored.example"+ let patternID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff1")!+ let ruleID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff2")!++ let pattern = BackupV17TitlePattern(+ id: patternID, siteHostname: host, version: 1, isActive: true, createdAt: created,+ definition: StoredPatternDefinition(+ definition: .segment(+ work: try! SegmentRangeSpec(origin: .start, offset: 0, length: 1),+ ignored: [])))++ let left: PathAnchor = leftAnchored ? .literal(ExactScalarString("series")) : .unanchored+ let rule = BackupV17URLRule(+ id: ruleID, version: 1, isCurrent: true, createdAt: created,+ origin: .readerTaught,+ definition: .work(locator: .pathBracketed(left: left, right: .unanchored)),+ siteHostname: host)++ let site = BackupV17Site(+ hostname: host, displayName: "Unanchored", mode: .taught)++ return BackupV17Payload(+ entries: [], works: [], sites: [site],+ titlePatterns: [pattern], urlRules: [rule], workTypes: [])+ }++ // MARK: - Combined rule, both presence states (Reqs 5.3–5.5)++ static let combinedRuleHost = "combined.example"++ /// A taught Site whose current rule is the tthfanfic-shaped combined rule,+ /// with the chapter sequence declared optional or not.+ ///+ /// 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) -> BackupV17Payload {+ let patternID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff3")!+ let ruleID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff4")!++ let pattern = BackupV17TitlePattern(+ id: patternID, siteHostname: combinedRuleHost, version: 1, isActive: true,+ createdAt: created,+ definition: StoredPatternDefinition(definition: .wholeTitle))++ let rule = BackupV17URLRule(+ id: ruleID, version: 1, isCurrent: true, createdAt: created,+ origin: .readerTaught,+ definition: .combined(+ locator: .pathBracketed(left: .start, right: .unanchored),+ template: URLTwoFieldTemplate(+ prefix: ExactScalarString("Story-"),+ separator: ExactScalarString("-"),+ suffix: ExactScalarString(""),+ order: .workThenSequence,+ sequencePresence: presence)),+ siteHostname: combinedRuleHost)++ let site = BackupV17Site(+ hostname: combinedRuleHost, displayName: "Combined", mode: .taught)++ return BackupV17Payload(+ entries: [], works: [], sites: [site],+ titlePatterns: [pattern], urlRules: [rule], workTypes: [])+ }++ /// The payload bytes a build **without** the optional-sequence feature+ /// writes for `combinedRulePayload(presence: .required)`: the same records,+ /// hand-written in the codec's canonical `.sortedKeys` layout, and carrying+ /// no `sequencePresence` key anywhere.+ ///+ /// It was recorded at 4/4 when the feature shipped and is restated at each+ /// generation — the envelope and the surrounding arrays move, the rule+ /// definition does not, which is the whole claim the literal exists to pin.+ static let sequencePresenceOmittedPayloadJSON =+ #"{"characters":[],"creatorRoles":[],"creators":[],"credits":[],"distinctPairs":[],"#+ + #""entries":[],"links":[],"memberships":[],"#+ + #""noEpisodeActions":[],"placeSuppressions":[],"places":[],"#+ + #""series":[],"sites":"#+ + #"[{"displayName":"Combined","hostname":"combined.example","mode":"taught"}],"#+ + #""suppressions":[],"titlePatterns":[{"createdAt":"1970-01-12T13:46:40.000Z","#+ + #""definition":{"definition":{"wholeTitle":{}}},"#+ + #""id":"FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFF3","isActive":true,"#+ + #""siteHostname":"combined.example","version":1}],"urlRules":"#+ + #"[{"createdAt":"1970-01-12T13:46:40.000Z","definition":{"combined":"#+ + #"{"locator":{"pathBracketed":{"left":{"start":{}},"right":{"unanchored":{}}}},"#+ + #""template":{"order":"workThenSequence","prefix":"Story-","separator":"-","#+ + #""suffix":""}}},"id":"FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFF4","isCurrent":true,"#+ + #""origin":"readerTaught","siteHostname":"combined.example","version":1}],"#+ + #""workTypes":[],"works":[]}"#++ /// A payload literal wrapped in the 15/16 envelope, with the checksum taken+ /// 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: `BackupV17Codec.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).+ ///+ /// The envelope's two numbers are the **document's own constants** rather+ /// than literals: left behind at the next generation move they would refuse+ /// every fixture below by *version*, which is a refusal none of them exists+ /// to pin, and the decode failures they do pin would stop being reached+ /// without a single test going red.+ static func literalDocument(+ payload: String, entryCount: Int = 0, workCount: Int = 0,+ appBuild: String = "literal"+ ) -> Data {+ let checksum = SHA256.hash(data: Data(payload.utf8))+ .map { String(format: "%02x", $0) }.joined()+ let format = BackupV17Document.formatVersion+ let schema = BackupV17Document.schemaVersion+ // Built in steps rather than as one concatenation: with the two numbers+ // interpolated the single expression no longer type-checks in+ // reasonable time.+ var envelope = #"{"appBuild":"\#(appBuild)","backupFormatVersion":\#(format),"#+ envelope += #""capabilityGate":"multi-site","checksum":"\#(checksum)","#+ envelope += #""databaseSchemaVersion":\#(schema),"entryCount":\#(entryCount),"#+ envelope += #""exportedAt":"1970-01-12T13:46:40.000Z","payload":\#(payload),"#+ envelope += #""workCount":\#(workCount)}"#+ return Data(envelope.utf8)+ }++ static func sequencePresenceOmittedDocument(appBuild: String = "pre-feature") -> Data {+ literalDocument(payload: sequencePresenceOmittedPayloadJSON, appBuild: appBuild)+ }++ // MARK: - A citation carrying a version (Req 5.4)++ /// `composedPayload()` as the current encoder writes it, with `"version":3`+ /// hand-added to the Entry's chapter-sequence citation — the shape a build+ /// before T-2281 wrote, and the one a 15/16 archive may not carry.+ ///+ /// Captured from `BackupCanonicalJSON.encoder()` and pasted, for the reason+ /// Q17 gives: an encoder that no longer writes the key cannot produce+ /// evidence about a file that does.+ static let citationVersionPayloadJSON =+ #"{"characters":[],"creatorRoles":[],"creators":[],"credits":[],"distinctPairs":[],"#+ + #""entries":[{"#+ + #""captureTitle":"TtH • Story • Actual Title","captureTitleSource":"host","#+ + #""chapterSequence":"94","citations":{"chapterSequence":"#+ + #"{"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD","version":3},"#+ + #""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://example.com/read?chapter=94&x=1","entryIdentityKey":"#+ + #""v3|h11:example.com|n12:Actual Title|s2:94","#+ + #""firstCapturedAt":"1970-01-12T13:46:40.000Z","#+ + #""hostname":"example.com","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":"","rawURL":"https://example.com/read?chapter=94&x=1","#+ + #""workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"}],"links":[],"memberships":"#+ + #"[{"createdAt":"1970-01-12T13:46:40.000Z","hostname":"example.com","#+ + #""id":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE1","urlIdentityState":"none","#+ + #""workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"}],"#+ + #""noEpisodeActions":[],"placeSuppressions":[],"places":[],"series":[],"sites":"#+ + #"[{"displayName":"Example","hostname":"example.com","mode":"taught"}],"#+ + #""suppressions":[],"#+ + #""titlePatterns":[{"createdAt":"1970-01-12T13:46:40.000Z","definition":"#+ + #"{"definition":{"wholeTitle":{}},"trimPrefix":"TtH • Story • "},"#+ + #""id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC","isActive":true,"#+ + #""siteHostname":"example.com","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":"example.com","version":1}],"#+ + #""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":[{"#+ + #""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","#+ + #""workTypeID":"00000000-0000-0000-0000-0000000000A1"}]}"#++ /// The same literal with the stray key removed — the bytes this build writes+ /// for the same records, so the refusal above is pinned to the `version` key+ /// and not to some other drift in the paste.+ static var citationVersionFreePayloadJSON: String {+ citationVersionPayloadJSON.replacingOccurrences(+ of: #"{"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD","version":3}"#,+ with: #"{"id":"DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD"}"#)+ }++ // MARK: - A Work missing the three status fields (Req 8.1)++ /// The bytes this build writes, with `workStatus`, `readingStatus` and+ /// `verdict` struck from the one Work record — the shape a 15/16 file may not+ /// carry, because all three are required and there is no default (Q34).+ ///+ /// It starts from the version-free literal because that is already the+ /// current encoder's output for a payload holding a Work: everything but the+ /// three keys is a file this build accepts, so the refusal is about them.+ static var statusFieldsOmittedPayloadJSON: String {+ citationVersionFreePayloadJSON+ .replacingOccurrences(of: #""readingStatus":"reading","#, with: "")+ .replacingOccurrences(of: #""verdict":"","#, with: "")+ .replacingOccurrences(of: #""workStatus":"ongoing","#, with: "")+ }++ // MARK: - The release days (`update-schedule` Req 8.1, Q22, Q36)++ /// The bytes this build writes, with `releaseDays` struck from the one Work+ /// record — the shape a **pre-feature** build wrote, wearing a 15/16+ /// envelope. The field is required and has no default (Q22), so this is a+ /// malformed 15/16 file rather than a restorable one: a default would make+ /// "the reader set no days" indistinguishable from "this record predates the+ /// column".+ static var releaseDaysOmittedPayloadJSON: String {+ citationVersionFreePayloadJSON+ .replacingOccurrences(of: #""releaseDays":[],"#, with: "")+ }++ /// The same literal carrying a day spelling this build has no case for. The+ /// list decodes into the typed `[ReleaseDay]`, so an unknown value fails the+ /// decode and the archive is refused as malformed (Q36) — there is no+ /// tolerant reading of a backup.+ static var unknownReleaseDayPayloadJSON: String {+ citationVersionFreePayloadJSON+ .replacingOccurrences(of: #""releaseDays":[],"#, with: #""releaseDays":["funday"],"#)+ }++ /// A Work carrying a real schedule, so the restore path has something other+ /// than the empty set to put back.+ static var populatedReleaseDaysPayloadJSON: String {+ citationVersionFreePayloadJSON+ .replacingOccurrences(+ of: #""releaseDays":[],"#, with: #""releaseDays":["monday","thursday"],"#)+ }++ // MARK: - A payload missing the two place arrays (Req 5.1)++ /// The same literal with the two place arrays struck out — the **shape** a+ /// pre-feature build writes, wearing a 15/16 envelope. Both arrays are+ /// declared without `decodeIfPresent` and without a default (Q51), so this+ /// fails the typed decode rather than restoring a library that asserts the+ /// reader accepted no places.+ static var placeArraysOmittedPayloadJSON: String {+ citationVersionFreePayloadJSON.replacingOccurrences(+ of: #""placeSuppressions":[],"places":[],"#, with: "")+ }++ // 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. `BackupV17Site.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`,+ /// which Req 7.2 keeps to `UnknownSiteModeTests`: what is pinned here is the+ /// typed column, and every unnameable value meets it at the same door. The+ /// retired spelling's own consequences are that suite's, and a 14/15 file —+ /// the only file that could carry it — is refused a step earlier, by pair.+ static var unknownSiteModePayloadJSON: String {+ citationVersionFreePayloadJSON.replacingOccurrences(+ of: #""mode":"taught""#, with: #""mode":"a-mode-this-build-has-no-case-for""#)+ }++ // MARK: - Duplicate and non-greatest rule versions (Req 3.2)++ /// A Site holding two title patterns at version 1 — one retired, one active+ /// — and a current URL rule whose version is *below* the retired rule's.+ ///+ /// 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() -> BackupV17Payload {+ 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) -> BackupV17TitlePattern {+ BackupV17TitlePattern(+ id: id, siteHostname: host, version: 1, isActive: active, createdAt: createdAt,+ definition: StoredPatternDefinition(definition: .wholeTitle))+ }++ func rule(_ id: UUID, version: Int, current: Bool, createdAt: Date) -> BackupV17URLRule {+ BackupV17URLRule(+ id: id, version: version, isCurrent: current, createdAt: createdAt,+ origin: .readerTaught,+ definition: .sequence(+ locator: .pathBracketed(left: .literal(ExactScalarString("c")), right: .end)),+ siteHostname: host)+ }++ return BackupV17Payload(+ entries: [], works: [],+ sites: [+ BackupV17Site(+ hostname: host, displayName: "Versions", mode: .taught)+ ],+ titlePatterns: [+ pattern(retiredPatternID, active: false, createdAt: created),+ pattern(activePatternID, active: true, createdAt: created.addingTimeInterval(60)),+ ],+ urlRules: [+ rule(retiredRuleID, version: 9, current: false, createdAt: created),+ rule(+ currentRuleID, version: 2, current: true,+ createdAt: created.addingTimeInterval(60)),+ ],+ workTypes: [])+ }++ // MARK: - Two current URL rules (illegal)++ static func twoCurrentRulePayload() -> BackupV17Payload {+ let host = "dup.example"+ let patternID = UUID()+ let ruleA = UUID()+ let ruleB = UUID()++ let pattern = BackupV17TitlePattern(+ 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) -> BackupV17URLRule {+ BackupV17URLRule(+ id: id, version: version, isCurrent: true, createdAt: created,+ origin: .readerTaught,+ definition: .sequence(+ locator: .pathBracketed(left: .literal(ExactScalarString("c")), right: .end)),+ siteHostname: host)+ }++ let site = BackupV17Site(+ hostname: host, displayName: "Dup", mode: .taught)++ return BackupV17Payload(+ entries: [], works: [], sites: [site],+ titlePatterns: [pattern], urlRules: [rule(ruleA, 1), rule(ruleB, 2)],+ workTypes: [])+ }++ // MARK: - Character records++ static func fact(+ statement: String = "Promised to guide them home.",+ quote: String = "promised to guide them home",+ nameKey: String = "grover",+ source: SourceRef = .entry(entryID)+ ) -> RecordFact {+ RecordFact(statement: statement, quote: quote, nameKey: nameKey, source: source)+ }++ static func character(+ id: UUID = groverID,+ workID: UUID? = workID,+ name: String = "Grover",+ nameKey: String = "grover",+ aliases: [String] = ["Klar"],+ note: String = "The guide.",+ facts: [RecordFact] = [fact()],+ createdAt: Date = created,+ modifiedAt: Date = created+ ) -> BackupV17Character {+ BackupV17Character(+ id: id, workID: workID, name: name, nameKey: nameKey, aliases: aliases,+ note: note, facts: facts, createdAt: createdAt, modifiedAt: modifiedAt)+ }++ static func suppression(+ id: UUID = suppressionID,+ workID: UUID? = workID,+ kind: CharacterSuppressionKind = .candidate,+ nameKey: String = "the crowned one",+ source: SourceRef? = nil,+ evidence: String? = nil,+ status: CharacterSuppressionStatus = .active,+ actionAt: Date = created+ ) -> BackupV17Suppression {+ BackupV17Suppression(+ id: id, workID: workID, kindRaw: kind.rawValue, nameKey: nameKey,+ sourceKindRaw: source?.kindRaw, sourceEntryID: source?.entryID,+ evidence: evidence, statusRaw: status.rawValue, actionAt: actionAt)+ }++ // MARK: - Place records (`place-extraction` Req 5.1)++ /// The place twin of `character(…)`. `workID` is **not** optional here: the+ /// table names its owner in a column, so the caller passes the id it names+ /// whether or not anything answers for it (Q60).+ static func place(+ id: UUID = keepID,+ workID: UUID = workID,+ name: String = "The High Keep",+ nameKey: String = "high keep",+ aliases: [String] = ["The Keep"],+ note: String = "The fortress above the pass.",+ facts: [RecordFact] = [placeFact()],+ createdAt: Date = created,+ modifiedAt: Date = created+ ) -> BackupV17Place {+ BackupV17Place(+ id: id, workID: workID, name: name, nameKey: nameKey, aliases: aliases,+ note: note, facts: facts, createdAt: createdAt, modifiedAt: modifiedAt)+ }++ static func placeFact(+ statement: String = "Sits above the pass.",+ quote: String = "above the pass",+ nameKey: String = "high keep",+ source: SourceRef = .entry(entryID)+ ) -> RecordFact {+ RecordFact(statement: statement, quote: quote, nameKey: nameKey, source: source)+ }++ static func placeSuppression(+ id: UUID = placeSuppressionID,+ workID: UUID = workID,+ kind: CharacterSuppressionKind = .candidate,+ nameKey: String = "low road",+ source: SourceRef? = nil,+ evidence: String? = nil,+ status: CharacterSuppressionStatus = .active,+ actionAt: Date = created+ ) -> BackupV17PlaceSuppression {+ BackupV17PlaceSuppression(+ id: id, workID: workID, kindRaw: kind.rawValue, nameKey: nameKey,+ sourceKindRaw: source?.kindRaw, sourceEntryID: source?.entryID,+ evidence: evidence, statusRaw: status.rawValue, actionAt: actionAt)+ }++ // MARK: - Payloads++ /// The composed payload with a noted Entry, generic notes on the Work, and+ /// whatever character records the caller asks for.+ ///+ /// The coverage fingerprints ride on the two records whose text they describe+ /// (Req 9.4) rather than in a table of their own. They are still+ /// self-validating against that *text* (Q81), so the fixture's sources carry+ /// it and the defaults are taken from them — a caller passing something else+ /// is describing a stale pair on purpose.+ static func payload(+ characters: [BackupV17Character] = [character()],+ suppressions: [BackupV17Suppression] = [suppression()],+ places: [BackupV17Place] = [place()],+ placeSuppressions: [BackupV17PlaceSuppression] = [placeSuppression()],+ entryFingerprint: String? = noteFingerprint,+ workFingerprint: String? = genericNotesFingerprint+ ) -> BackupV17Payload {+ let base = composedPayload()+ return BackupV17Payload(+ entries: base.entries.map { noted($0, fingerprint: entryFingerprint) },+ works: base.works.map { annotated($0, fingerprint: workFingerprint) },+ sites: base.sites,+ titlePatterns: base.titlePatterns,+ urlRules: base.urlRules,+ workTypes: base.workTypes,+ memberships: base.memberships,+ distinctPairs: base.distinctPairs,+ characters: characters,+ suppressions: suppressions,+ places: places,+ placeSuppressions: placeSuppressions)+ }++ static func metadata(appBuild: String = "test-12", exportedAt: Date = created)+ -> BackupV17Metadata+ {+ BackupV17Metadata(appBuild: appBuild, exportedAt: exportedAt)+ }++ static func plan(_ payload: BackupV17Payload) -> BackupImportPlan {+ BackupImportPlan(+ metadata: BackupImportMetadata(+ formatVersion: BackupV17Document.formatVersion,+ schemaVersion: BackupV17Document.schemaVersion,+ appBuild: "test-12", exportedAt: created,+ capabilityGate: "multi-site", entryCount: payload.entries.count,+ workCount: payload.works.count),+ payload: payload,+ counts: LibraryRecordCounts(+ entries: payload.entries.count, works: payload.works.count,+ sites: payload.sites.count, titlePatterns: payload.titlePatterns.count,+ urlRulePatterns: payload.urlRules.count, workTypes: payload.workTypes.count))+ }++ // MARK: - A refused envelope++ /// A 14/15 envelope, hand-written because nothing in the app can mint one+ /// any more. Structurally valid JSON with a well-formed payload: what makes+ /// it unimportable is the version pair, which is exactly the distinction the+ /// refusal has to draw (`remove-article-mode` Req 5.3, Q2).+ ///+ /// 14/15 is the generation immediately behind this one, and the one a reader+ /// is most likely to still hold: its Site records carry a junk-suffix rule+ /// 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 = 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()+ return Data(+ (#"{"appBuild":"retired","backupFormatVersion":\#(format),"capabilityGate":"m4","#+ + #""checksum":"\#(checksum)","databaseSchemaVersion":\#(schema),"entryCount":0,"#+ + #""exportedAt":"1970-01-12T13:46:40.000Z","payload":\#(payload),"#+ + #""workCount":0}"#).utf8)+ }++ // MARK: - Copies of the frozen records++ /// The composed Entry with a note and its covered revision. `BackupV17Entry`'s+ /// fields are `let`, so a copy is a full restatement — stated once here+ /// rather than in each suite.+ private static func noted(_ record: BackupV17Entry, fingerprint: String?) -> BackupV17Entry {+ BackupV17Entry(+ id: record.id, captureTitle: record.captureTitle,+ captureTitleSource: record.captureTitleSource, rawURL: record.rawURL,+ canonicalURL: record.canonicalURL, hostname: record.hostname,+ entryIdentityKey: record.entryIdentityKey,+ conservativeIdentityKey: record.conservativeIdentityKey,+ identityBasis: record.identityBasis,+ urlWorkIdentity: record.urlWorkIdentity,+ chapterSequence: record.chapterSequence,+ chapterTitle: record.chapterTitle,+ note: note, rating: record.rating, firstCapturedAt: record.firstCapturedAt,+ lastSharedAt: record.lastSharedAt, modifiedAt: record.modifiedAt,+ workID: record.workID, intentionallyUnattached: record.intentionallyUnattached,+ citations: record.citations,+ characterExtractionFingerprint: fingerprint)+ }++ /// The composed Work with generic notes and its covered revision.+ private static func annotated(_ record: BackupV17Work, fingerprint: String?) -> BackupV17Work {+ BackupV17Work(+ id: record.id, displayTitle: record.displayTitle,+ lastParsedTitle: record.lastParsedTitle, genericNotes: genericNotes,+ genreTags: record.genreTags, titleProvenance: record.titleProvenance,+ workStatus: record.workStatus, readingStatus: record.readingStatus,+ verdict: record.verdict,+ releaseDays: [],+ workTypeID: record.workTypeID, typeName: record.typeName,+ createdAt: record.createdAt, modifiedAt: record.modifiedAt,+ genericNotesExtractionFingerprint: fingerprint)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17ImportMatrixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17ImportMatrixTests.swiftnew file mode 100644index 00000000..eac8a0cd--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17ImportMatrixTests.swift@@ -0,0 +1,221 @@+import Foundation+import Testing++@testable import AsterismCore++/// Task 9 of `update-schedule`: the release days at the archive's two doors.+///+/// `BackupV17ArchiveTests` 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+/// exactly, and a record that omits the key — or carries a day this build cannot+/// 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 16/17 import: release days", .serialized)+struct BackupV17ImportMatrixTests {++ // MARK: - What restores (Req 8.1)++ @Test("An archive carrying an empty set restores a work with no release days")+ func emptySetRestores() async throws {+ let fixture = try await M5Fixture()++ let result = try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(BackupV17Fixtures.composedPayload(releaseDays: [])))+ guard case .committed = result else {+ Issue.record("expected committed, got \(result)")+ return+ }++ let work = try await fixture.repository.work(id: BackupV17Fixtures.composedWorkID)+ #expect(work.releaseDays == [])+ #expect(work.releaseDaysRaw == [])+ }++ @Test("An archive carrying a schedule restores it exactly")+ func nonEmptySetRestores() async throws {+ let fixture = try await M5Fixture()++ let result = try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.composedPayload(releaseDays: [.thursday, .monday])))+ guard case .committed = result else {+ Issue.record("expected committed, got \(result)")+ return+ }++ let work = try await fixture.repository.work(id: BackupV17Fixtures.composedWorkID)+ #expect(work.releaseDays == [.monday, .thursday])+ // Req 7.5: one spelling in the store, whatever order the file held.+ #expect(work.releaseDaysRaw == ["monday", "thursday"])+ }++ /// Import is an upsert, and the record has already passed the never-regress+ /// guard by the time the schedule is written — so a *newer* archive's set+ /// lands over the local one, including the empty set. Restoring a backup+ /// taken after the reader cleared a work's days has to clear them here too,+ /// or the restore would silently be a union.+ @Test("An imported schedule replaces the local one, the empty set included")+ func importReplacesTheLocalSchedule() async throws {+ let fixture = try await M5Fixture()+ _ = try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.composedPayload(releaseDays: [.friday])))+ #expect(+ try await fixture.repository.work(id: BackupV17Fixtures.composedWorkID).releaseDays+ == [.friday])++ // The same record, a second later, with the schedule cleared.+ let cleared = BackupV17Fixtures.composedPayload(releaseDays: [])+ let newer = BackupV17Payload(+ entries: cleared.entries,+ works: cleared.works.map { record in+ BackupV17Work(+ id: record.id, displayTitle: record.displayTitle,+ lastParsedTitle: record.lastParsedTitle,+ genericNotes: record.genericNotes, genreTags: record.genreTags,+ titleProvenance: record.titleProvenance,+ workStatus: record.workStatus, readingStatus: record.readingStatus,+ verdict: record.verdict, releaseDays: [],+ workTypeID: record.workTypeID, typeName: record.typeName,+ createdAt: record.createdAt,+ modifiedAt: record.modifiedAt.addingTimeInterval(1))+ },+ sites: cleared.sites, titlePatterns: cleared.titlePatterns,+ urlRules: cleared.urlRules, workTypes: cleared.workTypes,+ memberships: cleared.memberships)++ _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(newer))++ #expect(+ try await fixture.repository.work(id: BackupV17Fixtures.composedWorkID).releaseDays+ == [])+ }++ /// Decision 8's guard is untouched by this field: an archive record **older**+ /// than the local row is skipped whole, so a stale backup cannot put back a+ /// schedule the reader has since changed.+ @Test("An older archive record does not regress a newer local schedule")+ func olderArchiveDoesNotRegressTheSchedule() async throws {+ let fixture = try await M5Fixture()+ _ = try await fixture.repository.confirmImport(+ plan: BackupV17Fixtures.plan(+ BackupV17Fixtures.composedPayload(releaseDays: [.friday])))++ let stale = BackupV17Fixtures.composedPayload(releaseDays: [.monday])+ let older = BackupV17Payload(+ entries: stale.entries,+ works: stale.works.map { record in+ BackupV17Work(+ id: record.id, displayTitle: record.displayTitle,+ lastParsedTitle: record.lastParsedTitle,+ genericNotes: record.genericNotes, genreTags: record.genreTags,+ titleProvenance: record.titleProvenance,+ workStatus: record.workStatus, readingStatus: record.readingStatus,+ verdict: record.verdict, releaseDays: [.monday],+ workTypeID: record.workTypeID, typeName: record.typeName,+ createdAt: record.createdAt,+ modifiedAt: record.modifiedAt.addingTimeInterval(-1))+ },+ sites: stale.sites, titlePatterns: stale.titlePatterns,+ urlRules: stale.urlRules, workTypes: stale.workTypes,+ memberships: stale.memberships)++ _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(older))++ #expect(+ try await fixture.repository.work(id: BackupV17Fixtures.composedWorkID).releaseDays+ == [.friday])+ }++ // MARK: - What is refused (Req 8.1, Q22, Q36)++ /// A Work record without the key is malformed, not a pre-feature record with+ /// no schedule. The refusal is a decode failure rather than a checksum one —+ /// 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 16/17 Work record omitting releaseDays fails to decode")+ func recordWithoutTheFieldRefuses() throws {+ let document = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.releaseDaysOmittedPayloadJSON,+ entryCount: 1, workCount: 1)++ do {+ _ = try BackupV17Codec.decode(document)+ Issue.record("expected a decode refusal, but the document decoded")+ } catch let error as BackupCodecError {+ guard case .decodingFailed = error else {+ Issue.record("expected .decodingFailed, got \(error)")+ return+ }+ }++ let complete = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.citationVersionFreePayloadJSON,+ entryCount: 1, workCount: 1)+ let record = try #require(try BackupV17Codec.decode(complete).payload.works.first)+ #expect(record.releaseDays == [])+ }++ /// Q36: the list decodes into the typed `[ReleaseDay]`, so a spelling this+ /// 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 16/17 Work record carrying an unknown day fails to decode")+ func recordWithAnUnknownDayRefuses() throws {+ let document = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.unknownReleaseDayPayloadJSON,+ entryCount: 1, workCount: 1)++ do {+ _ = try BackupV17Codec.decode(document)+ Issue.record("expected a decode refusal, but the document decoded")+ } catch let error as BackupCodecError {+ guard case .decodingFailed = error else {+ Issue.record("expected .decodingFailed, got \(error)")+ return+ }+ }++ // 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 = BackupV17Fixtures.literalDocument(+ payload: BackupV17Fixtures.populatedReleaseDaysPayloadJSON,+ entryCount: 1, workCount: 1)+ let record = try #require(try BackupV17Codec.decode(known).payload.works.first)+ #expect(record.releaseDays == [.monday, .thursday])+ }++ /// `remove-article-mode` Req 5.3: the generation this one replaced is refused+ /// **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 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 = BackupV17Fixtures.retiredGenerationDocument(format: 15, schema: 16)++ let error = #expect(throws: BackupImportError.self) {+ try BackupImporter.plan(from: data)+ }+ guard case .unsupportedFormat(let reason) = error else {+ Issue.record("expected an unsupported-format refusal, got \(String(describing: error))")+ return+ }+ #expect(reason.contains("format 15"))+ #expect(reason.contains("schema 16"))+ #expect(reason.contains("(17/18)"))++ // 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+ // for `confirmImport` to take — the library is structurally unreachable+ // from a 14/15 file, and the hostnames are here to say so out loud.+ let after = try await fixture.repository.sites()+ #expect(after.map(\.hostname) == before.map(\.hostname))+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17RestoreAssertions.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17RestoreAssertions.swiftnew file mode 100644index 00000000..700f94d7--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV17RestoreAssertions.swift@@ -0,0 +1,56 @@+import Foundation+import Testing+@testable import AsterismCore++/// A restored note is a fresh occurrence, so its import adds clear evidence.+/// Every other archive record must still round-trip exactly, and no prior action+/// may be replaced by the import's new evidence.+enum BackupV17RestoreAssertions {+ private struct Scope: Hashable {+ let workID: UUID+ let day: String+ }++ static func expectExactRecordsAndFreshNoteClears(+ before: BackupV17Payload, after: BackupV17Payload,+ sourceLocation: SourceLocation = #_sourceLocation+ ) throws {+ #expect(after.entries == before.entries, sourceLocation: sourceLocation)+ #expect(after.works == before.works, sourceLocation: sourceLocation)+ #expect(after.sites == before.sites, sourceLocation: sourceLocation)+ #expect(after.titlePatterns == before.titlePatterns, sourceLocation: sourceLocation)+ #expect(after.urlRules == before.urlRules, sourceLocation: sourceLocation)+ #expect(after.workTypes == before.workTypes, sourceLocation: sourceLocation)+ #expect(after.memberships == before.memberships, sourceLocation: sourceLocation)+ #expect(after.distinctPairs == before.distinctPairs, sourceLocation: sourceLocation)+ #expect(after.characters == before.characters, sourceLocation: sourceLocation)+ #expect(after.suppressions == before.suppressions, sourceLocation: sourceLocation)+ #expect(after.places == before.places, sourceLocation: sourceLocation)+ #expect(after.placeSuppressions == before.placeSuppressions, sourceLocation: sourceLocation)+ #expect(after.series == before.series, sourceLocation: sourceLocation)+ #expect(after.links == before.links, sourceLocation: sourceLocation)+ #expect(after.creators == before.creators, sourceLocation: sourceLocation)+ #expect(after.creatorRoles == before.creatorRoles, sourceLocation: sourceLocation)+ #expect(after.credits == before.credits, sourceLocation: sourceLocation)++ for retained in before.noEpisodeActions {+ #expect(after.noEpisodeActions.contains(retained), sourceLocation: sourceLocation)+ }+ let added = after.noEpisodeActions.filter { !before.noEpisodeActions.contains($0) }+ let noteScopes = Set(before.entries.compactMap { entry -> Scope? in+ guard let workID = entry.workID else { return nil }+ return Scope(workID: workID,+ day: CivilDay(entry.lastSharedAt, calendar: .current).description)+ })+ #expect(!added.isEmpty, sourceLocation: sourceLocation)+ var freshScopes: Set<Scope> = []+ for row in added {+ let action = try row.action()+ let scope = Scope(workID: action.workID, day: action.day)+ #expect(action.kind == .clear, sourceLocation: sourceLocation)+ #expect(noteScopes.contains(scope), sourceLocation: sourceLocation)+ if action.key.hasPrefix("clear/") { freshScopes.insert(scope) }+ }+ #expect(freshScopes == noteScopes, sourceLocation: sourceLocation)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swiftindex 4e7ce089..7a29588e 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() == "17",+ #expect(try root.markerText() == "18", "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("17\n")+ try root.writeMarker("18\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("17\n")+ try root.writeMarker("18\n") case .readinessMarkerWithoutAStore: try root.createStoreDirectory()- try root.writeMarker("17\n")+ try root.writeMarker("18\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 a5f67eed..2e019932 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("17\n")+ try root.writeMarker("18\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("17\n")+ try root.writeMarker("18\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("17\n")+ try root.writeMarker("18\n") try #require(StoreMetadata.recordedVersion(at: root.storeURL) == .indeterminate) #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready,@@ -430,6 +430,7 @@ private struct Cell: Sendable, CustomStringConvertible { case .fifteen: try root.writeMarker("15\n") case .sixteen: try root.writeMarker("16\n") case .seventeen: try root.writeMarker("17\n")+ case .eighteen: try root.writeMarker("18\n") case .unrecognisedText: try root.writeMarker("99\n") case .nonUTF8: try root.writeMarkerBytes(ClassifierRoot.nonUTF8MarkerBytes) }@@ -442,7 +443,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 == .seventeen, storePresent { return .ready }+ if marker == .eighteen, storePresent { return .ready }+ if marker == .seventeen, storePresent { return .markerLagging(generation: "17") } if marker == .sixteen, storePresent { return .markerLagging(generation: "16") } if !storePresent { if marker != .absent { return .orphanedEvidence(kind: .readinessMarker) }@@ -470,7 +472,7 @@ private enum StoreFamily: String, CaseIterable, Sendable { } private enum MarkerAxis: String, CaseIterable, Sendable {- case absent, four, five, six, fourteen, fifteen, sixteen, seventeen, unrecognisedText, nonUTF8+ case absent, four, five, six, fourteen, fifteen, sixteen, seventeen, eighteen, 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 57bb3c01..b29a7b97 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift@@ -279,7 +279,7 @@ private enum PreCertificationState: String, CaseIterable, Sendable { /// The bytes a certified library's readiness marker holds. Frozen persisted state /// — `FrozenLibraryPathTests` is where that is pinned; here it is the value the /// ready cases compare against.-private let readyMarkerBytes = "17\n"+private let readyMarkerBytes = "18\n" /// The counts of a library seeded with exactly one `Site`. ///
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swiftindex 7bb0153e..52ebd405 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift@@ -6,17 +6,17 @@ import Testing @Suite("Catch-up archive 16/17", .serialized) struct CatchUpArchiveTests {- private static let base = BackupV16Fixtures.minimalTaughtPayload()+ private static let base = BackupV17Fixtures.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 {+ modifiedAt: Date = BackupV17Fixtures.created+ ) -> BackupV17Payload { let original = base.works[0]- let work = BackupV16Work(+ let work = BackupV17Work( id: original.id, displayTitle: original.displayTitle, lastParsedTitle: original.lastParsedTitle, genericNotes: original.genericNotes, genreTags: original.genreTags, titleProvenance: original.titleProvenance,@@ -27,7 +27,7 @@ struct CatchUpArchiveTests { latestReleasedChapter: latest, latestConfirmedAt: confirmation, countsUpOnReleaseDays: false, latestIsEstimate: true, lastChapterOverride: override, lastChapterOverrideAt: overrideMoment)- return BackupV16Payload(+ return BackupV17Payload( entries: base.entries, works: [work], sites: base.sites, titlePatterns: base.titlePatterns, urlRules: base.urlRules, workTypes: base.workTypes, memberships: base.memberships,@@ -41,8 +41,8 @@ struct CatchUpArchiveTests { @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)+ let data = try BackupV17Codec.encode(payload: original, metadata: BackupV17Fixtures.metadata())+ let work = try #require(try BackupV17Codec.decode(data).payload.works.first) #expect(work.latestReleasedChapter == 52) #expect(work.latestConfirmedAt == Self.confirmedAt) #expect(work.countsUpOnReleaseDays == false)@@ -58,14 +58,14 @@ struct CatchUpArchiveTests { #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)+ let data = try BackupV17Codec.encode(+ payload: Self.payload(latest: number), metadata: BackupV17Fixtures.metadata())+ _ = try BackupV17Codec.decode(data) } #expect(throws: BackupCodecError.self) {- let data = try BackupV16Codec.encode(- payload: Self.payload(override: number), metadata: BackupV16Fixtures.metadata())- _ = try BackupV16Codec.decode(data)+ let data = try BackupV17Codec.encode(+ payload: Self.payload(override: number), metadata: BackupV17Fixtures.metadata())+ _ = try BackupV17Codec.decode(data) } } }@@ -75,18 +75,18 @@ struct CatchUpArchiveTests { 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))+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(100))+ _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(local)) let older = Self.payload(latest: 40, confirmation: Self.confirmedAt.addingTimeInterval(10),- modifiedAt: BackupV16Fixtures.created)- let plan = BackupV16Fixtures.plan(older)+ modifiedAt: BackupV17Fixtures.created)+ let plan = BackupV17Fixtures.plan(older) _ = try await fixture.repository.confirmImport(plan: plan)- let first = try await fixture.repository.work(id: BackupV16Fixtures.minimalWorkID)+ let first = try await fixture.repository.work(id: BackupV17Fixtures.minimalWorkID) #expect(first.catchUp.latest == 40)- #expect(first.modifiedAt == BackupV16Fixtures.created.addingTimeInterval(100))+ #expect(first.modifiedAt == BackupV17Fixtures.created.addingTimeInterval(100)) saves.arm() _ = try await fixture.repository.confirmImport(plan: plan)- let second = try await fixture.repository.work(id: BackupV16Fixtures.minimalWorkID)+ let second = try await fixture.repository.work(id: BackupV17Fixtures.minimalWorkID) #expect(second.catchUp == first.catchUp) #expect(second.modifiedAt == first.modifiedAt) #expect(saves.saves > 0)@@ -97,37 +97,37 @@ struct CatchUpArchiveTests { 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))+ _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.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)+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(50))+ _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(earlier))+ #expect(try await fixture.repository.work(id: BackupV17Fixtures.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)+ _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(tied))+ #expect(try await fixture.repository.work(id: BackupV17Fixtures.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)))+ plan: BackupV17Fixtures.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)+ in: context, id: BackupV17Fixtures.minimalWorkID,+ title: "Different authored title", hostname: BackupV17Fixtures.minimalHost,+ timestamp: BackupV17Fixtures.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))+ modifiedAt: BackupV17Fixtures.created.addingTimeInterval(100))+ _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.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 }+ .filter { $0.id == BackupV17Fixtures.minimalWorkID } .map(\.catchUpRecord) } #expect(values.count == 2)@@ -137,35 +137,35 @@ struct CatchUpArchiveTests { @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.confirmImport(plan: BackupV17Fixtures.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 })+ .first { $0.id == BackupV17Fixtures.minimalWorkID }) work.catchUpConfirmationData = Data("broken".utf8) try context.save() } do {- _ = try await fixture.repository.backupV16Snapshot()+ _ = try await fixture.repository.backupV17Snapshot() Issue.record("expected an export refusal")- } catch let error as BackupV16ExportError {+ } catch let error as BackupV17ExportError { 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(record.contains(BackupV17Fixtures.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 old = BackupV17Fixtures.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)"))+ #expect(reason.contains("(17/18)")) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpProgressTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpProgressTests.swiftindex a8bb4b2a..cb2608e1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpProgressTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpProgressTests.swift@@ -142,4 +142,32 @@ struct CatchUpProgressTests { #expect(result?.confirmation?.confirmedAtMilliseconds == MillisecondInstant.milliseconds(day)) #expect(result?.override == old.override) }++ @Test("Marked dates reduce both expected-latest bounds without changing confirmations")+ func noEpisodeBounds() {+ let cal = calendar()+ let confirmedAt = instant(2026, 3, 5, calendar: cal)+ let readAt = instant(2026, 3, 12, calendar: cal)+ let end = CivilDay(instant(2026, 3, 26, calendar: cal), calendar: cal)+ let marked: Set<CivilDay> = [+ CivilDay(instant(2026, 3, 19, calendar: cal), calendar: cal), end+ ]+ let baseline = record(10, at: confirmedAt)+ let note = NumberedNote(number: 11, firstCapturedAt: readAt, title: "11")+ let progress = CatchUpProgress.build(+ record: baseline, notes: [note], releaseDays: [.thursday],+ noEpisodeDays: marked, workStatus: .ongoing, day: end, calendar: cal)+ #expect(progress.effectiveLatest == 11)+ #expect(progress.state == .caughtUp)+ #expect(baseline.latest == 10)+ let disabled = CatchUpProgress.build(+ record: record(10, at: confirmedAt, countsUp: false), notes: [note],+ releaseDays: [.thursday], noEpisodeDays: marked,+ workStatus: .ongoing, day: end, calendar: cal)+ #expect(disabled.effectiveLatest == 11)+ let unknown = CatchUpProgress.build(+ record: .pristine, notes: [note], releaseDays: [.thursday],+ noEpisodeDays: marked, workStatus: .ongoing, day: end, calendar: cal)+ #expect(unknown.effectiveLatest == nil)+ } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swiftindex d2b7b965..e865beae 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift@@ -124,4 +124,35 @@ struct CatchUpRebaseRepositoryTests { } #expect(try fixture.workRows(id: id).first?.catchUpRecord == before) }++ @Test("Rebase gives a live note precedence over an acknowledged overlapping mark")+ func liveNotePrecedesOverlappingMark() async throws {+ let noteAt = calendar().date(byAdding: .day, value: -3, to: WriteFixture.epoch)!+ let noteDay = CivilDay(noteAt, calendar: calendar())+ let (fixture, id) = try seeded(latest: 50, days: [noteDay.weekday(calendar: calendar())])+ let repository = try await fixture.openForApp()+ try await repository.prepareNoEpisodeNotes(calendar: calendar())+ let context = try fixture.readContext()+ let clearKeys = try NoEpisodeIndex(context: context).history(for: id)+ .clearKeys(workID: id, day: noteDay.description)+ #expect(!clearKeys.isEmpty)+ _ = try NoEpisodeWriter.insertMissing([+ .init(workID: id, key: "mark/\(UUID().uuidString)",+ day: noteDay.description, kind: .mark,+ observedClearKeys: clearKeys.sorted())+ ], context: context)+ try context.save()++ let work = try await repository.work(id: id)+ #expect(work.noEpisodeHistory.activeDays(for: id).contains(noteDay))+ let expected = CatchUpProgress.build(+ work: work, day: CivilDay(WriteFixture.epoch, calendar: calendar()),+ calendar: calendar()).effectiveLatest+ #expect(expected == 51)+ let outcome = try await repository.updateWork(+ id: id, basis: WorkEditBasis(work: work),+ draft: draft(work, status: .hiatus), calendar: calendar())+ #expect(outcome == .committed)+ #expect(try fixture.workRows(id: id).first?.catchUpRecord.latest == expected)+ } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swiftindex 378d6846..26a633ca 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift@@ -34,7 +34,8 @@ struct CatchUpWriterTests { #expect(row.catchUpRecord.confirmation == nil) #expect(row.catchUpRecord.override == first.override) let snapshot = LibraryRepository.snapshot(- row, entries: [], types: .empty, series: .empty, credits: .empty)+ row, entries: [], types: .empty, series: .empty, credits: .empty,+ history: .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 3b88593c..9850df7f 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift@@ -107,7 +107,7 @@ struct CertificationPathTests { // unopenable rather than because the marker was read first. try Data("16\n".utf8).write(to: cfg.readinessMarkerURL, options: .atomic) _ = try await LibraryRepository.openForApp(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["17.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["18.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) == "17",+ #expect(try markerContent(cfg) == "18", "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 eaa82fc9..8400c561 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 `BackupV16ImportTests`, which ask the+/// Shared by `EmptyLibraryTests` and `BackupV17ImportTests`, 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 5dbc27a9..d3c579d2 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: BackupV16ExportError.self) {- _ = try await fixture.repository.backupV16Snapshot()+ await #expect(throws: BackupV17ExportError.self) {+ _ = try await fixture.repository.backupV17Snapshot() } 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 `BackupV16Character` carries as its+ /// `CharacterGroup.modifiedAt` is what `BackupV17Character` 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 a5ec9fd8..afc3f2b3 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ComposedCaptureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ComposedCaptureTests.swiftindex 237f6d10..b7ae67b3 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ComposedCaptureTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ComposedCaptureTests.swift@@ -22,6 +22,92 @@ struct ComposedCaptureTests { .sequence(locator: .query(name: ExactScalarString("chapter"))) } + @Test("A committed rule-assigned capture clears a matching no-episode mark")+ func committedCaptureClearsMark() async throws {+ let fixture = try ComposedCaptureFixture()+ try fixture.seedUntaught([(UUID(), "Solo Story", "https://ex.com/read?chapter=1")])+ try await fixture.teach(ComposedTeachingRequest(+ titleDefinition: .wholeTitle, urlDefinition: sequenceURL()))+ let context = fixture.freshContext()+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ let calendar = Calendar.current+ let day = CivilDay(Date(timeIntervalSince1970: 1_800_000_000), calendar: calendar)+ work.releaseDays = [day.weekday(calendar: calendar)]+ try context.save()+ #expect(try await fixture.repository.markNoEpisode(+ workID: work.id, day: day, calendar: calendar) == .committed)++ let captured = try await fixture.capture(+ title: "Solo Story", rawURL: "https://ex.com/read?chapter=2")+ #expect(captured.workID == work.id)+ let history = try NoEpisodeIndex(context: fixture.freshContext()).history(for: work.id)+ #expect(try !history.isMarked(workID: work.id, day: day.description))+ #expect(try await fixture.repository.deleteEntry(+ id: captured.id, basis: EntryEditBasis(entry: captured),+ disclosedVariants: nil) == .committed)+ #expect(try !NoEpisodeIndex(context: fixture.freshContext()).history(for: work.id)+ .isMarked(workID: work.id, day: day.description))+ }++ @Test("Composed teaching clears a mark when it attaches an existing note")+ func teachingAssignmentClearsMark() async throws {+ let fixture = try ComposedCaptureFixture()+ try fixture.seedSite()+ let context = fixture.freshContext()+ let site = try #require(try context.fetch(FetchDescriptor<Site>()).first)+ let instant = Date(timeIntervalSince1970: 1_800_000_000)+ let day = CivilDay(instant, calendar: .current)+ let work = Work.create(in: context, title: "Solo Story", hostname: "ex.com",+ site: site, timestamp: instant)+ work.lastParsedTitle = "Solo Story"+ work.titleProvenanceRaw = TitleProvenance.parsed.rawValue+ work.releaseDays = [day.weekday(calendar: .current)]+ let entry = Entry(captureTitle: "Solo Story", captureTitleSource: .host,+ rawURLString: "https://ex.com/read?chapter=1", hostname: "ex.com",+ entryIdentityKey: "https://ex.com/read?chapter=1", timestamp: instant)+ entry.conservativeIdentityKey = entry.rawURLString+ entry.site = site+ context.insert(entry)+ try context.save()+ #expect(try await fixture.repository.markNoEpisode(+ workID: work.id, day: day, calendar: .current) == .committed)++ try await fixture.teach(ComposedTeachingRequest(+ titleDefinition: .wholeTitle, urlDefinition: sequenceURL()))+ let attached = try await fixture.repository.entry(id: entry.id)+ #expect(attached.workID == work.id)+ #expect(try !NoEpisodeIndex(context: fixture.freshContext()).history(for: work.id)+ .isMarked(workID: work.id, day: day.description))+ }++ @Test("Committed reparse clears a mark when it attaches a note")+ func committedReparseClearsMark() async throws {+ let fixture = try ComposedCaptureFixture()+ try fixture.seedUntaught([(UUID(), "Solo Story", "https://ex.com/read?chapter=1")])+ try await fixture.teach(ComposedTeachingRequest(+ titleDefinition: .wholeTitle, urlDefinition: sequenceURL()))+ let context = fixture.freshContext()+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ let site = try #require(try context.fetch(FetchDescriptor<Site>()).first)+ let instant = Date(timeIntervalSince1970: 1_800_000_000)+ let day = CivilDay(instant, calendar: .current)+ work.releaseDays = [day.weekday(calendar: .current)]+ let entry = Entry(captureTitle: "Solo Story", captureTitleSource: .host,+ rawURLString: "https://ex.com/read?chapter=2", hostname: "ex.com",+ entryIdentityKey: "https://ex.com/read?chapter=2", timestamp: instant)+ entry.conservativeIdentityKey = entry.rawURLString+ entry.site = site+ context.insert(entry)+ try context.save()+ #expect(try await fixture.repository.markNoEpisode(+ workID: work.id, day: day, calendar: .current) == .committed)+ let contract = try await fixture.repository.projectReparse(entryID: entry.id)+ #expect(try await fixture.repository.commitReparse(contract) == .committed)+ #expect(try await fixture.repository.entry(id: entry.id).workID == work.id)+ #expect(try !NoEpisodeIndex(context: fixture.freshContext()).history(for: work.id)+ .isMarked(workID: work.id, day: day.description))+ }+ // MARK: - Capture-after-teaching matrix @Test("Capture after WC + identity-sequence teach: v2 key, chapter, sequence, identity reuse")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swiftindex 784f7088..76a7a974 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #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 BackupV16Codec.encode(+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))- let decoded = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+ let decoded = try BackupV17Codec.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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #expect(payload.titlePatterns.count == 1) #expect(payload.titlePatterns.first?.isActive == true) #expect(payload.sites.first?.mode == .taught)- let encoded = try BackupV16Codec.encode(+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))- _ = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+ _ = try BackupV17Codec.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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() #expect(payload.urlRules.count == 1) #expect(payload.urlRules.first?.id == shared) #expect(payload.urlRules.first?.isCurrent == true)- let encoded = try BackupV16Codec.encode(+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))- _ = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+ _ = try BackupV17Codec.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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) let container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.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 64a945c3..a8e9a5b6 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swiftindex e4976f34..6c61fa1b 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swiftindex 2de7a2d9..fca697a5 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swiftindex 3c81052a..f5c10052 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 BackupV16Codec.encode(- payload: try await fixture.repository.backupV16Snapshot(),- metadata: BackupV16Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))+ let archive = try BackupV17Codec.encode(+ payload: try await fixture.repository.backupV17Snapshot(),+ metadata: BackupV17Metadata(appBuild: "test", exportedAt: M5Fixture.epoch)) let restored = try await M5Fixture() try await restored.repository.confirmImport(plan: try BackupImporter.plan(from: archive))
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swiftindex 200e3eba..8f5c81b3 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 BackupV16Codec.encode(- payload: try await source.repository.backupV16Snapshot(),+ let archive = try BackupV17Codec.encode(+ payload: try await source.repository.backupV17Snapshot(), metadata: BackupGoldenLibrary.metadata) let target = try await M5Fixture()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swiftindex e3bcf519..42a297af 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) seed = ModelContext(container) if let saveStrategy {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swiftindex eb93efa0..16cd0294 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift@@ -16,6 +16,39 @@ import Testing @Suite("Duplicate resolution contract", .serialized) struct DuplicateResolutionTests { + @Test("Manual Work resolution carries no-episode actions to the surviving identity")+ func workResolutionCarriesNoEpisodeActions() async throws {+ let library = try ResolutionFixture()+ let survivorID = UUID()+ let loserID = UUID()+ try library.seed { store in+ store.insertSite(hostname: "dup.example")+ store.insertWork(id: survivorID, title: "Serial", offset: 0, notes: "kept")+ store.insertWork(id: loserID, title: "Serial", offset: 40, notes: "other")+ }+ let day = CivilDay(ResolutionFixture.epoch, calendar: .current)+ let clearKey = "clear/\(UUID().uuidString)"+ let markKey = "mark/\(UUID().uuidString)"+ try library.mutate { store in+ try NoEpisodeWriter.insertMissing([+ .init(workID: loserID, key: clearKey, day: day.description,+ kind: .clear, observedClearKeys: []),+ .init(workID: loserID, key: markKey, day: day.description,+ kind: .mark, observedClearKeys: [clearKey]),+ ], context: store.context)+ }+ let repository = try await library.openForApp()+ let contract = try await repository.projectDuplicateResolution(+ setKey: try Self.onlyWorkSetKey(library))+ #expect(try await repository.commitDuplicateResolution(+ contract, choosing: contract.preselected) == .committed(survivorID: survivorID))+ let index = try NoEpisodeIndex(context: library.readContext())+ #expect(try index.history(for: loserID).actions.isEmpty)+ let moved = try index.history(for: survivorID)+ #expect(Set(moved.actions.map(\.key)) == [clearKey, markKey])+ #expect(try moved.isMarked(workID: survivorID, day: day.description))+ }+ // MARK: - Projection (Req 4.2) @Test("The sheet presents every variant, the fields they differ in, and preselects the leading one")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swiftindex 77fcac4a..65950d18 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swiftindex 419014da..0aa455e0 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift@@ -23,7 +23,7 @@ struct EmptyLibraryTests { try await fixture.seedGoldenLibrary() let before = try await fixture.repository.emptyLibraryRowCounts()- #expect(before.count == 17, "the phase list must name every entity")+ #expect(before.count == 18, "the phase list must name every entity") #expect( before.values.allSatisfy { $0 > 0 }, "the seed leaves \(before.filter { $0.value == 0 }.keys.sorted()) empty")@@ -454,23 +454,22 @@ struct EmptyLibraryTests { // MARK: - Req 5.1: the round trip - /// Export, empty, import, export. Payload to payload, which is archive- /// equality with the export metadata masked (Q15) — the payload carries no- /// `exportedAt` and no file name at all, so the comparison is exactly the- /// one the requirement asks for.+ /// Export, empty, import, export. Restoring notes adds fresh clear evidence;+ /// every prior action and every non-action record must survive exactly. @Test("An archive exported before the emptying restores the library exactly") func exportEmptyImportExportIsExact() async throws { let fixture = try await EmptyLibraryFixture() try await fixture.seedGoldenLibrary() - let before = try await fixture.repository.backupV16Snapshot()+ let before = try await fixture.repository.backupV17Snapshot() 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.backupV16Snapshot()+ let after = try await fixture.repository.backupV17Snapshot() - #expect(after == before)+ try BackupV17RestoreAssertions.expectExactRecordsAndFreshNoteClears(+ before: before, after: after) await fixture.tearDown() } @@ -492,10 +491,10 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture(saveStrategy: strategy) try await fixture.seedGoldenLibrary() - let archive = try await fixture.repository.backupV16Snapshot()+ let archive = try await fixture.repository.backupV17Snapshot() _ = try await fixture.repository.emptyLibrary() try await fixture.repository.confirmImport(plan: EmptyLibraryFixture.plan(archive))- let restored = try await fixture.repository.backupV16Snapshot()+ let restored = try await fixture.repository.backupV17Snapshot() let stamps = try await fixture.repository.modificationStampsForTesting() strategy.arm()@@ -505,7 +504,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.backupV16Snapshot() == restored)+ #expect(try await fixture.repository.backupV17Snapshot() == restored) #expect(try await fixture.repository.modificationStampsForTesting() == stamps) await fixture.tearDown() }@@ -517,7 +516,7 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture() try await fixture.seedGoldenLibrary() - let archive = try await fixture.repository.backupV16Snapshot()+ let archive = try await fixture.repository.backupV17Snapshot() let late = try await fixture.repository.capture( CaptureDraft( captureTitle: "Chapter 9 - After the export",@@ -810,7 +809,7 @@ private final class EmptyLibraryFixture { func seedGoldenLibrary() async throws { try await repository.confirmImport( plan: try BackupImporter.plan(- from: try BackupV16Codec.encode(+ from: try BackupV17Codec.encode( payload: BackupGoldenLibrary.payload, metadata: BackupGoldenLibrary.metadata))) }@@ -859,11 +858,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: BackupV16Payload) -> BackupImportPlan {+ static func plan(_ payload: BackupV17Payload) -> BackupImportPlan { BackupImportPlan( metadata: BackupImportMetadata(- formatVersion: BackupV16Document.formatVersion,- schemaVersion: BackupV16Document.schemaVersion,+ formatVersion: BackupV17Document.formatVersion,+ schemaVersion: BackupV17Document.schemaVersion, appBuild: "empty-library-test", exportedAt: BackupGoldenLibrary.created, capabilityGate: "multi-site", entryCount: payload.entries.count, workCount: payload.works.count),
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swiftindex 6fe26700..fdf13cc8 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.backupV16Snapshot()+ _ = try await repository.backupV17Snapshot() Issue.record("the export archived an unrepresentable value")- } catch let error as BackupV16ExportError {+ } catch let error as BackupV17ExportError { 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.backupV16Snapshot()+ _ = try await repository.backupV17Snapshot() Issue.record("the export archived an unreadable citation blob")- } catch let error as BackupV16ExportError {+ } catch let error as BackupV17ExportError { guard case .unrepresentableValue(_, let refused, _) = error else { Issue.record("expected .unrepresentableValue, got \(error)") return
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ExportInputReadTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ExportInputReadTests.swiftindex 819eed27..c79fa55d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ExportInputReadTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ExportInputReadTests.swift@@ -387,7 +387,8 @@ struct ExportInputReadTests { var sites = LibraryRepository.SiteLookupCache() return try LibraryRepository.exportInput( for: snapshot, includingWork: true, sites: &sites,- context: context, locale: auLocale)+ context: context, locale: auLocale,+ noEpisode: NoEpisodeIndex(context: context)) } // The line is omitted; nothing else about the block is disturbed.
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swiftindex 0f83ba57..5dc7afab 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift@@ -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 = BackupV16Entry(+ let entry = BackupV17Entry( 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 = BackupV16Site(+ let site = BackupV17Site( 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 b3a6a5fe..a747d26d 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 `BackupV16Exporter` — the same-/// `backupV16Snapshot()` → `BackupV16Codec.encode` → decode-validate → write path+/// The archive is produced through the real `BackupV17Exporter` — the same+/// `backupV17Snapshot()` → `BackupV17Codec.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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(repository: repository, stagingDirectory: staging) let result = try await exporter.export(- metadata: BackupV16Metadata(appBuild: "fixture-5k", exportedAt: exportedAt))+ metadata: BackupV17Metadata(appBuild: "fixture-5k", exportedAt: exportedAt)) withExtendedLifetime(container) {} try FileManager.default.createDirectory(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-17-18-golden.json b/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-17-18-golden.jsonnew file mode 100644index 00000000..5e794ff6--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-17-18-golden.json@@ -0,0 +1 @@+{"appBuild":"golden","backupFormatVersion":17,"capabilityGate":"multi-site","checksum":"ee254d25df3476c5bd9083437f985dd6c6ce34a17024e29ba9f357539f53f2e9","databaseSchemaVersion":18,"entryCount":3,"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"}],"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"}],"noEpisodeActions":[{"key":"mark/10000000-0000-4000-8000-000000000002","payloadData":"eyJkYXkiOiIyMDI2LTA5LTI5Iiwia2V5IjoibWFyay8xMDAwMDAwMC0wMDAwLTQwMDAtODAwMC0wMDAwMDAwMDAwMDIiLCJraW5kIjoibWFyayIsIm9ic2VydmVkQ2xlYXJLZXlzIjpbImNsZWFyLzEwMDAwMDAwLTAwMDAtNDAwMC04MDAwLTAwMDAwMDAwMDAwMSJdLCJ2ZXJzaW9uIjoxfQ==","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"key":"clear/10000000-0000-4000-8000-000000000001","payloadData":"eyJkYXkiOiIyMDI2LTA5LTI5Iiwia2V5IjoiY2xlYXIvMTAwMDAwMDAtMDAwMC00MDAwLTgwMDAtMDAwMDAwMDAwMDAxIiwia2luZCI6ImNsZWFyIiwib2JzZXJ2ZWRDbGVhcktleXMiOltdLCJ2ZXJzaW9uIjoxfQ==","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEEE"},{"key":"mark/10000000-0000-4000-8000-000000000003","payloadData":"eyJkYXkiOiIyMDI2LTA5LTMwIiwia2V5IjoibWFyay8xMDAwMDAwMC0wMDAwLTQwMDAtODAwMC0wMDAwMDAwMDAwMDMiLCJraW5kIjoibWFyayIsIm9ic2VydmVkQ2xlYXJLZXlzIjpbXSwidmVyc2lvbiI6MX0=","workID":"EEEEEEEE-EEEE-EEEE-EEEE-EEEEEEEEEEE9"}],"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":"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":{}},"trimPrefix":"TtH • Story • "},"id":"CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC","isActive":true,"siteHostname":"golden.example","version":1},{"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}],"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":[{"createdAt":"1970-01-12T13:46:40.000Z","id":"00000000-0000-0000-0000-0000000000A1","modifiedAt":"1970-01-12T13:46:40.000Z","name":"novel","stateRaw":"active"},{"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"}],"works":[{"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"},{"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":"novella","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"}]},"workCount":3}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swiftindex 3ce22337..4740985d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift@@ -76,7 +76,7 @@ struct FrozenLibraryPathTests { /// moved it from `"5"` to `"6"` (Q26), `character-extraction` from `"6"` to /// `"7"` (Q80), and it now reads `"17"`, a two-character /// generation. What is frozen is the shape and the filename beside it.- private static let markerContents = "17\n"+ private static let markerContents = "18\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> = [- "AsterismSchemaV16", "AsterismSchemaV17",- "AsterismV17MigrationPlan",+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18",+ "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "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> = [- "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",+ "BackupV17Entry", "BackupV17Site", "BackupV17TitlePattern", "BackupV17URLRule",+ "BackupV17Work", "BackupV17WorkType", "BackupV17Membership", "BackupV17DistinctPair",+ "BackupV17Character", "BackupV17Codec", "BackupV17Series", "BackupV17Link",+ "BackupV17Document", "BackupV17ExportError", "BackupV17Exporter", "BackupV17Metadata",+ "BackupV17Payload", "BackupV17ReferenceValidator",+ "BackupV17SnapshotProviding", "BackupV17Suppression",+ "BackupV17Creator", "BackupV17CreatorRole", "BackupV17Credit",+ "BackupV17Place", "BackupV17PlaceSuppression", "BackupV17NoEpisodeAction",+ "backupV17Snapshot", "importedV2", "importedV2Path",- "mapV16EntryRecord", "mapV16SiteRecord", "mapV16TitlePatternRecord",- "mapV16URLRuleRecord", "mapV16WorkRecord",- "mapV16CharacterRecord", "mapV16SuppressionRecord",- "mapV16PlaceRecord", "mapV16PlaceSuppressionRecord",- "mapV16CreatorRecords", "mapV16CreatorRoleRecords",- "projectV16Payload",+ "mapV17EntryRecord", "mapV17SiteRecord", "mapV17TitlePatternRecord",+ "mapV17URLRuleRecord", "mapV17WorkRecord",+ "mapV17CharacterRecord", "mapV17SuppressionRecord",+ "mapV17PlaceRecord", "mapV17PlaceSuppressionRecord",+ "mapV17CreatorRecords", "mapV17CreatorRoleRecords",+ "projectV17Payload", ] /// 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() == [- "AsterismSchemaV16", "AsterismSchemaV17",+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", ], "the package declares versioned schemas \(declared); Req 3.3 allows only ones a plan references") - let referenced = AsterismV17MigrationPlan.schemas.map { String(describing: $0) }+ let referenced = AsterismV18MigrationPlan.schemas.map { String(describing: $0) } #expect(- referenced == ["AsterismSchemaV16", "AsterismSchemaV17"],+ referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18"], "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(- AsterismV17MigrationPlan.stages.count == 1,+ AsterismV18MigrationPlan.stages.count == 2, "the plan stages \(AsterismV17MigrationPlan.stages.count) migrations; V15 → V16 is one") #expect( AsterismSchemaV16.versionIdentifier == Schema.Version(16, 0, 0), "the frozen snapshot's version stamp is the `from` side every V15 store is matched on") #expect(- AsterismSchemaV17.versionIdentifier == Schema.Version(17, 0, 0),+ AsterismSchemaV18.versionIdentifier == Schema.Version(18, 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 6b5305d8..bd80aea0 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift@@ -269,11 +269,12 @@ struct GroupFetchTests { #expect(group.variantIDs == before.variantIDs) #expect(group.authoredContent == before.authoredContent) let row = LibraryRepository.snapshot(- bare, entries: [], types: .empty, series: .empty, credits: .empty)+ bare, entries: [], types: .empty, series: .empty, credits: .empty,+ history: .empty) #expect(row.catchUp.confirmation == newerConfirmation) let presented = try LibraryRepository.snapshot( group, entryRows: [], canonicalWorkIDs: [:], types: .empty,- series: .empty, credits: .empty)+ series: .empty, credits: .empty, history: .empty) #expect(presented.catchUp.confirmation == newerConfirmation) #expect(presented.catchUp.override == .value(20, atMilliseconds: 3_000)) }@@ -293,12 +294,12 @@ private final class GroupStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismGroupFetch-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swiftindex 97f3739a..3317f151 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swiftindex 2356c3e6..a6c40599 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swiftindex b5afd100..6da25957 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swift@@ -58,14 +58,16 @@ struct IntentAnswersTests { private static func work( id: UUID, title: String, releaseDays: [ReleaseDay],- readingStatus: ReadingStatus = .reading, entries: [EntrySnapshot] = []+ readingStatus: ReadingStatus = .reading, entries: [EntrySnapshot] = [],+ noEpisodeHistory: NoEpisodeHistory = .empty ) -> WorkSnapshot { WorkSnapshot( id: id, displayTitle: title, lastParsedTitle: nil, memberships: [WorkSiteMembershipSnapshot(id: UUID(), hostname: "example.test")], genericNotes: "", genreTags: [], titleProvenance: .parsed, createdAt: .distantPast, modifiedAt: .distantPast, entries: entries,- readingStatus: readingStatus, releaseDays: releaseDays)+ readingStatus: readingStatus, releaseDays: releaseDays,+ noEpisodeHistory: noEpisodeHistory) } private static func row(@@ -156,6 +158,46 @@ struct IntentAnswersTests { #expect(noted == ["Anchor": false, "Lately": false, "Zephyr": true]) } + @Test("Marked releases are removed before shortcut values and dialog are built")+ func markedReleaseIsAbsentFromEveryAnswer() throws {+ let markedID = Self.id(20)+ let action = try NoEpisodeHistory.Action(+ workID: markedID, key: "mark/\(UUID().uuidString)", day: Self.thursday.description,+ kind: .mark, observedClearKeys: [])+ let marked = Self.work(+ id: markedID, title: "Skipped", releaseDays: [.thursday],+ noEpisodeHistory: try NoEpisodeHistory([action]))+ let pending = Self.work(id: Self.id(21), title: "Pending", releaseDays: [.thursday])+ let noted = Self.work(+ id: Self.id(22), title: "Noted", releaseDays: [.thursday],+ entries: [Self.entry(sharedAt: Self.instant(2026, 3, 12))])+ let presentation = Self.presentation(works: [marked, pending, noted], days: [])++ let answer = IntentAnswers.releasingToday(+ presentation, currentDay: Self.thursday, calendar: Self.calendar())++ #expect(answer.map(\.title) == ["Noted", "Pending"])+ #expect(answer.map(\.notedToday) == [true, false])+ #expect(!IntentAnswers.dialog(for: answer).full.contains("Skipped"))+ }++ @Test("An all-marked day uses the existing empty shortcut answer")+ func allMarkedUsesEmptyAnswer() throws {+ let id = Self.id(23)+ let action = try NoEpisodeHistory.Action(+ workID: id, key: "mark/\(UUID().uuidString)", day: Self.thursday.description,+ kind: .mark, observedClearKeys: [])+ let work = Self.work(+ id: id, title: "Skipped", releaseDays: [.thursday],+ noEpisodeHistory: try NoEpisodeHistory([action]))+ let answer = IntentAnswers.releasingToday(+ Self.presentation(works: [work], days: []),+ currentDay: Self.thursday, calendar: Self.calendar())++ #expect(answer.isEmpty)+ #expect(IntentAnswers.dialog(for: answer).full == "No chapters are expected today.")+ }+ /// Req 1.4's midnight clause: an open Today screen may still show the /// previous day, but the intent is answered for the day it runs on. The /// presentation below was published on Thursday and holds only Thursday's
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swiftindex 8d92bdb9..a5f41d2c 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swiftindex 5574fc6a..9e35fbe0 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swiftindex d366fdd6..e481cc37 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swiftindex ccd6622f..003f988e 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 -> BackupV16Payload {+ static func exportedFixturePayload() async throws -> BackupV17Payload { 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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() withExtendedLifetime(container) {} return payload }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swiftindex da7c0af6..67caea65 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 `BackupV16Exporter.export`: the encode,+ /// The *projection* is timed, not `BackupV17Exporter.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.backupV16Snapshot()+ _ = try await repository.backupV17Snapshot() } 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 = BackupV16Exporter(repository: repository, stagingDirectory: staging)+ let exporter = BackupV17Exporter(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: BackupV16Metadata(appBuild: "m4-performance", exportedAt: Date()))+ metadata: BackupV17Metadata(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 BackupV16Exporter(+ let exported = try await BackupV17Exporter( repository: repository, stagingDirectory: staging- ).export(metadata: BackupV16Metadata(appBuild: "m4-performance", exportedAt: Date()))+ ).export(metadata: BackupV17Metadata(appBuild: "m4-performance", exportedAt: Date())) await repository.shutdown() return (exported.fileURL, try fileSize(of: exported.fileURL)) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ScalePerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ScalePerformanceTests.swiftindex f50aeea6..97035dbe 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ScalePerformanceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ScalePerformanceTests.swift@@ -453,6 +453,7 @@ struct M4ScalePerformanceTests { the no-op pass must be scanning the whole linked graph: expected \ \(LibraryRepository.m4FixtureEntryCount) linked Entries, found \(linked) """)+ try seedNoEpisodeActions(at: configuration.storeURL) let (result, repository) = try await LibraryRepository.openForApp( configuration, capabilities: .multiSite)@@ -463,6 +464,9 @@ struct M4ScalePerformanceTests { // The other half of the trap: a pass that writes something is not the // no-op case either.+ // Materialise note clears once; the measured pass is the unchanged+ // action-bearing graph, including the retained mark history.+ _ = try await repository.reconcileAfterSync() let first = try await repository.reconcileAfterSync() #expect( first.isEmpty,@@ -614,6 +618,23 @@ struct M4ScalePerformanceTests { let context = ModelContext(container) return try context.fetch(FetchDescriptor<Entry>()).filter { $0.site != nil }.count }++ private func seedNoEpisodeActions(at storeURL: URL) throws {+ let container = try LibraryRepository.openContainer(at: storeURL)+ defer { withExtendedLifetime(container) {} }+ let context = ModelContext(container)+ let workIDs = try context.fetch(FetchDescriptor<Work>()).map(\.id)+ let initialActionCount = try NoEpisodeIndex(context: context).allActions.count+ let actions = try workIDs.map {+ try NoEpisodeHistory.Action(+ workID: $0, key: "mark/\(UUID().uuidString)", day: "2099-01-01",+ kind: .mark, observedClearKeys: [])+ }+ _ = try NoEpisodeWriter.insertMissing(actions, context: context)+ try context.save()+ let finalActionCount = try NoEpisodeIndex(context: context).allActions.count+ #expect(finalActionCount - initialActionCount == Set(workIDs).count)+ } } // MARK: - Fixture: the worst consolidation the fixture can express
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swiftindex c6d68c43..664a9873 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift@@ -115,6 +115,8 @@ struct M4ToleratedScalePerformanceTests { func extensionOpenWithDuplicateSiteRows() async throws { let coherent = try await M4PerformanceStore(state: nil) let duplicated = try await M4PerformanceStore(state: .duplicateSiteRows)+ try coherent.seedNoEpisodeActions()+ try duplicated.seedNoEpisodeActions() let coherentOpen = try await measureExtensionOpen(coherent) let duplicatedOpen = try await measureExtensionOpen(duplicated)@@ -185,6 +187,7 @@ struct M4ToleratedScalePerformanceTests { @Test("Publishing a Today day ≤ 2 s over the M4 fixture (Req 10.5)") func todayPublication() async throws { let store = try await M4PerformanceStore(state: nil)+ try store.seedNoEpisodeActions() let repository = try await store.openApp() var calendar = Calendar(identifier: .gregorian)@@ -781,8 +784,30 @@ private final class M4PerformanceStore { return repository } + /// History-bearing M4 read shape: one mark per Work plus a longer clear+ /// history on one Work. The future date has no fixture note to overlap.+ func seedNoEpisodeActions() throws {+ let container = try LibraryRepository.openContainer(at: configuration.storeURL)+ let context = ModelContext(container)+ let workIDs = try context.fetch(FetchDescriptor<Work>())+ .map(\.id).sorted { $0.uuidString < $1.uuidString }+ var actions: [NoEpisodeHistory.Action] = try workIDs.map {+ try .init(workID: $0, key: "mark/\(UUID().uuidString)",+ day: "1970-01-08", kind: .mark, observedClearKeys: [])+ }+ if let first = workIDs.first {+ for _ in 0..<32 {+ actions.append(try .init(+ workID: first, key: "clear/\(UUID().uuidString)",+ day: "1970-01-08", kind: .clear, observedClearKeys: []))+ }+ }+ _ = try NoEpisodeWriter.insertMissing(actions, context: context)+ try context.save()+ withExtendedLifetime(container) {}+ }+ deinit { try? FileManager.default.removeItem(at: root) } }-
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swiftindex 6fffda7b..08a2ab8c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift@@ -71,12 +71,12 @@ struct MarkerContractTests { func appAcceptsTheCurrentMarkerVersion() async throws { let (_, cfg) = try config() try await makeReadyLibrary(cfg)- #expect(try markerContent(cfg) == "17",+ #expect(try markerContent(cfg) == "18", "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) == "17", "and the open leaves the marker as it found it")+ #expect(try markerContent(cfg) == "18", "and the open leaves the marker as it found it") } /// Req 4.4: the previous generation is *opened*, not refused — the stage@@ -92,7 +92,7 @@ struct MarkerContractTests { await repository.shutdown() #expect(result == .ready(.seededEmpty))- #expect(try markerContent(cfg) == "17",+ #expect(try markerContent(cfg) == "18", "the marker moves only after the converted store has validated") } @@ -138,7 +138,7 @@ struct MarkerContractTests { func extensionAcceptsTheCurrentVersion() async throws { let (_, cfg) = try config() try await makeReadyLibrary(cfg)- #expect(try markerContent(cfg) == "17")+ #expect(try markerContent(cfg) == "18") let (result, _) = try await LibraryRepository.openForExtension(cfg) #expect(result == .ready(.seededEmpty))@@ -207,9 +207,9 @@ struct MarkerContractTests { // Control: with a "17" marker the same store is reached, opened, and // converted. Without this the assertion above could hold because the // store was unopenable rather than because the marker was read first.- try writeMarker(cfg, "17\n")+ try writeMarker(cfg, "18\n") _ = try await LibraryRepository.openForExtension(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["17.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["18.0.0"], "the same store converts once the marker check passes") }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swiftindex dc2a1995..3a2b608f 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift@@ -54,7 +54,7 @@ struct MarkerGenerationSeventeenTests { func seventeenIsReady() throws { let root = try Root() try root.seedV16Library()- try root.writeMarker("17\n")+ try root.writeMarker("18\n") #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready) withExtendedLifetime(root) {}@@ -101,9 +101,9 @@ struct MarkerGenerationSeventeenTests { } #expect(counts.works == 1) #expect(counts.entries == 3)- #expect(try root.markerText() == "17")+ #expect(try root.markerText() == "18") #expect(try V4RecordedStoreFixture.recordedModelVersions(at: root.configuration.storeURL)- == ["17.0.0"], "the store the arm opened is recorded at the version it converted to")+ == ["18.0.0"], "the store the arm opened is recorded at the version it converted to") let facts = try await repository.withLockedContext( mode: .shared, operation: "reading the converted library"@@ -144,7 +144,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("expected a ready library, got \(result)") return }- #expect(try root.markerText() == "17")+ #expect(try root.markerText() == "18") withExtendedLifetime(root) {} } @@ -180,7 +180,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("expected the retry to reach a ready library, got \(result)") return }- #expect(try root.markerText() == "17")+ #expect(try root.markerText() == "18") withExtendedLifetime(root) {} } @@ -217,7 +217,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("a diagnosable library must still open, got \(result)") return }- #expect(try root.markerText() == "17")+ #expect(try root.markerText() == "18") #expect(quarantined != nil, "the broken title rule quarantines its hostname, as on V15") withExtendedLifetime(root) {} }@@ -299,7 +299,7 @@ struct MarkerGenerationSeventeenTests { try root.seedV16Library() let (_, repository) = try await LibraryRepository.openForApp(root.configuration) await repository.shutdown()- #expect(try root.markerText() == "17")+ #expect(try root.markerText() == "18") 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 85b239c4..4d64372b 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swiftindex 525fc710..dc3df47a 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 `BackupV16Exporter`+ /// Exports and decode-validates, which is exactly what `BackupV17Exporter` /// 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 backupV16Snapshot()- let encoded = try BackupV16Codec.encode(+ let payload = try await backupV17Snapshot()+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))- _ = try BackupV16Codec.decode(encoded)+ metadata: BackupV17Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))+ _ = try BackupV17Codec.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 da0bc9ea..1ab3e506 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swiftindex 782b7d9e..742a296f 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 == "17")+ #expect(call.markerVersion == "18") #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 == "17")+ #expect(log.calls.first?.markerVersion == "18") #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 == "17")+ #expect(log.calls.first?.markerVersion == "18") #expect(await repository.mirroring.isMirroring) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swiftindex bfbff374..ab7376ec 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift@@ -219,7 +219,7 @@ struct ModelContractTests { func emptyLibraryPhasesCoverTheSchema() { let phased = Set( LibraryRepository.emptyLibraryPhases.flatMap { $0.entities.map(\.name) })- let declared = Set(AsterismSchemaV17.models.map { String(describing: $0) })+ let declared = Set(AsterismSchemaV18.models.map { String(describing: $0) }) #expect( phased == declared, """@@ -296,7 +296,7 @@ struct ModelContractTests { work.releaseDays = [.sunday, .monday, .sunday] #expect(work.releaseDaysRaw == ["monday", "sunday"], "the setter writes canonical order") - let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.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 }@@ -350,7 +350,7 @@ struct ModelContractTests { #expect(work.thumbnailShape == nil) #expect(work.thumbnailIdentity == nil) - let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.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@@ -442,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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.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")@@ -519,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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.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")@@ -560,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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.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")@@ -693,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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) var propertiesByEntity: [String: Set<String>] = [:] for entity in schema.entities { propertiesByEntity[entity.name, default: []]@@ -774,6 +774,7 @@ struct ModelContractTests { #expect( declaringSnapshots.sorted() == [ "AsterismSchemaV16.swift", "AsterismSchemaV17.swift",+ "AsterismSchemaV18.swift", ], """ the package declares versioned schemas in \(declaringSnapshots.sorted()); \@@ -1090,7 +1091,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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swiftindex 9fc0cedc..cc7f5330 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.- "AsterismSchemaV16.swift",+ "AsterismSchemaV16.swift", "AsterismSchemaV17Models.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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swiftindex 1dc11214..2915621c 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 = BackupV16URLRule(+ let rule = BackupV17URLRule( 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: BackupV16ExportError.self) {+ #expect(throws: BackupV17ExportError.self) { try LibraryRepository.requireCitationsResolve( entries: [entry], memberships: [], titlePatterns: [], urlRules: [rule]) } // Same rule, taught for the Entry's own site: legal.- let sameSite = BackupV16URLRule(+ let sameSite = BackupV17URLRule( 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 = BackupV16TitlePattern(+ let pattern = BackupV17TitlePattern( 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: BackupV16ExportError.self) {+ #expect(throws: BackupV17ExportError.self) { try LibraryRepository.requireCitationsResolve( entries: [entry], memberships: [], titlePatterns: [pattern], urlRules: []) }@@ -303,9 +303,9 @@ struct MultiSiteReviewFixTests { private static func wireEntry( hostname: String, citations: EntryCitations- ) -> BackupV16Entry {+ ) -> BackupV17Entry { let url = "https://\(hostname)/one"- return BackupV16Entry(+ return BackupV17Entry( 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/NSItemProviderTextBridgeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NSItemProviderTextBridgeTests.swiftindex 0ed61377..fd8024da 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/NSItemProviderTextBridgeTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NSItemProviderTextBridgeTests.swift@@ -22,6 +22,8 @@ struct NSItemProviderTextBridgeTests { ) let item = ConcreteProviderExtensionItem(providers: [provider]) + #expect(provider.hasText)+ let payload = try await SharePayloadExtractor().extract(from: [item]) #expect(payload.providerURL == "https://tapas.io/series/the-regressor-creates-everything/ep11")@@ -36,6 +38,8 @@ struct NSItemProviderTextBridgeTests { ) let item = ConcreteProviderExtensionItem(providers: [provider]) + #expect(provider.hasText)+ let payload = try await SharePayloadExtractor().extract(from: [item]) #expect(payload.providerURL == "https://example.com/data-backed")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistoryTests.swiftnew file mode 100644index 00000000..5f39da57--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistoryTests.swift@@ -0,0 +1,158 @@+import Foundation+import Testing++@testable import AsterismCore++@Suite("No episode history")+struct NoEpisodeHistoryTests {+ private static let work = UUID(uuidString: "00000000-0000-4000-8000-000000000001")!+ private static let otherWork = UUID(uuidString: "00000000-0000-4000-8000-000000000002")!+ private static let day = "2026-09-29"++ private static func mark(_ n: Int, observing keys: [String] = [], workID: UUID = work,+ day: String = day) throws -> NoEpisodeHistory.Action {+ try .init(workID: workID, key: "mark/\(id(n))", day: day,+ kind: .mark, observedClearKeys: keys)+ }++ private static func clear(_ n: Int, workID: UUID = work,+ day: String = day) throws -> NoEpisodeHistory.Action {+ try .init(workID: workID, key: "clear/\(id(n))", day: day,+ kind: .clear, observedClearKeys: [])+ }++ private static func id(_ n: Int) -> String {+ String(format: "%08X-0000-4000-8000-000000000000", n)+ }++ @Test func clearDominanceAndDeliberateRemark() throws {+ let m1 = try Self.mark(1)+ let c1 = try Self.clear(1)+ let m2 = try Self.mark(2, observing: [c1.key])+ #expect(try NoEpisodeHistory([m1]).isMarked(workID: Self.work, day: Self.day))+ #expect(try !NoEpisodeHistory([m1, c1]).isMarked(workID: Self.work, day: Self.day))+ #expect(try NoEpisodeHistory([m1, c1, m2]).isMarked(workID: Self.work, day: Self.day))+ #expect(try NoEpisodeHistory([m2]).isMarked(workID: Self.work, day: Self.day))+ }++ @Test func scopesAndDuplicates() throws {+ let mark = try Self.mark(1)+ let clearOtherWork = try Self.clear(1, workID: Self.otherWork)+ let clearOtherDay = try Self.clear(2, day: "2026-09-30")+ let history = try NoEpisodeHistory([mark, mark, clearOtherWork, clearOtherDay])+ #expect(history.actions.count == 3)+ #expect(try history.isMarked(workID: Self.work, day: Self.day))+ #expect(try !history.isMarked(workID: Self.otherWork, day: Self.day))+ }++ @Test func unionLawsUnderAllSmallPartitions() throws {+ let c1 = try Self.clear(1)+ let c2 = try Self.clear(2)+ let actions = [try Self.mark(1), c1, try Self.mark(2, observing: [c1.key]), c2,+ try Self.mark(3, observing: [c1.key, c2.key])]+ for bits in 0..<(1 << actions.count) {+ let a = try NoEpisodeHistory(actions.enumerated().compactMap { bits & (1 << $0.offset) == 0 ? nil : $0.element })+ let b = try NoEpisodeHistory(actions.enumerated().compactMap { bits & (1 << $0.offset) == 0 ? $0.element : nil })+ #expect(try a.union(b) == b.union(a))+ #expect(try a.union(a) == a)+ #expect(try a.union(b).union(a) == a.union(b.union(a)))+ let all = try a.union(b)+ #expect(try all.isMarked(workID: Self.work, day: Self.day))+ }+ }++ @Test func seededReplicaDeliveryAgreesWithReferenceModel() throws {+ var seed: UInt64 = 0x2374_2026+ func random(_ limit: Int) -> Int {+ seed = seed &* 6364136223846793005 &+ 1442695040888963407+ return Int((seed >> 32) % UInt64(limit))+ }+ for replicaCount in 2...3 {+ for trial in 0..<40 {+ var replicas = Array(repeating: [NoEpisodeHistory.Action](), count: replicaCount)+ for step in 0..<12 {+ let replica = random(replicaCount)+ if random(3) == 0 {+ replicas[replica].append(try Self.clear(1000 + trial * 12 + step))+ } else {+ let known = replicas[replica].filter { $0.kind == .clear }.map(\.key)+ replicas[replica].append(try Self.mark(1000 + trial * 12 + step,+ observing: known))+ }+ if random(4) == 0 {+ let source = random(replicaCount)+ let copied = replicas[source]+ replicas[replica].append(contentsOf: copied)+ }+ }+ let all = replicas.flatMap { $0 }+ let clearKeys = Set(all.filter { $0.kind == .clear }.map(\.key))+ .union(all.flatMap(\.observedClearKeys))+ let expected = all.contains {+ $0.kind == .mark && clearKeys.isSubset(of: Set($0.observedClearKeys))+ }+ var result = try NoEpisodeHistory()+ var generator = SeededGenerator(seed: seed)+ for index in replicas.indices.shuffled(using: &generator) {+ result = try result.union(NoEpisodeHistory(replicas[index]))+ }+ #expect(try result.isMarked(workID: Self.work, day: Self.day) == expected)+ #expect(try result.union(NoEpisodeHistory(all)) == result)+ }+ }+ }++ @Test func canonicalWireAndInvalidPayloads() throws {+ let clear = try Self.clear(1)+ let action = try Self.mark(2, observing: [clear.key, clear.key])+ #expect(action.observedClearKeys == [clear.key])+ let bytes = try action.canonicalData()+ #expect(try NoEpisodeHistory.Action.decode(bytes, workID: Self.work) == action)+ let string = String(decoding: bytes, as: UTF8.self)+ #expect(string.contains("\"version\":1"))+ #expect(throws: (any Error).self) {+ try NoEpisodeHistory.Action.decode(Data(string.replacingOccurrences(of: "\"version\":1", with: "\"version\":2").utf8), workID: Self.work)+ }+ #expect(throws: (any Error).self) { try Self.mark(3, observing: ["mark/\(Self.id(3))"]) }+ #expect(throws: (any Error).self) { try Self.mark(3, day: "2026-02-30") }+ #expect(throws: (any Error).self) { try Self.mark(3, day: "2026-2-3") }+ #expect(throws: (any Error).self) { try Self.mark(3, observing: ["clear/not-a-uuid"]) }+ #expect(throws: (any Error).self) { try Self.mark(3, observing: ["note/garbage"]) }+ #expect(throws: (any Error).self) {+ try Self.mark(3, observing: [+ "note/\(Self.id(4))/not-a-work-uuid/0/\(Self.day)"+ ])+ }+ #expect(throws: (any Error).self) {+ try Self.mark(3, observing: [+ "note/\(Self.id(4))/\(Self.work.uuidString)/0/2026-09-30"+ ])+ }+ #expect(try Self.mark(3, observing: [+ "note/\(Self.id(4))/\(Self.otherWork.uuidString)/0/\(Self.day)"+ ]).observedClearKeys.count == 1)+ #expect(throws: (any Error).self) { try NoEpisodeHistory([try Self.mark(1), Self.mark(1, day: "2026-09-30")]) }+ }++ @Test func civilDaySurvivesDisplayCalendarAndDST() throws {+ var zone = Calendar(identifier: .gregorian)+ zone.timeZone = TimeZone(identifier: "Australia/Melbourne")!+ let first = CivilDay(DateComponents(calendar: zone, year: 2026, month: 10, day: 3, hour: 12).date!, calendar: zone)+ let second = first.adding(days: 1, calendar: zone)+ var japanese = Calendar(identifier: .japanese)+ japanese.timeZone = zone.timeZone+ #expect(first.description == "2026-10-03")+ #expect(second.description == "2026-10-04")+ #expect(CivilDay(second.date(in: japanese), calendar: japanese) == second)+ #expect(try NoEpisodeHistory([Self.mark(1, day: second.description)]).activeDays(for: Self.work).contains(second))+ }+}++private struct SeededGenerator: RandomNumberGenerator {+ var seed: UInt64++ mutating func next() -> UInt64 {+ seed = seed &* 6364136223846793005 &+ 1442695040888963407+ return seed+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistoryTokenTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistoryTokenTests.swiftnew file mode 100644index 00000000..6044e814--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistoryTokenTests.swift@@ -0,0 +1,96 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("No-episode store change token", .serialized)+struct NoEpisodeHistoryTokenTests {+ private var calendar: Calendar {+ var value = Calendar(identifier: .gregorian)+ value.timeZone = TimeZone(secondsFromGMT: 0)!+ return value+ }++ @Test("Same-count Entry and action mutations advance the latest store token")+ func sameCountChanges() throws {+ let fixture = try WriteFixture()+ let workID = UUID()+ let entryID = UUID()+ try fixture.seed { store in+ store.insertSite(hostname: "token.example")+ let work = store.insertWork(id: workID, hostname: "token.example",+ title: "A Serial", offset: 0)+ let entry = store.insertEntry(id: entryID, hostname: "token.example",+ title: "Chapter", offset: 0)+ entry.work = work+ }+ let container = try LibraryRepository.openContainer(at: fixture.configuration.storeURL)+ let context = ModelContext(container)+ func latest() throws -> DefaultHistoryToken? {+ var descriptor = HistoryDescriptor<DefaultHistoryTransaction>()+ descriptor.sortBy = [.init(\.transactionIdentifier, order: .reverse)]+ descriptor.fetchLimit = 1+ return try context.fetchHistory(descriptor).first?.token+ }+ let original = try #require(try latest())+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == entryID })+ entry.note = "changed without changing row count"+ try context.save()+ let edited = try #require(try latest())+ #expect(edited != original)+ let action = try NoEpisodeHistory.Action(+ workID: workID, key: "mark/\(UUID().uuidString)", day: "2026-09-29",+ kind: .mark, observedClearKeys: [])+ _ = try NoEpisodeWriter.insertMissing([action], context: context)+ try context.save()+ #expect(try latest() != edited)+ withExtendedLifetime(container) {}+ }++ @Test("Preparation rechecks same-count external note and action changes")+ func preparationInvalidatesOnExternalSave() async throws {+ let fixture = try WriteFixture()+ let workID = UUID()+ let entryID = UUID()+ try fixture.seed { store in+ store.insertSite(hostname: "token.example")+ let work = store.insertWork(id: workID, hostname: "token.example",+ title: "A Serial", offset: 0)+ let entry = store.insertEntry(id: entryID, hostname: "token.example",+ title: "Chapter", offset: 0)+ entry.work = work+ }+ let repository = try await fixture.openForApp()+ try await repository.prepareNoEpisodeNotes(calendar: calendar)+ try await repository.prepareNoEpisodeNotes(calendar: calendar)+ let context = try fixture.readContext()+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == entryID })+ let originalDay = CivilDay(entry.lastSharedAt, calendar: calendar)+ let stableKey = NoEpisodeWriter.NoteFact(+ entryID: entryID, workID: workID, sharedAt: entry.lastSharedAt,+ calendar: calendar).stableKey+ let initial = try NoEpisodeIndex(context: context).history(for: workID)+ #expect(initial.clearKeys(workID: workID, day: originalDay.description).contains(stableKey))++ let mark = try NoEpisodeHistory.Action(+ workID: workID, key: "mark/\(UUID().uuidString)",+ day: originalDay.description, kind: .mark,+ observedClearKeys: [stableKey])+ _ = try NoEpisodeWriter.insertMissing([mark], context: context)+ try context.save()+ try await repository.prepareNoEpisodeNotes(calendar: calendar)+ #expect(try !NoEpisodeIndex(context: context).history(for: workID)+ .isMarked(workID: workID, day: originalDay.description))++ let later = calendar.date(byAdding: .day, value: 1, to: entry.lastSharedAt)!+ entry.lastSharedAt = later+ try context.save()+ try await repository.prepareNoEpisodeNotes(calendar: calendar)+ let laterKey = NoEpisodeWriter.NoteFact(+ entryID: entryID, workID: workID, sharedAt: later,+ calendar: calendar).stableKey+ let laterDay = CivilDay(later, calendar: calendar)+ #expect(try NoEpisodeIndex(context: context).history(for: workID)+ .clearKeys(workID: workID, day: laterDay.description).contains(laterKey))+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swiftnew file mode 100644index 00000000..ed71e10f--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swift@@ -0,0 +1,438 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("No-episode repository commands and local notes", .serialized)+struct NoEpisodeRepositoryTests {+ private var calendar: Calendar {+ var value = Calendar(identifier: .gregorian)+ value.timeZone = TimeZone(secondsFromGMT: 0)!+ return value+ }++ private func fixture(note: Bool = false, torn: Bool = false) throws -> (WriteFixture, UUID, UUID?) {+ let fixture = try WriteFixture()+ let workID = UUID()+ let entryID = note ? UUID() : nil+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ try fixture.seed { store in+ store.insertSite(hostname: "dup.example")+ for copy in 0..<(torn ? 2 : 1) {+ let work = store.insertWork(id: workID, hostname: "dup.example",+ title: copy == 0 ? "A Serial" : "Other", offset: 0)+ if torn { work.genericNotes = copy == 0 ? "first" : "second" }+ work.releaseDays = [day.weekday(calendar: calendar)]+ work.workStatus = .ongoing+ work.readingStatus = .reading+ if let entryID, copy == 0 {+ let entry = store.insertEntry(id: entryID, hostname: "dup.example",+ title: "Chapter", offset: 0)+ entry.work = work+ }+ }+ }+ return (fixture, workID, entryID)+ }++ private func history(_ fixture: WriteFixture, workID: UUID) throws -> NoEpisodeHistory {+ try NoEpisodeIndex(context: fixture.readContext()).history(for: workID)+ }++ @Test("Selected past, current and future dates are independent; retries leave metadata alone")+ func selectedDates() async throws {+ let (fixture, workID, _) = try fixture()+ let repository = try await fixture.openForApp()+ let today = CivilDay(WriteFixture.epoch, calendar: calendar)+ let before = try #require(fixture.workRows(id: workID).first)+ let modifiedAt = before.modifiedAt+ let progress = before.catchUpRecord+ for offset in [-7, 0, 7] {+ let date = calendar.date(byAdding: .day, value: offset, to: WriteFixture.epoch)!+ let day = CivilDay(date, calendar: calendar)+ #expect(try await repository.markNoEpisode(workID: workID, day: day, calendar: calendar) == .committed)+ #expect(try await repository.markNoEpisode(workID: workID, day: day, calendar: calendar) == .committed)+ }+ #expect(try history(fixture, workID: workID).activeDays(for: workID).count == 3)+ #expect(try await repository.undoNoEpisode(workID: workID, day: today) == .committed)+ #expect(try await repository.undoNoEpisode(workID: workID, day: today) == .committed)+ #expect(try history(fixture, workID: workID).activeDays(for: workID).count == 2)+ let after = try #require(fixture.workRows(id: workID).first)+ #expect(after.modifiedAt == modifiedAt)+ #expect(after.catchUpRecord == progress)+ #expect(try fixture.allEntryRows().isEmpty)+ }++ @Test("A matching note refuses marking, and a torn work refuses both commands")+ func refusals() async throws {+ let (noted, workID, _) = try fixture(note: true)+ let repository = try await noted.openForApp()+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ #expect(try await repository.markNoEpisode(workID: workID, day: day, calendar: calendar) != .committed)+ #expect(try history(noted, workID: workID).actions.isEmpty)++ let (torn, tornID, _) = try fixture(torn: true)+ let tornRepository = try await torn.openForApp()+ #expect(try await tornRepository.markNoEpisode(workID: tornID, day: day, calendar: calendar) != .committed)+ #expect(try await tornRepository.undoNoEpisode(workID: tornID, day: day) != .committed)+ #expect(try history(torn, workID: tornID).actions.isEmpty)+ }++ @Test("A note arriving and then leaving permanently clears its date")+ func noteLifetime() async throws {+ let (fixture, workID, seededEntryID) = try fixture(note: true)+ let entryID = try #require(seededEntryID)+ let repository = try await fixture.openForApp()+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ // A note is present at the outset. Remove it, mark, then attach it again.+ let basis = EntryAssignmentBasis(workID: workID, intentionallyUnattached: false,+ hostname: "dup.example", conservativeIdentityKey: fixture.identityKey)+ #expect(try await repository.moveEntry(entryID, basis: basis, to: .unattached) == .committed)+ #expect(try await repository.markNoEpisode(workID: workID, day: day, calendar: calendar) == .committed)+ let unattached = EntryAssignmentBasis(workID: nil, intentionallyUnattached: true,+ hostname: "dup.example", conservativeIdentityKey: fixture.identityKey)+ #expect(try await repository.moveEntry(entryID, basis: unattached, to: .existing(workID)) == .committed)+ #expect(try await repository.deleteEntry(id: entryID, basis: EntryEditBasis(+ note: "", rating: nil, hostname: "dup.example", conservativeIdentityKey: fixture.identityKey),+ disclosedVariants: nil) == .committed)+ #expect(try history(fixture, workID: workID).activeDays(for: workID).isEmpty)+ }++ @Test("Changed schedule or status refuses a stale mark")+ func changedEligibility() async throws {+ let (fixture, workID, _) = try fixture()+ let repository = try await fixture.openForApp()+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ let context = try fixture.readContext()+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == workID })+ work.releaseDays = []+ try context.save()+ #expect(try await repository.markNoEpisode(workID: workID, day: day, calendar: calendar) != .committed)+ work.releaseDays = [day.weekday(calendar: calendar)]+ work.readingStatus = .finished+ try context.save()+ #expect(try await repository.markNoEpisode(workID: workID, day: day, calendar: calendar) != .committed)+ #expect(try history(fixture, workID: workID).actions.isEmpty)+ }++ @Test("Schedule and status edits retain action history")+ func metadataEditsRetainHistory() async throws {+ let (fixture, workID, _) = try fixture()+ let repository = try await fixture.openForApp()+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ #expect(try await repository.markNoEpisode(workID: workID, day: day,+ calendar: calendar) == .committed)+ let marked = try history(fixture, workID: workID)+ let context = try fixture.readContext()+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == workID })+ work.releaseDays = []+ work.readingStatus = .finished+ try context.save()+ #expect(try history(fixture, workID: workID) == marked)+ }++ @Test("A failed mark save leaves no action")+ func failedSave() async throws {+ let (fixture, workID, _) = try fixture()+ let save = NoEpisodeFailingSave()+ let (_, repository) = try await LibraryRepository.openForApp(+ fixture.configuration, capabilities: .multiSite,+ clock: FixedRepositoryClock(WriteFixture.epoch), saveStrategy: save,+ noteCalendar: { Calendar(identifier: .gregorian) })+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ await #expect(throws: LibraryRepositoryError.self) {+ try await repository.markNoEpisode(workID: workID, day: day, calendar: calendar)+ }+ #expect(try history(fixture, workID: workID).actions.isEmpty)+ }++ @Test("Editing note text keeps stable evidence without a fresh occurrence")+ func ordinaryTextEdit() async throws {+ let (fixture, workID, seededEntryID) = try fixture(note: true)+ let entryID = try #require(seededEntryID)+ let repository = try await fixture.openForApp()+ let basis = EntryEditBasis(note: "", rating: nil, hostname: "dup.example",+ conservativeIdentityKey: fixture.identityKey)+ #expect(try await repository.updateEntry(id: entryID, basis: basis,+ note: "first", rating: nil) == .committed)+ let first = try history(fixture, workID: workID)+ #expect(first.actions.count == 1)+ let editedBasis = EntryEditBasis(note: "first", rating: nil, hostname: "dup.example",+ conservativeIdentityKey: fixture.identityKey)+ #expect(try await repository.updateEntry(id: entryID, basis: editedBasis,+ note: "second", rating: nil) == .committed)+ #expect(try history(fixture, workID: workID) == first)+ }++ @Test("A drained re-share moves note evidence to its new civil day")+ func drainedReShareClearsSelectedDay() async throws {+ let (fixture, workID, seededEntryID) = try fixture(note: true)+ let entryID = try #require(seededEntryID)+ let repository = try await fixture.openForApp()+ let later = calendar.date(byAdding: .day, value: 7, to: WriteFixture.epoch)!+ let selected = CivilDay(later, calendar: calendar)+ #expect(try await repository.markNoEpisode(workID: workID, day: selected,+ calendar: calendar) == .committed)+ let target = DrainedReShareTarget(entryID: entryID, hostname: "dup.example",+ identityKey: fixture.identityKey)+ #expect(try await repository.recordDrainedReShare(target: target,+ sharedAt: later) == .committed)+ #expect(try history(fixture, workID: workID).activeDays(for: workID).isEmpty)+ let entry = try await repository.entry(id: entryID)+ #expect(try await repository.deleteEntry(+ id: entryID, basis: EntryEditBasis(entry: entry), disclosedVariants: nil) == .committed)+ #expect(try history(fixture, workID: workID).activeDays(for: workID).isEmpty)+ }++ @Test("An edited re-share clears the date it arrives on")+ func editedReShareClearsSelectedDay() async throws {+ let (fixture, workID, _) = try fixture(note: true)+ let later = calendar.date(byAdding: .day, value: 7, to: WriteFixture.epoch)!+ let (_, repository) = try await LibraryRepository.openForApp(+ fixture.configuration, capabilities: .multiSite,+ clock: FixedRepositoryClock(later), noteCalendar: { Calendar.current })+ let selected = CivilDay(later, calendar: calendar)+ #expect(try await repository.markNoEpisode(workID: workID, day: selected,+ calendar: calendar) == .committed)+ let lookup = try await repository.captureLookup(rawURL: fixture.identityKey)+ guard case .edit(let basis) = lookup else {+ Issue.record("expected an editable re-share basis")+ return+ }+ #expect(try await repository.commitReShareUpdate(+ basis: basis, note: "updated", rating: nil) == .committed)+ #expect(try history(fixture, workID: workID).activeDays(for: workID).isEmpty)+ }++ @Test("Deletion retains clear evidence against a later offline mark")+ func deletedBeforeOfflineMarkArrives() async throws {+ let (fixture, workID, seededEntryID) = try fixture(note: true)+ let entryID = try #require(seededEntryID)+ let repository = try await fixture.openForApp()+ let basis = EntryEditBasis(note: "", rating: nil, hostname: "dup.example",+ conservativeIdentityKey: fixture.identityKey)+ #expect(try await repository.deleteEntry(id: entryID, basis: basis,+ disclosedVariants: nil) == .committed)+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ let context = try fixture.readContext()+ let offlineMark = try NoEpisodeHistory.Action(+ workID: workID, key: "mark/\(UUID().uuidString)", day: day.description,+ kind: .mark, observedClearKeys: [])+ try NoEpisodeWriter.insertMissing([offlineMark], context: context)+ try context.save()+ #expect(try history(fixture, workID: workID).activeDays(for: workID).isEmpty)+ }++ @Test("Both sync tiers clear a mark overlapping an already acknowledged note")+ func reconcileOverlap() async throws {+ for tier in [ReconcilePassTier.arrival, .full] {+ let (fixture, workID, seededEntryID) = try fixture(note: true)+ let entryID = try #require(seededEntryID)+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ let stable = NoEpisodeWriter.NoteFact(+ entryID: entryID, workID: workID,+ sharedAt: WriteFixture.epoch, calendar: calendar).stableKey+ try fixture.seedAdditional { store in+ try NoEpisodeWriter.insertMissing([+ .init(workID: workID, key: stable, day: day.description,+ kind: .clear, observedClearKeys: []),+ .init(workID: workID, key: "mark/\(UUID().uuidString)",+ day: day.description, kind: .mark, observedClearKeys: [stable]),+ ], context: store.context)+ }+ let repository = try await fixture.openForApp()+ #expect(try history(fixture, workID: workID).isMarked(+ workID: workID, day: day.description))+ let first = try await repository.reconcileAfterSync(tier: tier)+ #expect(!first.isEmpty)+ let cleared = try history(fixture, workID: workID)+ #expect(try !cleared.isMarked(workID: workID, day: day.description))+ let second = try await repository.reconcileAfterSync(tier: tier)+ #expect(second.isEmpty)+ #expect(try history(fixture, workID: workID) == cleared)+ }+ }++ @Test("Deleting a work removes its complete action history")+ func deletingWorkRemovesActions() async throws {+ let (fixture, workID, _) = try fixture()+ let repository = try await fixture.openForApp()+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ #expect(try await repository.markNoEpisode(workID: workID, day: day,+ calendar: calendar) == .committed)+ let contract = try await repository.projectWorkDeletion(workID: workID)+ #expect(try await repository.commitWorkDeletion(+ contract, disposition: .deleteEntries, disclosedVariants: nil) == .committed)+ #expect(try history(fixture, workID: workID).actions.isEmpty)+ }++ @Test("Merging works moves action keys and acknowledgements to the survivor")+ func mergingWorksMovesActions() async throws {+ let (fixture, sourceID, _) = try fixture()+ let targetID = UUID()+ try fixture.seedAdditional { store in+ _ = store.insertWork(id: targetID, hostname: "dup.example",+ title: "Target Serial", offset: 1)+ }+ let repository = try await fixture.openForApp()+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ #expect(try await repository.markNoEpisode(workID: sourceID, day: day,+ calendar: calendar) == .committed)+ let original = try history(fixture, workID: sourceID)+ let contract = try await repository.projectMerge(+ sourceWorkID: sourceID, targetWorkID: targetID)+ #expect(try await repository.commitMerge(contract) == .committed(targetID: targetID))+ #expect(try history(fixture, workID: sourceID).actions.isEmpty)+ let moved = try history(fixture, workID: targetID)+ #expect(moved.actions.map(\.key) == original.actions.map(\.key))+ #expect(moved.actions.map(\.observedClearKeys) == original.actions.map(\.observedClearKeys))+ }++ @Test("Restoring the same note again clears a mark that acknowledged its stable key")+ func repeatedBackupRestoration() async throws {+ let fixture = try await M5Fixture()+ let payload = BackupV17Fixtures.composedPayload()+ let plan = BackupV17Fixtures.plan(payload)+ let entryRecord = try #require(payload.entries.first)+ let workID = BackupV17Fixtures.composedWorkID+ let calendar = Calendar.current+ let day = CivilDay(entryRecord.lastSharedAt, calendar: calendar)+ _ = try await fixture.repository.confirmImport(plan: plan)++ let entry = try await fixture.repository.entry(id: entryRecord.id)+ #expect(try await fixture.repository.deleteEntry(+ id: entry.id, basis: EntryEditBasis(entry: entry), disclosedVariants: nil) == .committed)++ let configuration = LibraryConfiguration(rootDirectory: fixture.directory)+ let container = try LibraryRepository.openContainer(at: configuration.storeURL)+ let context = ModelContext(container)+ let stable = NoEpisodeWriter.NoteFact(+ entryID: entry.id, workID: workID,+ sharedAt: entryRecord.lastSharedAt, calendar: calendar).stableKey+ let knownClears = try NoEpisodeIndex(context: context).history(for: workID)+ .clearKeys(workID: workID, day: day.description)+ #expect(knownClears.contains(stable))+ try NoEpisodeWriter.insertMissing([+ .init(workID: workID, key: "mark/\(UUID().uuidString)",+ day: day.description, kind: .mark,+ observedClearKeys: knownClears.sorted()),+ ], context: context)+ try context.save()+ #expect(try NoEpisodeIndex(context: ModelContext(container)).history(for: workID)+ .isMarked(workID: workID, day: day.description))++ _ = try await fixture.repository.confirmImport(plan: plan)+ let restored = try NoEpisodeIndex(context: ModelContext(container)).history(for: workID)+ #expect(try !restored.isMarked(workID: workID, day: day.description))+ let restoredEntry = try await fixture.repository.entry(id: entryRecord.id)+ #expect(try await fixture.repository.deleteEntry(+ id: restoredEntry.id, basis: EntryEditBasis(entry: restoredEntry),+ disclosedVariants: nil) == .committed)+ #expect(try !NoEpisodeIndex(context: ModelContext(container)).history(for: workID)+ .isMarked(workID: workID, day: day.description))+ }++ @Test("Today, Works, detail and Set latest read the same active date")+ func readParity() async throws {+ let (fixture, workID, _) = try fixture()+ let repository = try await fixture.openForApp()+ let day = CivilDay(WriteFixture.epoch, calendar: calendar)+ #expect(try await repository.markNoEpisode(+ workID: workID, day: day, calendar: calendar) == .committed)+ let single = try await repository.work(id: workID)+ let list = try await repository.works()+ let detail = try await repository.workDetail(id: workID)+ let today = try await repository.todayPresentation(calendar: calendar)+ let sheet = try await repository.catchUpSheetState(+ workID: workID, day: day, calendar: calendar)+ #expect(try single.noEpisodeHistory.activeDays(for: workID) == [day])+ #expect(try list.works.first?.noEpisodeHistory.activeDays(for: workID) == [day])+ #expect(try detail.work.noEpisodeHistory.activeDays(for: workID) == [day])+ #expect(try sheet.work.noEpisodeHistory.activeDays(for: workID) == [day])+ #expect(today.schedule.works.first?.noEpisodeDays == [day])+ }++ @Test("Split Entry assignments clear each work's own noted date through deletion")+ func splitAssignmentsKeepPerWorkClearDates() async throws {+ let fixture = try WriteFixture()+ let entryID = UUID()+ let newerWorkID = UUID()+ let olderWorkID = UUID()+ let olderAt = calendar.date(byAdding: .day, value: -7, to: WriteFixture.epoch)!+ let newerDay = CivilDay(WriteFixture.epoch, calendar: calendar)+ let olderDay = CivilDay(olderAt, calendar: calendar)+ try fixture.seed { store in+ store.insertSite(hostname: "dup.example")+ let newerWork = store.insertWork(id: newerWorkID, hostname: "dup.example",+ title: "Newer", offset: 0)+ let olderWork = store.insertWork(id: olderWorkID, hostname: "dup.example",+ title: "Older", offset: 0)+ newerWork.releaseDays = [newerDay.weekday(calendar: calendar)]+ olderWork.releaseDays = [olderDay.weekday(calendar: calendar)]+ store.insertEntry(id: entryID, hostname: "dup.example", title: "Chapter", offset: 0)+ .work = newerWork+ store.insertEntry(id: entryID, hostname: "dup.example", title: "Chapter",+ offset: -7 * 86_400).work = olderWork+ }+ let repository = try await fixture.openForApp()+ let schedule = try await repository.todayPresentation(calendar: calendar).schedule+ #expect(schedule.works.first(where: { $0.id == newerWorkID })?.notedDays.map(\.day) == [newerDay])+ #expect(schedule.works.first(where: { $0.id == olderWorkID })?.notedDays.map(\.day) == [olderDay])++ // A peer's mark can arrive before this device reconciles its notes.+ let context = try fixture.readContext()+ _ = try NoEpisodeWriter.insertMissing([+ .init(workID: olderWorkID, key: "mark/\(UUID().uuidString)",+ day: olderDay.description, kind: .mark, observedClearKeys: [])+ ], context: context)+ try context.save()+ _ = try await repository.reconcileAfterSync(tier: .arrival)+ let olderHistory = try history(fixture, workID: olderWorkID)+ let newerHistory = try history(fixture, workID: newerWorkID)+ #expect(!olderHistory.isMarked(workID: olderWorkID, day: olderDay.description))+ #expect(olderHistory.clearKeys(workID: olderWorkID, day: olderDay.description)+ .contains { $0.hasPrefix("note/") })+ #expect(newerHistory.clearKeys(workID: newerWorkID, day: newerDay.description)+ .contains { $0.hasPrefix("note/") })++ let group = try LibraryRepository.fetchNormalisedEntryGroup(+ id: entryID, context: fixture.readContext())+ #expect(try await repository.deleteEntry(+ id: entryID, basis: fixture.entryBasis(id: entryID),+ disclosedVariants: group.variantIDs) == .committed)+ #expect(try fixture.entryRows(id: entryID).isEmpty)+ #expect(try !history(fixture, workID: olderWorkID)+ .isMarked(workID: olderWorkID, day: olderDay.description))+ }++ @Test("Mark eligibility uses a duplicate Entry's newest date for its work")+ func duplicateEntryMarkEligibilityMatchesToday() async throws {+ let fixture = try WriteFixture()+ let workID = UUID()+ let entryID = UUID()+ let olderAt = calendar.date(byAdding: .day, value: -7, to: WriteFixture.epoch)!+ let olderDay = CivilDay(olderAt, calendar: calendar)+ let newestDay = CivilDay(WriteFixture.epoch, calendar: calendar)+ try fixture.seed { store in+ store.insertSite(hostname: "dup.example")+ let work = store.insertWork(id: workID, hostname: "dup.example",+ title: "A Serial", offset: 0)+ work.releaseDays = [newestDay.weekday(calendar: calendar)]+ store.insertEntry(id: entryID, hostname: "dup.example", title: "Chapter",+ offset: -7 * 86_400).work = work+ store.insertEntry(id: entryID, hostname: "dup.example", title: "Chapter", offset: 0)+ .work = work+ }+ let repository = try await fixture.openForApp()+ let scheduled = try await repository.todayPresentation(calendar: calendar).schedule.works+ #expect(scheduled.first?.notedDays.map(\.day) == [newestDay])+ #expect(try await repository.markNoEpisode(+ workID: workID, day: olderDay, calendar: calendar) == .committed)+ #expect(try await repository.markNoEpisode(+ workID: workID, day: newestDay, calendar: calendar) != .committed)+ }+}++private struct NoEpisodeFailingSave: RepositorySaveStrategy {+ func save(_ context: ModelContext) throws { throw CocoaError(.fileWriteUnknown) }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swiftnew file mode 100644index 00000000..a3affda3--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift@@ -0,0 +1,165 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("No-episode V18 storage", .serialized)+struct NoEpisodeStorageTests {+ @Test("V18 adds one CloudKit-compatible action table")+ func schemaContract() throws {+ let frozen = Schema(versionedSchema: AsterismSchemaV17.self)+ let live = Schema(versionedSchema: AsterismSchemaV18.self)+ let frozenNames = Set(frozen.entities.map(\.name))+ let liveNames = Set(live.entities.map(\.name))+ #expect(liveNames.subtracting(frozenNames) == ["NoEpisodeAction"])+ #expect(frozenNames.subtracting(liveNames).isEmpty)+ let entity = try #require(live.entities.first { $0.name == "NoEpisodeAction" })+ #expect(entity.uniquenessConstraints.isEmpty)+ #expect(entity.relationships.isEmpty)+ let columns = Set(entity.properties.map(\.name))+ #expect(columns == ["workID", "key", "payloadData"])+ #expect(AsterismV18MigrationPlan.schemas.map { $0.versionIdentifier.major } == [16, 17, 18])+ #expect(AsterismV18MigrationPlan.stages.count == 2)+ }++ @Test("duplicate rows union, conflicts fail, and dangling actions survive restart")+ func indexAndRestart() throws {+ let url = FileManager.default.temporaryDirectory.appending(path: "NoEpisodeStorage-\(UUID())")+ defer { try? FileManager.default.removeItem(at: url) }+ let schema = Schema(versionedSchema: AsterismSchemaV18.self)+ let config = ModelConfiguration(schema: schema, url: url)+ let workID = UUID()+ let action = try NoEpisodeHistory.Action(workID: workID, key: "mark/\(UUID().uuidString)",+ day: "2026-09-29", kind: .mark,+ observedClearKeys: [])+ do {+ let container = try ModelContainer(for: schema, configurations: [config])+ let context = ModelContext(container)+ #expect(try NoEpisodeWriter.insertMissing([action, action], context: context))+ try context.save()+ #expect(try NoEpisodeIndex(context: context).history(for: workID).actions == [action])+ }+ let reopened = try ModelContainer(for: schema, configurations: [config])+ let context = ModelContext(reopened)+ #expect(try NoEpisodeIndex(context: context).history(for: workID).actions == [action])+ #expect(try !NoEpisodeWriter.insertMissing([action], context: context))+ context.insert(NoEpisodeAction(+ workID: workID, key: action.key, payloadData: try action.canonicalData()))+ try context.save()+ #expect(try NoEpisodeIndex(context: context).history(for: workID).actions == [action])+ let conflicting = try NoEpisodeHistory.Action(workID: workID, key: action.key,+ day: "2026-09-30", kind: .mark,+ observedClearKeys: [])+ #expect(throws: NoEpisodeHistory.HistoryError.self) {+ try NoEpisodeWriter.insertMissing([conflicting], context: context)+ }+ context.insert(NoEpisodeAction(+ workID: workID, key: conflicting.key,+ payloadData: try conflicting.canonicalData()))+ #expect(throws: NoEpisodeHistory.HistoryError.self) {+ try NoEpisodeIndex(context: context).history(for: workID)+ }+ context.rollback()+ context.insert(NoEpisodeAction(+ workID: workID, key: "mark/\(UUID().uuidString)",+ payloadData: Data("not an action".utf8)))+ #expect(throws: Error.self) { try NoEpisodeIndex(context: context).history(for: workID) }+ }++ @Test("an unrelated damaged action does not break a targeted history read")+ func malformedActionIsScopedToItsWork() throws {+ let schema = Schema(versionedSchema: AsterismSchemaV18.self)+ let container = try ModelContainer(+ for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)])+ let context = ModelContext(container)+ let healthyWorkID = UUID()+ let damagedWorkID = UUID()+ let mark = try NoEpisodeHistory.Action(+ workID: healthyWorkID, key: "mark/\(UUID().uuidString)",+ day: "2026-09-29", kind: .mark, observedClearKeys: [])+ context.insert(NoEpisodeAction(+ workID: healthyWorkID, key: mark.key, payloadData: try mark.canonicalData()))+ context.insert(NoEpisodeAction(+ workID: damagedWorkID, key: "mark/\(UUID().uuidString)",+ payloadData: Data("not an action".utf8)))++ let index = try NoEpisodeIndex(context: context)+ #expect(try index.history(for: healthyWorkID).actions == [mark])+ #expect(throws: Error.self) { try index.history(for: damagedWorkID) }+ #expect(throws: Error.self) { try index.allActions }+ }++ @Test("17/18 archive requires, checksums, and validates full action history")+ func archiveContract() throws {+ let workID = UUID()+ let mark = try NoEpisodeHistory.Action(+ workID: workID, key: "mark/\(UUID().uuidString)", day: "2026-09-29",+ kind: .mark, observedClearKeys: ["clear/\(UUID().uuidString)"])+ let record = try BackupV17NoEpisodeAction(mark)+ let payload = BackupV17Payload(+ entries: [], works: [], sites: [], titlePatterns: [], urlRules: [],+ noEpisodeActions: [record])+ let encoded = try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Metadata(+ appBuild: "test", exportedAt: Date(timeIntervalSince1970: 0)))+ let decoded = try BackupV17Codec.decode(encoded)+ #expect(decoded.backupFormatVersion == 17)+ #expect(decoded.databaseSchemaVersion == 18)+ #expect(decoded.payload.noEpisodeActions == [record])++ var object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any])+ var body = try #require(object["payload"] as? [String: Any])+ body.removeValue(forKey: "noEpisodeActions")+ object["payload"] = body+ #expect(throws: BackupCodecError.self) {+ try BackupV17Codec.decode(JSONSerialization.data(withJSONObject: object))+ }++ let conflict = try NoEpisodeHistory.Action(+ workID: workID, key: mark.key, day: "2026-09-30",+ kind: .mark, observedClearKeys: [])+ let conflictingPayload = BackupV17Payload(+ entries: [], works: [], sites: [], titlePatterns: [], urlRules: [],+ noEpisodeActions: [record, try BackupV17NoEpisodeAction(conflict)])+ let conflicting = try BackupV17Codec.encode(+ payload: conflictingPayload, metadata: BackupV17Metadata(+ appBuild: "test", exportedAt: Date(timeIntervalSince1970: 0)))+ #expect(throws: BackupCodecError.self) { try BackupV17Codec.decode(conflicting) }+ }++ @Test("archive import unions both arrival orders and an old repeat cannot revive a mark")+ func archiveImportUnion() async throws {+ let workID = UUID()+ let mark = try NoEpisodeHistory.Action(+ workID: workID, key: "mark/\(UUID().uuidString)",+ day: "2026-09-29", kind: .mark, observedClearKeys: [])+ let clear = try NoEpisodeHistory.Action(+ workID: workID, key: "clear/\(UUID().uuidString)",+ day: "2026-09-29", kind: .clear, observedClearKeys: [])++ func plan(_ action: NoEpisodeHistory.Action) throws -> BackupImportPlan {+ let payload = BackupV17Payload(+ entries: [], works: [], sites: [], titlePatterns: [], urlRules: [],+ noEpisodeActions: [try BackupV17NoEpisodeAction(action)])+ let bytes = try BackupV17Codec.encode(+ payload: payload, metadata: BackupV17Metadata(+ appBuild: "test", exportedAt: Date(timeIntervalSince1970: 0)))+ return try BackupImporter.plan(from: bytes)+ }++ for ordering in [[mark, clear, mark], [clear, mark, clear]] {+ let fixture = try await M5Fixture()+ for action in ordering {+ try await fixture.repository.confirmImport(plan: plan(action))+ }+ let history = try await fixture.repository.withLockedContext(+ mode: .shared, operation: "checking imported action union"+ ) { context in+ try NoEpisodeIndex(context: context).history(for: workID)+ }+ #expect(history.actions.count == 2)+ #expect(try !history.isMarked(workID: workID, day: "2026-09-29"))+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swiftindex d39eb196..c041666c 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: BackupV16ExportError.self) {- _ = try await fixture.repository.backupV16Snapshot()+ await #expect(throws: BackupV17ExportError.self) {+ _ = try await fixture.repository.backupV17Snapshot() } withExtendedLifetime(fixture) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ReconcileTierTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ReconcileTierTests.swiftindex 1505d3d2..2a1c4a8d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ReconcileTierTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ReconcileTierTests.swift@@ -39,6 +39,9 @@ struct ReconcileTierTests { try await repository.refreshDiagnostics() #expect(await repository.worksWithoutMembership == false) + // First pass records the seeded notes' durable clear evidence. The+ // unchanged pass remains empty on the arrival tier.+ #expect(try await repository.reconcileAfterSync(tier: .arrival).noEpisodeChanged) #expect(try await repository.reconcileAfterSync(tier: .arrival).isEmpty) #expect(try await repository.membershipHostnames() == [Self.primary]) @@ -81,8 +84,9 @@ struct ReconcileTierTests { try await repository.refreshDiagnostics() #expect(await repository.worksWithoutMembership == false) - // Nothing to do, and no throw: the phases ran and found the library- // coherent, which is what an empty outcome over a coherent library means.+ // The first pass records stable clear evidence for the seeded note;+ // subsequent passes find the same coherent graph unchanged.+ #expect(try await repository.reconcileAfterSync(tier: .arrival).noEpisodeChanged) #expect(try await repository.reconcileAfterSync(tier: .arrival).isEmpty) #expect(try await repository.reconcileAfterSync(tier: .full).isEmpty) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swiftindex 99980334..6c0fa26c 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 = BackupV16Character(+ let record = BackupV17Character( 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: BackupV16Suppression(+ let imported = CharacterSuppression.make(imported: BackupV17Suppression( 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 38df3527..7d83a85f 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 `BackupV16Exporter.swift:41` would+/// (`+ReparseCapture.swift:284`, `:396`), and `BackupV17Exporter.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.backupV16Snapshot()+ let payload = try await repository.backupV17Snapshot() // 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/RuleSelectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swiftindex 7e952df4..9af2ec86 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) return try ModelContainer( for: schema, configurations: [ModelConfiguration(@@ -248,7 +248,8 @@ struct RuleSelectionTests { private func selectingReads() throws -> [SelectingRead] { var found: [SelectingRead] = [] for file in try Self.productionRoots.flatMap({ try swiftFiles(under: $0) })- where file.lastPathComponent != "RuleSelection.swift" {+ where file.lastPathComponent != "RuleSelection.swift"+ && file.lastPathComponent != "AsterismSchemaV17Models.swift" { let text = try String(contentsOf: file, encoding: .utf8) let relativePath = file.path.replacingOccurrences( of: Self.repositoryRoot.path + "/", with: "")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swiftindex f3ce470e..a17805bb 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.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 bcb2569c..4f5e8f2d 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swiftindex 22638cae..ddab9da7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift@@ -209,7 +209,7 @@ struct StoreMetadataTests { try #require(FileManager.default.fileExists(atPath: dir.storeURL.path + "-wal"), "the conversion has to be in the log for this to be the hazard") - #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["17.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["18.0.0"], "the conversion is committed in the log, so a reader of the log sees it") #expect(StoreMetadata.recordedVersion(at: dir.storeURL) == .atOrAboveV5, "a reader that ignored the log would still have to answer, not refuse")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swiftindex c64bc11e..4f3e8c46 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift@@ -78,6 +78,7 @@ struct ThumbnailBytesReachTests { private static let sanctioned: Set<String> = [ "Models.swift", "AsterismSchemaV16.swift",+ "AsterismSchemaV17Models.swift", "GroupOrdering.swift", "Thumbnails/ThumbnailStoreProbe.swift", "LibraryRepository+Thumbnails.swift",
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swiftindex 63f69cd3..8b7466ce 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift@@ -55,7 +55,7 @@ struct ThumbnailStoreProbeTests { let probeNames = Set(ThumbnailStoreProbe.schema.entities.map(\.name)) #expect(probeNames == ["ProbeExternalWork", "ProbeInlineWork"]) - let live = Set(Schema(versionedSchema: AsterismSchemaV17.self).entities.map(\.name))+ let live = Set(Schema(versionedSchema: AsterismSchemaV18.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 477cd798..90e67547 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) container = try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swiftindex 3c3dcc85..61b753a2 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift@@ -68,7 +68,8 @@ struct TodayDayPlanTests { hostname: String = "example.test", releaseDays: [ReleaseDay] = [.thursday], workStatus: WorkStatus = .ongoing, readingStatus: ReadingStatus = .reading,- entries: [EntrySnapshot] = [], catchUp: CatchUpRecord = .pristine+ entries: [EntrySnapshot] = [], catchUp: CatchUpRecord = .pristine,+ noEpisodeHistory: NoEpisodeHistory = .empty ) -> WorkSnapshot { WorkSnapshot( id: id, displayTitle: title, lastParsedTitle: nil,@@ -76,7 +77,8 @@ struct TodayDayPlanTests { genericNotes: "", genreTags: [], titleProvenance: .parsed, createdAt: .distantPast, modifiedAt: .distantPast, entries: entries, workStatus: workStatus, readingStatus: readingStatus,- releaseDays: releaseDays, catchUp: catchUp)+ releaseDays: releaseDays, catchUp: catchUp,+ noEpisodeHistory: noEpisodeHistory) } private static func presentationRow(id: UUID = UUID(), sharedAt: Date)@@ -996,4 +998,58 @@ struct TodayDayPlanTests { #expect(snapshot("ftp://example.test/file").primaryURL == nil) #expect(snapshot(nil).primaryURL == nil) }++ @Test("Only distinct scheduled marks inside the count interval are subtracted")+ func noEpisodeCountEndpoints() {+ let calendar = Self.calendar()+ let start = Self.day(2026, 3, 5)+ let end = Self.day(2026, 3, 26)+ let marks: Set<CivilDay> = [+ start, Self.day(2026, 3, 12), Self.day(2026, 3, 19),+ Self.day(2026, 3, 20), Self.day(2026, 4, 2)+ ]+ #expect(TodayDayPlan.releaseCount(+ of: [.thursday], after: start, through: end,+ noEpisodeDays: marks, calendar: calendar) == 1)+ #expect(TodayDayPlan.releaseCount(+ of: [], after: start, through: end,+ noEpisodeDays: marks, calendar: calendar) == nil)+ }++ @Test("A marked release stays on the shelf as a distinct completed state")+ func noEpisodeReleaseState() throws {+ let calendar = Self.calendar()+ let mark = try NoEpisodeHistory.Action(+ workID: Self.id(1), key: "mark/00000001-0000-4000-8000-000000000000",+ day: Self.thursday.description, kind: .mark, observedClearKeys: [])+ let history = try NoEpisodeHistory([mark])+ let plan = TodayDayPlan.build(+ day: Self.thursday, currentDay: Self.thursday,+ schedule: TodaySchedule.build(+ works: [Self.work(noEpisodeHistory: history)], calendar: calendar),+ presentation: Self.presentation([], calendar: calendar), calendar: calendar)+ let row = try #require(plan.releases.first)+ #expect(row.releaseState == .noEpisode)+ #expect(row.isCompleted)+ #expect(!row.isNotedOnDay)+ }++ @Test("A real note takes precedence over a stored mark")+ func notedPrecedesNoEpisode() throws {+ let calendar = Self.calendar()+ let mark = try NoEpisodeHistory.Action(+ workID: Self.id(1), key: "mark/00000002-0000-4000-8000-000000000000",+ day: Self.thursday.description, kind: .mark, observedClearKeys: [])+ let history = try NoEpisodeHistory([mark])+ let work = Self.work(+ entries: [Self.entry(sharedAt: Self.instant(2026, 3, 12))],+ noEpisodeHistory: history)+ let schedule = TodaySchedule.build(works: [work], calendar: calendar)+ #expect(schedule.works.first?.noEpisodeDays.isEmpty == true)+ let plan = TodayDayPlan.build(+ day: Self.thursday, currentDay: Self.thursday, schedule: schedule,+ presentation: Self.presentation([], calendar: calendar), calendar: calendar)+ #expect(plan.releases.first?.releaseState == .noted)+ #expect(plan.releases.first?.isNotedOnDay == true)+ } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swiftindex 5e229490..b457a70a 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: BackupV16Payload) throws -> URLTwoFieldTemplate? {+ private static func combinedRule(of payload: BackupV17Payload) 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 = BackupV16Fixtures.sequencePresenceOmittedDocument()+ let document = BackupV17Fixtures.sequencePresenceOmittedDocument() #expect(!String(decoding: document, as: UTF8.self).contains("sequencePresence")) - let decoded = try BackupV16Codec.decode(document)+ let decoded = try BackupV17Codec.decode(document) - #expect(decoded.payload == BackupV16Fixtures.combinedRulePayload(presence: .required))+ #expect(decoded.payload == BackupV17Fixtures.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 BackupV16Codec.encode(- payload: BackupV16Fixtures.combinedRulePayload(presence: .required),- metadata: BackupV16Metadata(- appBuild: "pre-feature", exportedAt: BackupV16Fixtures.created))+ let encoded = try BackupV17Codec.encode(+ payload: BackupV17Fixtures.combinedRulePayload(presence: .required),+ metadata: BackupV17Metadata(+ appBuild: "pre-feature", exportedAt: BackupV17Fixtures.created)) let json = String(decoding: encoded, as: UTF8.self) #expect(!json.contains("sequencePresence")) #expect(- json.contains(BackupV16Fixtures.sequencePresenceOmittedPayloadJSON),+ json.contains(BackupV17Fixtures.sequencePresenceOmittedPayloadJSON), "the exported payload is no longer the pre-feature payload")- #expect(encoded == BackupV16Fixtures.sequencePresenceOmittedDocument())+ #expect(encoded == BackupV17Fixtures.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 = BackupV16Fixtures.combinedRulePayload(presence: .optional)- let encoded = try BackupV16Codec.encode(+ let payload = BackupV17Fixtures.combinedRulePayload(presence: .optional)+ let encoded = try BackupV17Codec.encode( payload: payload,- metadata: BackupV16Metadata(appBuild: "with-feature", exportedAt: BackupV16Fixtures.created))+ metadata: BackupV17Metadata(appBuild: "with-feature", exportedAt: BackupV17Fixtures.created)) #expect(String(decoding: encoded, as: UTF8.self).contains(#""sequencePresence":"optional""#)) - let decoded = try BackupV16Codec.decode(encoded)+ let decoded = try BackupV17Codec.decode(encoded) #expect(decoded.payload == payload) #expect(try Self.combinedRule(of: decoded.payload)?.sequencePresence == .optional) - let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swiftindex 2da3ebe0..aa1e5871 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.backupV16Snapshot()+ _ = try await repository.backupV17Snapshot() Issue.record("expected the export to refuse a Site whose mode has no case")- } catch let error as BackupV16ExportError {+ } catch let error as BackupV17ExportError { 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/V16RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swiftindex da95e96c..b6fe4bab 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift@@ -63,8 +63,8 @@ struct V16RecordedStoreTests { return } // The stage completed and the marker moved, in that order.- #expect(try root.recordedVersions() == ["17.0.0"])- #expect(try root.markerText() == "17")+ #expect(try root.recordedVersions() == ["18.0.0"])+ #expect(try root.markerText() == "18") #expect(counts.works == 1) #expect(counts.entries == 3) #expect(counts.sites == 1)@@ -392,8 +392,8 @@ struct V16RecordedStoreTests { #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready) let (_, second) = try await LibraryRepository.openForApp(root.configuration) await second.shutdown()- #expect(try root.markerText() == "17")- #expect(try root.recordedVersions() == ["17.0.0"])+ #expect(try root.markerText() == "18")+ #expect(try root.recordedVersions() == ["18.0.0"]) withExtendedLifetime(root) {} } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swiftnew file mode 100644index 00000000..b23cfcd7--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift@@ -0,0 +1,61 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("A V17-recorded store under the V18 plan", .serialized)+struct V17RecordedStoreTests {+ @Test("V17 converts with its Work intact and an empty action table")+ func conversion() async throws {+ let root = FileManager.default.temporaryDirectory.appending(+ path: "V17Recorded-\(UUID())", directoryHint: .isDirectory)+ defer { try? FileManager.default.removeItem(at: root) }+ let configuration = LibraryConfiguration(rootDirectory: root)+ try FileManager.default.createDirectory(+ at: configuration.storeURL.deletingLastPathComponent(),+ withIntermediateDirectories: true)+ let workID = UUID()++ // A frozen seed container must be released before opening the live+ // model; SwiftData otherwise mixes identically named entity versions.+ try seedV17(at: configuration.storeURL, workID: workID)+ try Data("17\n".utf8).write(to: configuration.readinessMarkerURL, options: .atomic)++ let (result, repository) = try await LibraryRepository.openForApp(configuration)+ defer { Task { await repository.shutdown() } }+ guard case .ready = result else {+ Issue.record("expected ready after migration, got \(result)")+ return+ }+ let facts = try await repository.withLockedContext(+ mode: .shared, operation: "checking V17 conversion"+ ) { context in+ let works = try context.fetch(FetchDescriptor<Work>())+ let actions = try context.fetch(FetchDescriptor<NoEpisodeAction>())+ return (works.map(\.id), works.map(\.displayTitle), actions.count)+ }+ #expect(facts.0 == [workID])+ #expect(facts.1 == ["Migrating Work"])+ #expect(facts.2 == 0)+ #expect(try String(contentsOf: configuration.readinessMarkerURL,+ encoding: .utf8) == "18\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(+ at: configuration.storeURL) == ["18.0.0"])+ await repository.shutdown()+ }++ private func seedV17(at url: URL, workID: UUID) throws {+ let schema = Schema(versionedSchema: AsterismSchemaV17.self)+ let store = ModelConfiguration("AsterismV3", schema: schema, url: url,+ cloudKitDatabase: .none)+ let container = try ModelContainer(for: schema, configurations: [store])+ let context = ModelContext(container)+ let work = AsterismSchemaV17.Work(+ id: workID, displayTitle: "Migrating Work",+ timestamp: Date(timeIntervalSince1970: 1_000_000))+ context.insert(work)+ try context.save()+ withExtendedLifetime(container) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swiftindex 94b4c9c2..866ed58f 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swiftindex 1ac4dad6..42a6a240 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swiftindex f4542353..c425ffe4 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swiftindex 507c01b6..b9eae53f 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let container = try ModelContainer( for: schema, configurations: [ModelConfiguration(@@ -418,7 +418,7 @@ struct WriteSiteRelationshipTests { let context = ModelContext(container) try LibraryRepository.materializeArchive(- BackupImportPayload(BackupV16Fixtures.minimalTaughtPayload()), into: context)+ BackupImportPayload(BackupV17Fixtures.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) == "17",+ #expect(try markerContent(cfg) == "18", "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) == "17", "the import republishes nothing")+ #expect(try markerContent(cfg) == "18", "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) == "17")+ #expect(try markerContent(cfg) == "18") try expectEveryRelationshipPopulated(cfg) withExtendedLifetime(dir) {} }@@ -553,7 +553,7 @@ struct WriteSiteRelationshipTests { } private func importPlan() throws -> BackupImportPlan {- let payload = BackupImportPayload(BackupV16Fixtures.minimalTaughtPayload())+ let payload = BackupImportPayload(BackupV17Fixtures.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("17\n".utf8).write(to: cfg.readinessMarkerURL, options: .atomic)+ try Data("18\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 15bad60d..8c05ae91 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift@@ -44,8 +44,8 @@ struct WrongHostWorkURLCompatibilityTests { @Test("The heal leaves the archive's version pair where the schema put it") func archiveVersionIsUnchanged() { // The heal leaves the live archive generation alone.- #expect(BackupV16Document.formatVersion == 16)- #expect(BackupV16Document.schemaVersion == 17)+ #expect(BackupV17Document.formatVersion == 17)+ #expect(BackupV17Document.schemaVersion == 18) } @Test("A healed library's archive uses only the membership keys 9/10 declared")@@ -83,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 BackupV16Codec.decode(archive)+ let decoded = try BackupV17Codec.decode(archive) let minted = try #require( decoded.payload.memberships.first { $0.hostname == Self.destination }) #expect(minted.workID == workID)@@ -149,10 +149,10 @@ private struct CompatibilityRoot { let outcome = try await repository.reconcileAfterSync() #expect(outcome.memberships.movedWorkURLs == 1) - let exporter = BackupV16Exporter(+ let exporter = BackupV17Exporter( repository: repository, stagingDirectory: directory.appending(path: "staging")) let result = try await exporter.export(- metadata: BackupV16Metadata(+ metadata: BackupV17Metadata( 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 c4770f96..77c68c54 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. [- BackupV16Membership(+ BackupV17Membership( 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?-) -> BackupV16Membership {- BackupV16Membership(+) -> BackupV17Membership {+ BackupV17Membership( id: id, workID: work, hostname: hostname, createdAt: epoch, urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: workURL) } -private func url(of records: [BackupV16Membership], _ id: UUID) -> String? {+private func url(of records: [BackupV17Membership], _ id: UUID) -> String? { records.first { $0.id == id }?.workURLString ?? nil } @@ -418,14 +418,14 @@ private func url(of records: [BackupV16Membership], _ id: UUID) -> String? { /// a test can address them. private func makePlan( activePattern: Bool = true,- memberships: (_ workID: UUID, _ otherMembershipID: UUID) -> [BackupV16Membership]+ memberships: (_ workID: UUID, _ otherMembershipID: UUID) -> [BackupV17Membership] ) -> BackupImportPlan { let workID = UUID() let otherMembershipID = UUID() let patternID = UUID() let rawURL = "https://\(siteHostname)/chapter/1" - let entry = BackupV16Entry(+ let entry = BackupV17Entry( 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 = BackupV16Work(+ let work = BackupV17Work( 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 = [- BackupV16TitlePattern(+ BackupV17TitlePattern( id: patternID, siteHostname: siteHostname, version: 1, isActive: activePattern, createdAt: epoch, definition: StoredPatternDefinition(definition: .wholeTitle)) ] let sites = [siteHostname, otherHostname].map {- BackupV16Site(hostname: $0, displayName: $0, mode: $0 == siteHostname ? .taught : .untaught)+ BackupV17Site(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 5cc990e4..81a844b4 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: AsterismSchemaV17.self)+ let schema = Schema(versionedSchema: AsterismSchemaV18.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV17MigrationPlan.self,+ for: schema, migrationPlan: AsterismV18MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swiftindex 24c76e68..323f2333 100644--- a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift@@ -161,9 +161,7 @@ struct FoundationCharacterExtractionModelClientTests { /// `ExtractionResult` — which is the one thing this test exists to pin, and /// the one case left able to fail it. static func isTransientModelError(_ error: (any Error)?) -> Bool {- guard let generation = error as? LanguageModelSession.GenerationError else { return false }- if case .decodingFailure = generation { return false }- return true+ LiveFoundationModelIssue.isTransient(error) } @Test("A live model call returns a decodable ExtractionResult, places included, for one note")
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationRuleSuggestionModelClientTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationRuleSuggestionModelClientTests.swiftindex 756633ec..96550549 100644--- a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationRuleSuggestionModelClientTests.swift+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationRuleSuggestionModelClientTests.swift@@ -134,9 +134,7 @@ struct FoundationRuleSuggestionModelClientTests { /// response failed to become a `RuleProposal` — which is the one thing this /// test exists to pin, and the one case left able to fail it. static func isTransientModelError(_ error: (any Error)?) -> Bool {- guard let generation = error as? LanguageModelSession.GenerationError else { return false }- if case .decodingFailure = generation { return false }- return true+ LiveFoundationModelIssue.isTransient(error) } @Test("A live model call returns a decodable RuleProposal for a two-example corpus")
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/LiveFoundationModelIssue.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/LiveFoundationModelIssue.swiftnew file mode 100644index 00000000..3700414b--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/LiveFoundationModelIssue.swift@@ -0,0 +1,55 @@+import Foundation+import FoundationModels+import Testing++/// Keeps the live model tests sensitive to response decoding while allowing a+/// failed host service request to be reported as an intermittent known issue.+enum LiveFoundationModelIssue {+ static func isTransient(_ error: (any Error)?) -> Bool {+ guard let error else { return false }+ if let generation = error as? LanguageModelSession.GenerationError {+ if case .decodingFailure = generation { return false }+ return true+ }++ let wrapper = error as NSError+ guard wrapper.domain == "FoundationModels.LanguageModelError", wrapper.code == -1 else {+ return false+ }+ let underlying = wrapper.userInfo[NSMultipleUnderlyingErrorsKey] as? [NSError] ?? []+ return underlying.contains {+ $0.domain == "ModelManagerServices.ModelManagerError" && $0.code == 1008+ }+ }+}++@Suite("Live Foundation Models error classification")+struct LiveFoundationModelIssueTests {+ @Test("Only the observed nested host service error is transient")+ func nestedHostServiceError() {+ func wrapped(_ underlying: NSError) -> NSError {+ NSError(domain: "FoundationModels.LanguageModelError", code: -1, userInfo: [+ NSMultipleUnderlyingErrorsKey: [underlying],+ ])+ }++ let unavailable = NSError(domain: "ModelManagerServices.ModelManagerError", code: 1008)+ let unrelated = NSError(domain: "ModelManagerServices.ModelManagerError", code: 42)+ #expect(LiveFoundationModelIssue.isTransient(wrapped(unavailable)))+ #expect(!LiveFoundationModelIssue.isTransient(wrapped(unrelated)))+ #expect(!LiveFoundationModelIssue.isTransient(unavailable))+ #expect(!LiveFoundationModelIssue.isTransient(NSError(domain: "Other", code: 1008,+ userInfo: [NSMultipleUnderlyingErrorsKey: [unavailable]])))+ #expect(!LiveFoundationModelIssue.isTransient(nil))+ }++ @Test("Typed decoding failures still fail the live test")+ func decodingFailure() {+ let decoding = LanguageModelSession.GenerationError+ .decodingFailure(.init(debugDescription: "invalid response"))+ let rateLimit = LanguageModelSession.GenerationError+ .rateLimited(.init(debugDescription: "retry later"))+ #expect(!LiveFoundationModelIssue.isTransient(decoding))+ #expect(LiveFoundationModelIssue.isTransient(rateLimit))+ }+}
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a453a711..f127dde1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,8 +6,32 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Fixed++- **Release carousel menus (T-2374):** long-press actions now target the+ selected release instead of the first card. Preserve tap navigation with+ per-card menus and add a second-card interaction regression. Include the+ release error and undo strings generated by Xcode.+ ### Changed +- **No episode today — App phase (T-2374):** prepare note clears before+ publication, add selected-date mark/undo actions and distinct completed+ presentation at regular and accessibility text sizes, and omit marked+ releases from shortcut answers. Record passing Core, simulator and focused+ iPhone/iPad checks; signed Mac and two-device CloudKit verification remain.++- **No episode today — Core phase (T-2374):** add V18 action history and+ archive 17/18 union, permanent clearing across note and work lifecycles,+ and indexed no-episode dates in Today and catch-up calculations. Retain+ V16/V17 upgrades and keep unchanged reconciliation within its existing+ performance ceiling using a store-history checkpoint.++- **No episode today — Specification (T-2374):** document the approved+ requirements, sync and persistence design, decisions, and 17 implementation+ tasks for per-date no-episode marks; register the feature as planned in the+ specs overview.+ - Include Xcode-generated localization entries for catch-up progress and app intents, and add the catch-up implementation explanation.
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 84a14fca..7c33aa00 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -56,6 +56,7 @@ | [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 | Done — implementation complete; 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. |+| [No Episode Today](#no-episode-today) | 2026-09-29 | Done | Full spec (T-2374). All 17 tasks implemented and reviewed: synced marks, permanent note clearing, adjusted counts, release menus and shortcut filtering. Automated checks pass; signed Mac build and real two-device CloudKit verification remain. | --- @@ -922,3 +923,15 @@ Full spec for §6 and §7 of `docs/Asterism-Today-v2.md`. The reader sets a work - [runbook.md](catch-up-progress/runbook.md) - [verification-run.md](catch-up-progress/verification-run.md) - [implementation.md](catch-up-progress/implementation.md)++## No Episode Today++**Created:** 2026-09-29 · **Status:** Done — all 17 tasks implemented and reviewed. Core, simulator unit, identity and focused iPhone/iPad UI checks pass. The host's Mac signing failure and outstanding two-device CloudKit check are recorded in the verification run.++Full spec (T-2374). The release context menu marks or unmarks the selected date. Marked releases keep the completed shelf treatment with a minus icon, are excluded from expected-release counts and the Chapters Releasing Today shortcut, and are permanently cleared by matching notes. Retained action history resolves concurrent mark/undo conflicts to unmarked while allowing deliberate re-marking. Schema V18 adds the action table, the archive moves to 17/18, and V16/V17 upgrade paths remain supported.++- [requirements.md](no-episode-today/requirements.md)+- [design.md](no-episode-today/design.md)+- [tasks.md](no-episode-today/tasks.md)+- [decision_log.md](no-episode-today/decision_log.md)+- [verification-run.md](no-episode-today/verification-run.md)
diff --git a/specs/bugfixes/core-host-compatibility/report.md b/specs/bugfixes/core-host-compatibility/report.mdnew file mode 100644index 00000000..31f1ca54--- /dev/null+++ b/specs/bugfixes/core-host-compatibility/report.md@@ -0,0 +1,58 @@+# Bugfix Report: Core host compatibility failures++**Date:** 2026-09-29 +**Status:** Fixed++## Description of the Issue++The pre-push Core run completed 3,346 cases with four failures: two live Foundation Models requests and two concrete `NSItemProvider` plain-text loads. The live tests received a host service error despite the model's earlier availability check. The share tests discarded valid text providers and reported `noUsableURL`.++**Reproduction steps:** Run `make test-core` on the macOS 27 host with Apple Intelligence available. The archived run and xUnit are under `/tmp/asterism-prepush-review.xjWqd3/review-inputs/`.++**Impact:** The Core pre-push gate was red. A concrete plain-text share on a host with the same Uniform Type Identifiers behavior could also lose its embedded URL.++## Investigation Summary++- **Symptoms examined:** The archived xUnit names `FoundationCharacterExtractionModelClientTests.liveCall()`, `FoundationRuleSuggestionModelClientTests.liveCall()`, and both `NSItemProviderTextBridgeTests` cases.+- **Code inspected:** The two live model tests, the production `NSItemProvider` bridge, `SharePayloadExtractor`, and the earlier Tapas plain-text bugfix report.+- **Hypotheses tested:** A local provider registered `public.plain-text` but `hasItemConformingToTypeIdentifier(public.text)` was false. A direct `UTType.plainText.conforms(to: .text)` check was also false on this host, showing the bridge filtered the provider before loading. The model failures' xUnit entries show an `NSError` wrapper with a nested service error, not the typed `GenerationError` the matcher accepts.++## Discovered Root Cause++The text bridge relies only on `.text` conformance to find the registered representation. This host's Uniform Type Identifiers database does not report conformance for `public.plain-text`, so `hasText` is false and extraction never calls `loadText`. The live tests' known-issue matchers accept only `LanguageModelSession.GenerationError`; their observed `FoundationModels.LanguageModelError` wrappers contain `ModelManagerServices.ModelManagerError` code 1008 and escape that matcher. The model service's failure is environmental; the test classification was incomplete.++**Defect type:** Platform conformance mismatch and incomplete error classification. +**Contributing factors:** The model availability read is only a snapshot. The bridge's previous concrete provider regression ran on a host where the same conformance check returned true.++## Resolution for the Issue++- Recognize standard plain-text and UTF-8 plain-text Uniform Type Identifiers explicitly, preserving the existing `.text` check for other types.+- Match only the observed Foundation Models wrapper and nested host service error 1008 as intermittent in the live tests. Typed decoding failures remain failures.++The alternative of skipping all live model errors would hide a response decoding defect. Removing the concrete provider tests would hide a real share extraction failure.++## Regression Test++`NSItemProviderTextBridgeTests` now asserts that each concrete plain-text provider advertises text before extraction, then checks the expected embedded URL. `LiveFoundationModelIssueTests` exercises the nested service wrapper, unrelated errors, and typed decoding failure without repeatedly contacting the model service.++**Focused command:** `make test-core CORE_TEST='NSItemProviderTextBridgeTests|LiveFoundationModelIssueTests'`++## Affected Files++| File | Change |+|------|--------|+| `Packages/AsterismCore/Sources/AsterismCore/NSItemProvider+ItemProviderLoading.swift` | Recognize standard plain-text identifiers |+| `Packages/AsterismCore/Tests/AsterismCoreTests/NSItemProviderTextBridgeTests.swift` | Assert concrete provider availability |+| `Packages/AsterismCore/Tests/AsterismIntelligenceTests/LiveFoundationModelIssue.swift` | Share and test narrow live error classifier |+| `Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift` | Use shared classifier |+| `Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationRuleSuggestionModelClientTests.swift` | Use shared classifier |++## Verification++Both focused suites passed: the two concrete provider cases and the two new error-classification cases. The final `make test-core` run exited 0. Its text output records 3,293 passed, 55 skipped, and zero failed test declarations, including successful live model calls and both provider cases. `make test-core` ran `make verify-identity` as a prerequisite and reported no new compiler warnings. Full output: `/tmp/asterism-2374-core-final.log`.++The live model calls succeeded in this final run, so the new 1008 path is verified by a synthetic regression with the exact nested error domains and code from the earlier failing xUnit, rather than by inducing another live service outage.++## Prevention++Keep concrete platform providers in share tests, and test both a transient service wrapper and a decoding failure when live model error handling changes.
diff --git a/specs/bugfixes/release-carousel-context-menu/report.md b/specs/bugfixes/release-carousel-context-menu/report.mdnew file mode 100644index 00000000..ea61cb30--- /dev/null+++ b/specs/bugfixes/release-carousel-context-menu/report.md@@ -0,0 +1,74 @@+# Bugfix Report: Release carousel context menu targets the first card++**Date:** 2026-09-29 +**Status:** Fixed++## Description of the Issue++With more than one release in Today's horizontal shelf, a long press on the second card opened the first card's context menu. A reader could therefore mark the wrong work as having no episode.++**Reproduction steps:**+1. Open Today with the `seeded-no-episode` fixture. Amber Signal is pending and Blue Signal is marked as no episode.+2. Long-press Blue Signal's cover.+3. Observe `No episode today` (Amber's action) instead of `Undo no episode` (Blue's action).++**Impact:** The menu could act on a different release from the one pressed whenever multiple covers share the shelf.++## Investigation Summary++- **Symptoms examined:** The new UI regression pressed Blue's element at its own coordinates. Amber occupied x=20–118 pt and Blue x=132–230 pt. After the Blue press, Xcode's captured accessibility hierarchy contained Amber's `No episode today` menu action.+- **Code inspected:** `ReleaseShelf` and `ReleaseShelfItem` in `TodaySections.swift`, their `TodayView` call site, the fixture seeder, and existing Today UI tests.+- **Hypotheses tested:** Moving the interaction content shape from the Button label to the Button did not change the result. Attaching `.contextMenu` directly to the inner card content also opened Amber's menu. Both attempts failed the same coordinate-based UI test.++## Discovered Root Cause++The separate release buttons exposed distinct accessibility frames and labels, but SwiftUI's `.contextMenu` interaction inside the horizontal shelf's single List row resolved the long press to the first item's menu. The exact framework-internal reason for that resolution is not observable here; the captured menu and the two failed placement changes establish that the original context-menu attachment was unsuitable for this layout.++**Defect type:** UI interaction routing.++**Why it occurred:** The original UI journey mutated only the first card. Its later long press on Blue checked that navigation existed, but did not check which work the menu targeted.++## Resolution for the Issue++**Changes made:**+- `Asterism/Asterism/Views/TodaySections.swift` — make each release card a SwiftUI `Menu` with a `primaryAction`. Tapping still opens the work; long pressing opens that card's own mark/undo, page, and navigation actions.+- `Asterism/AsterismUITests/TodayUITests.swift` — press the second card at its own coordinates, verify Blue alone toggles twice while Amber stays pending, and verify a normal tap opens Blue.++**Approach rationale:** A `Menu` owns both the card's primary tap and secondary long-press action. It avoids attaching a separate context-menu gesture to multiple children of one scrolling List row while preserving the existing visible card and commands. Apple's [Menu documentation](https://developer.apple.com/documentation/swiftui/menu) describes this primary/secondary interaction.++**Alternatives considered:** Changing `.contentShape` placement and moving `.contextMenu` into the Button label; both retained the wrong first-card menu in the focused UI run.++## Regression Test++**Test file:** `Asterism/AsterismUITests/TodayUITests.swift` +**Test name:** `testNoEpisodeShelfSecondCoverMenuTargetsSecondWork`++**What it verifies:** A physical long press on Blue opens Blue's action, undo/mark changes Blue alone, and a tap on Blue opens Blue's detail.++**Run command:** `make test-only TEST=AsterismUITests/TodayUITests/testNoEpisodeShelfSecondCoverMenuTargetsSecondWork XCODE_TEST_FLAGS='-collect-test-diagnostics never'`++## Affected Files++| File | Change |+|------|--------|+| `Asterism/Asterism/Views/TodaySections.swift` | Per-card Menu with primary navigation action |+| `Asterism/AsterismUITests/TodayUITests.swift` | Second-card interaction regression |+| `specs/bugfixes/release-carousel-context-menu/report.md` | Investigation and verification record |++## Verification++**Automated:**+- Red before fix: second-card test failed because Blue's `Undo no episode` was absent; Xcode's hierarchy showed Amber's `No episode today`. Log: `/tmp/asterism-carousel-red.log`.+- Green after fix: the second-card test and the existing `testNoEpisodeShelfMenusMarkUndoAndKeepWorkNavigation` each passed. Logs: `/tmp/asterism-carousel-final-ui.log`, `/tmp/asterism-carousel-existing-ui.log`.+- The existing iPad `testNoEpisodeMenuWorksBesideWideDetailColumn` passed. Log: `/tmp/asterism-carousel-wide-ui.log`.+- `make verify-identity` passed. Log: `/tmp/asterism-carousel-identity.log`.+- `make test-quick SKIP_MAC=1 XCODE_TEST_FLAGS='-collect-test-diagnostics never'` passed. Log: `/tmp/asterism-carousel-test-quick.log`.+- `git diff --check` passed. The Makefile has no lint target; the simulator test builds compiled the changed Swift files.++**Device delivery:** Xcode MCP installed and launched the corrected `Asterism Development` build on the Makefile-selected phone, `The Dark Side`, successfully. The owner confirmed that the fix works on the phone.++**Limit:** `SKIP_MAC=1` omits the macOS build because this machine's CLI signing fails with `errSecInternalComponent`.++## Prevention++When multiple items in a scrolling row have distinct menus, test a non-first item with a physical coordinate press and assert the affected work's identity. The first item's menu alone cannot prove per-item routing.
diff --git a/specs/no-episode-today/decision_log.md b/specs/no-episode-today/decision_log.mdnew file mode 100644index 00000000..e3585afb--- /dev/null+++ b/specs/no-episode-today/decision_log.md@@ -0,0 +1,144 @@+# Decision Log: No Episode Today++Transit: T-2374++## Quick Decisions++| ID | Date | Decision | Rationale |+|----|------|----------|-----------|+| Q1 | 2026-09-28 | Use the full spec workflow; name the feature `no-episode-today`. | Owner approved the scope assessment and selected the name. |+| Q2 | 2026-09-28 | No-episode marks sync between devices. | Owner expects this library state to sync like other library data. |+| Q3 | 2026-09-28 | A mark may apply to any selected date, including past and future dates. | Owner permits any date even though today is the main use case. |+| Q4 | 2026-09-28 | Keep a marked work on the Releasing shelf with the same completed treatment as a work noted that day, but a distinct icon. | Owner wants the release treated as dealt with while distinguishing no episode from a recorded note. |+| Q5 | 2026-09-28 | A note for the marked work and date permanently clears that date's mark; deleting or moving the note later does not restore it. | Owner confirmed date-specific automatic undo and permanent clearing. |+| Q6 | 2026-09-28 | Offer marking and manual undo through the release's context menu. | Owner approved both actions so an accidental mark can be corrected without adding a note. |+| Q7 | 2026-09-28 | Exclude marked dates from expected-release counts used to estimate unread episodes. | Owner confirmed that a known non-release must not increase the estimate. |+| Q8 | 2026-09-28 | Omit marked works from Chapters Releasing Today. | Owner wants the shortcut to exclude known non-releases. |+| Q9 | 2026-09-28 | Keep the existing supported backup version-pair policy and no mixed-version sync guarantee. | Owner confirmed the project remains in full development mode. |+| Q10 | 2026-09-28 | Requirements approved, including summary counts, `releases since`, and manual undo through visible release rows. | Owner explicitly approved proceeding to design. |+| Q11 | 2026-09-28 | Use `minus` in the existing completed-release badge and `{read} of {total} read · {skipped} no episode` when skips exist. | Keeps the established shelf treatment while distinguishing skipped releases from read ones; approved with the design on 2026-09-29. |+| Q12 | 2026-09-28 | Retain V16 upgrade support. | Approved design preserves the migration path; overall approval is not evidence that every device has passed V16. |+| Q13 | 2026-09-29 | Design approved, including action retention until work deletion; proceed to task planning. | Owner explicitly approved continuing. Implementation remains a separate gated phase. |+| Q14 | 2026-09-29 | All 17 implementation tasks approved. | Owner approved the task plan; requirements, design and task planning are complete. |++## Decision 1: Unmarked Wins Concurrent Mark and Undo++**Date**: 2026-09-28+**Status**: accepted++### Context++Two offline devices can independently mark and undo the same work's release date. The resulting state needs to agree across devices without relying on arrival order.++### Decision++Resolve concurrent mark/undo conflicts to unmarked. A deliberate new mark after observing the cleared state remains possible, provided no matching note exists. Matching-note precedence and permanent automatic clearing continue to apply.++### Rationale++The owner chose unmarked because a release can always be marked again. Keeping a potentially available release visible for attention is preferable to silently dismissing it.++### Alternatives Considered++- **Latest action wins:** Rejected by the owner in favor of unmarked winning the conflict, rather than choosing by timestamps.+- **Marked wins:** Rejected because it would dismiss the release despite another device's undo.++### Consequences++**Positive:**+- Conflicts leave the release available for attention and correction.++**Negative:**+- An offline mark may need to be repeated after synchronization.+- The design must distinguish conflicting actions from a deliberate new mark after a clear.++---++## Decision 2: Retain Actions With Observed Clear Keys++**Date**: 2026-09-28+**Status**: accepted++### Context++CloudKit can deliver concurrent changes in either order. Decision 1 requires an unseen clear to defeat a mark while permitting a deliberate later mark, and Req 3.2 requires a clear to outlive the note that caused it and stale backup imports.++### Decision++Store immutable action payloads in a separate synced table. A mark acknowledges the clear keys it observed; an unacknowledged clear defeats it. Union actions when reading or importing, and retain their history until the work is deleted. Capture stable note-clear evidence with note mutations even when no mark is locally visible.++An actual note arrival at a work/date also creates a fresh clear, including a repeated attachment or restoration of the same note. Reconciliation and the pre-removal hook create a fresh clear when a live matching note overlaps an otherwise active mark; unchanged reconciliations are no-ops.++### Rationale++Separate inserted records preserve independent actions under CloudKit's row-level syncing. The acknowledgement set distinguishes a new deliberate mark from an offline conflict without trusting device clocks. Retained clears prevent resurrection after a note is deleted or an archive restored.++Stable note identity alone cannot represent repeated attachment: a later mark may already acknowledge that identity's clear. Fresh arrival/overlap evidence prevents moving a note back and then deleting it from reviving such a mark.++### Alternatives Considered++- **Boolean or timestamped value on Work:** Loses independent per-date changes and cannot distinguish concurrency from an intentional later mark.+- **One union blob on Work:** Concurrent updates can overwrite one another before the app receives both histories.+- **Age-based history cleanup:** Cannot prove that an old offline device or supported-format archive will never return.++### Consequences++**Positive:**+- Arrival order, duplicates and clock skew do not determine the outcome.+- One pure fold drives all consumers and can be checked with generated histories.++**Negative:**+- History grows with actions and observed note facts until work deletion.+- Note mutation, backup and reconciliation paths must retain clearing evidence; this is more work than a display-only flag.++The owner accepted the storage trade-off with design approval on 2026-09-29.++---++## Decision 3: Cache Completed Scans By Store History++**Date**: 2026-09-29+**Status**: accepted++### Context++The action-bearing M4 fixture exposed an unchanged-reconciliation regression:+the first implementation took about 2.37 seconds against the existing 100 ms+regression ceiling. Reusing fetched actions reduced this to about 0.75 seconds;+profiling still attributed most time to fetching notes and decoding actions.+The approved design permits a generation cache rather than widening budgets.++### Decision++Keep an actor-local completed-scan checkpoint keyed by the latest SwiftData+history transaction token and the note calendar's time zone. Skip scanning only+when the checkpoint matches and the context has no pending changes. Certify a+scan only when it wrote nothing and its pre/post history tokens match. Missing+history or an intervening transaction requires a full scan.++### Rationale++History tokens detect same-count changes saved by another context. Comparing+tokens before and after scanning avoids certifying a concurrent change that the+scan did not process. The measured unchanged paths now take about 27–28 ms,+inside the existing regression ceiling, without new persisted state.++### Alternatives Considered++- **Always scan:** Correct, but the measured fetch and decode costs exceed the+ existing budget even after removing repeated work.+- **Cache by row counts or reconciliation tier:** Misses same-count edits and+ cannot establish that note assignments and action payloads are unchanged.+- **Increase the budget:** Rejected; the approved plan requires resolving this+ indexing regression rather than weakening the gate.++### Consequences++**Positive:**+- Unchanged reconciliation avoids materializing thousands of notes and actions.+- Same-count external saves invalidate the checkpoint.++**Negative:**+- A scan that writes clears requires another unchanged scan before caching.+- Missing history falls back to the full scan, retaining its measured cost.+- Host token tests do not replace the outstanding real CloudKit delivery check.
diff --git a/specs/no-episode-today/design.md b/specs/no-episode-today/design.mdnew file mode 100644index 00000000..85fda329--- /dev/null+++ b/specs/no-episode-today/design.md@@ -0,0 +1,161 @@+# Design: No Episode Today++Transit: T-2374. Requirements and design are approved; design approval recorded on 2026-09-29.++## Overview++Add a synced table of per-work, per-date actions and a pure fold that derives no-episode dates. A mark records which clears it has seen: unseen clears defeat it, while a deliberate mark after a clear remains possible (Decision 1).++## Data Models and Conflict Rule++Add `NoEpisodeAction` to the live V18 schema, nested with the other models and exposed through a typealias. It has no SwiftData relationships or uniqueness constraints. Its stored fields are `id: UUID`, `workID: UUID`, and `payload: Data?`, with CloudKit-compatible defaults. The required versioned JSON payload contains:++| Field | Meaning |+|---|---|+| `key` | Logical action identity: `mark/{UUID}`, `clear/{UUID}`, or the note-clear key below |+| `day` | Validated Gregorian year/month/day; the existing `CivilDay` value, independent of device time zone |+| `kind` | `mark` or `clear` |+| `observedClearKeys` | Sorted unique clear keys acknowledged by a mark; empty for a clear |++The payload is immutable. `workID` changes only through the existing work-merge/collapse operation. Physical row IDs are not logical action identity: duplicate rows with identical logical content count once. Canonical encoding sorts keys and arrays; validate each acknowledgement as a clear key, never a mark key. Unknown versions, invalid dates and conflicting payloads for one logical key are errors, not a guessed no-episode state.++For one work/date, let `C` be the union of explicit clear keys and all clear keys referenced by marks. The date is marked exactly when some mark acknowledges every key in `C`. This is a set-union fold: order and duplicate delivery do not affect the result. A referenced clear is evidence even if its own row has not arrived. No wall clock, row `modifiedAt`, or CloudKit arrival order participates.++| Action sequence | Result |+|---|---|+| Mark with no clears | Marked |+| Mark acknowledges C; an unseen clear D arrives | Unmarked |+| Mark/undo happen independently offline | Unmarked in either delivery order |+| New mark acknowledges C and D after observing the clear | Marked |+| Old marks or old backups arrive afterwards | Unchanged |+| Two concurrent new marks, with no new clear | Marked once |++Retain actions, including defeated marks and clears, until their work is deleted. Do not compact by age: neither offline devices nor old supported-format archives have an acknowledgement boundary. Persist full history in backups (Decision 2).++## Components and Interfaces++New Core files live in `Packages/AsterismCore/Sources/AsterismCore/`:++| Component | Contract |+|---|---|+| `NoEpisodeHistory.swift` | Codable action values, strict decoding, set-union fold and active-date derivation; no store or clock access |+| `NoEpisodeIndex.swift` | Fetch actions once and bucket by logical work ID; union duplicate rows without traversing Work inverse relationships |+| `NoEpisodeWriter.swift` | Insert missing actions and note clears into the caller's context; never save or refresh on its own |+| `LibraryRepository+NoEpisode.swift` | Exclusive-lock mark/undo commands, note reconciliation, refusal/error mapping |++```swift+func markNoEpisode(workID: UUID, day: CivilDay, calendar: Calendar)+ async throws -> LibraryWriteOutcome+func undoNoEpisode(workID: UUID, day: CivilDay)+ async throws -> LibraryWriteOutcome+func prepareNoEpisodeNotes(calendar: Calendar) async throws+```++Add these methods to `LibraryProviding` and update its forwarding implementations and test doubles. Preparation is idempotent, takes the exclusive repository lock, and saves only newly materialized clears. Existing note writers capture one calendar at their commit boundary through a new injected `@Sendable () -> Calendar` repository dependency, defaulting to `Calendar.current` in production; tests inject the same calendar used by their read. The app and share-extension repository factories supply that dependency. The explicit preparation/calendar parameters use the app's already captured publication calendar.++Each command resolves the current work group, applies existing write eligibility/torn-group gates, and re-reads its action history under the repository lock. Marking verifies that the work is scheduled for the supplied date and that no matching note exists; its new action acknowledges the current clear-key set. Undo appends a fresh clear. Repeated marking of an already marked date and undoing an already unmarked date are no-ops. Commands leave Work metadata and catch-up confirmations untouched. A save failure rolls back the action and returns through the existing library failure path (Reqs 1.1–1.5).++The app passes the selected date captured at the menu tap, not a later selection. It disables repeated taps while the command runs, refreshes only after a committed result, and uses the existing alert/refusal presentation for failures. Refresh failure after a successful save is reported as refresh failure, not a failed write.++## Automatic Clearing and Note Lifetimes++Derive note clears from the same logical Entry snapshots that Today uses, including its `lastSharedAt` day rule. The clear's stable logical key is the canonical encoding of `(entry UUID, work UUID, lastSharedAt in integer milliseconds, civil day)`, prefixed `note/`. This gives repeated reconciliation the same clear key without requiring unique CloudKit rows.++Every note mutation records stable clears for its logical assignments/dates **before and after** the mutation in the same save as the note change. In addition, each actual transition into a `(work, noted date)` that the note did not occupy immediately before the mutation appends a fresh `clear/{UUID}` action, even if that note occupied the destination earlier and even when no mark is locally visible. Capture, reattachment and accepted backup restoration therefore leave new evidence after a repeated occurrence. Deletion preserves the before-clear; reassignment and re-share preserve the old clear and add the destination clear. An unchanged note-text edit or repeated no-op import creates no fresh occurrence. A refused commit rolls back both note and action rows. Projection and draft-edit paths remain read-only.++Sync reconciliation materializes missing stable note-clear actions from the resulting logical Entry groups after assignment/duplicate reconciliation. After folding those actions, if a live matching note still overlaps an active mark (because the mark already acknowledges that note's stable key), append one fresh `clear/{UUID}` for the work/date. Re-folding then yields unmarked, so unchanged reconciliation writes nothing further. The before-mutation hook applies this same overlap rule before any note can leave or be deleted. Independently generated clears on two devices are both retained.++A read includes current matching-note clear keys in the pure fold and gives the ordinary noted state precedence, so temporary arrival gaps cannot display a no-episode mark over a note. Stable evidence covers delivery order; fresh occurrence and overlap clears make clearing permanent even when the same note is moved back or restored repeatedly (Decision 2).++Calendar changes use the same captured calendar as Today: before publishing in a new calendar context, run the targeted note-clear reconciliation and then the read, retaining the existing `CalendarKey` publication guard. The same preparation applies to a cold intent's first read. This is an explicit repository maintenance operation called by the app/broker, not a write inside `todayPresentation`, a view, or a projection. Note clears already recorded for a date remain recorded when the time zone changes; the mark itself never changes civil date (Reqs 3.1–3.4, 5.3).++## Reads, Counts, and UI++`WorkSnapshot` carries `NoEpisodeHistory`; every group-snapshot caller receives the relevant history from the shared index. `ScheduledWork` derives active dates using the supplied calendar and note snapshots. The Today publication builds the index once alongside its existing Entry/Work reads, preserving the single-publication boundary and its avoidance of `works()` at launch.++`ReleaseRow` adds `releaseState: pending | noted | noEpisode`. Notes have first precedence; otherwise the history decides between pending and no episode. Keep `isNotedOnDay` note-only, and add `isCompleted` for shelf styling and ordering. Catch-up status does not become caught up merely because today's release has no episode.++`TodayDayPlan.releaseCount` accepts the active date set, keeps the existing whole-week arithmetic, and subtracts distinct marked dates satisfying `start < date <= end` whose weekday belongs to the schedule. Pass that same set into both bounds of `CatchUpProgress.build`, the `releases since` line, work detail and the Set latest sheet. No per-day scan of the whole interval is introduced, and a mark never rebases or overwrites the confirmed latest/last-read values (Reqs 4.1–4.3).++In `TodaySections.swift`, `ReleaseShelfItem` reuses the read cover's badge container, opacity, border/glow suppression and next-episode-badge suppression. A no-episode row uses the SF Symbol `minus` in place of `checkmark`; the accessible label says `No episode`. `ReleaseShelfText.ordered` partitions pending/completed and retains the existing title order within each partition. Summary text is `{read} of {total} read` plus ` · {skipped} no episode` when skipped is nonzero. The context menu adds the selected-date action or undo and keeps Open Work Page and Go to Work (Reqs 2.1–2.5).++`IntentAnswers.releasingToday` filters out `.noEpisode` before creating `ReleaseAnswer` values. The existing intent dialog, snippet, WorkEntity list and empty-result handling then receive the same filtered answer (Req 6.1).++## Integration and Parity Audit++The audit follows Entry assignment/time changes, Work group snapshots, release-count consumers, and existing schema/backup table registration. Production call sites need the following equivalents; fixtures never replace the production hooks.++| Existing site/pattern | Needs equivalent | Change |+|---|---|---|+| `LibraryRepository.capture`, `updateEntry`, `deleteEntry`, `moveEntry`, assignment helpers | Yes | Capture logical before/after note facts; append clears within each existing save |+| `LibraryRepository+ReparseCapture` `commitCapture`, `commitReparse`, `applyCaptureAssignment` | Yes | Note-clear hook in committed paths only |+| `LibraryRepository+Capture` `commitReShareUpdate`, `recordDrainedReShare` | Yes | Old and new noted dates; drained captures use the same contract |+| `LibraryRepository+ComposedTeaching` assignment commits | Yes | Clears when teaching assigns previously unattached notes |+| `LibraryRepository+DuplicateResolution` and `DuplicateReconciler` Entry folds, detachments and deletions | Yes | Before/after logical note facts; retain clears before deleting a losing Entry |+| `LibraryRepository+ConfirmImport` `commitEntries`, legacy assignment reconnects; scratch import in `LibraryRepository+BackupImport` | Yes | Union imported history and capture note clears across imported note changes; scratch projection remains isolated |+| `LibraryRepository+WorkMerge`, `DuplicateReconciler` Work collapse, Work duplicate resolution | Yes | Move action rows to surviving logical Work and union histories without changing keys or acknowledgements; clear matching transferred notes in same commit |+| `LibraryRepository+WorkDeletion` | Yes | Remove the work's action rows in the existing deletion commit; when preserving notes by detachment, preserve clears only for surviving works |+| `LibraryRepository.reconcileAfterSync`, `ReconciliationOutcome` | Yes | Idempotent note-clear/action validation phase on both arrival and full tiers; report whether it wrote |+| `AppLibraryModel.publishToday`, `refreshAll`, calendar changes; `IntentLibraryBroker` preparation | Yes | Prepare calendar-specific note clears before publication/read; preserve refresh generation and failure handling |+| `LibraryRepository+Groups.snapshot` overloads; `LibraryRepository` work/group snapshot overloads and callers (`works`, `work`, `workDestinations`, `insertWork`, `updateWork`) | Yes | Inject indexed history; new works start empty; metadata edits preserve it |+| `LibraryRepository+TodayPresentation.todaySchedule`, `LibraryRepository+WorkDetail`, `LibraryRepository+CatchUpProgress.catchUpSheetState` | Yes | Supply history in coherent snapshot read; no per-work table fetch in bulk readers |+| `TodaySchedule.build`, `ScheduledWork`, `TodayDayPlan.row`, `CatchUpProgress.build` overloads | Yes | Carry active dates into every count; no default empty history at production call sites |+| `WorkDetailView` direct `CatchUpProgress.build` call | Yes | Supply the loaded work's history using the same calendar |+| `TodayView`, `ReleaseShelf`, `ReleaseShelfItem`, `ReleaseShelfText` | Yes | Date and callbacks, completed state, icon, ordering, summary, accessibility |+| `IntentAnswers.releasingToday`, `ChaptersReleasingTodayIntent` | Yes | Filter derived state before all output forms |+| `CatchUpWriter`, catch-up confirmation election, work-editor rebase | No | No-episode state has a separate union rule; do not stamp/rebase confirmed values |+| Stats, note search, markdown export, Works filters | No | No synthetic notes or new filter dimension |+| `Models`, schema lists, `LibraryRepository+Bootstrap`, scratch import gates, `LibraryRepository+EmptyLibrary` | Yes | Register V18 and the new table everywhere; empty-library reset removes actions |+| `BackupV16Types/Codec/Exporter`, archive projection/builders, importer/version gates, reference checks, confirm-import, checksum/golden fixtures | Yes | Replace supported wire pair with 17/18 and include full action history |+| `StoreMetadata`/store digests, model/marker/archive contracts, library validation | Yes | Include actions in schema and integrity contracts; absence of a referenced work alone remains tolerated hydration |+| `TodayFixture`, M4 schedule fixtures, `CatchUpFixtureWriter`, test-only raw Entry assignments | Yes | Seed through shared action helpers when modeling notes/marks; keep intentionally malformed fixtures explicit |++Work merging preserves action identities and unions the two date histories; clears from either work defeat marks that did not observe them. Follow the repository's existing child-row reassignment semantics; this feature does not introduce cross-device Work merge identity reconciliation. Dangling work references remain stored but produce no shelf row. Only an explicit known Work deletion removes its actions; absence during hydration never does.++## Migration and Backup++Freeze V17's models exactly and add V18 with the new table; retain the existing frozen V16 and V16→V17 stage. `AsterismV18MigrationPlan` contains `[V16, V17, V18]`, with lightweight stages. The app accepts markers `16`, `17`, `18`; the extension accepts only `18`. Conversion requires no note/action backfill: the table begins empty and ordinary note processing creates clear evidence. Preserve the app-only migration boundary and marker advancement after a successful open. Retiring V16 requires the owner's population confirmation and a corresponding design update before implementation.++The archive pair becomes format 17/schema 18, with a required `noEpisodeActions` array. Export logical actions in stable work/date/key order with their acknowledgements, including clears and dangling references; checksum covers the array. Import validates the whole array before writes, rejects contradictory content for a logical key, unions by `(workID, key)` before note changes, and never replaces local history with an archive's subset. A repeat import is a no-op; an old archive cannot defeat a later clear. Archive data is not gated on the Work row's `modifiedAt`. Other version pairs are rejected before mutation under Q9.++Update bootstrap/marker and archive contracts in the same implementation phase as the new model. Keep the schema fixture's seed-container lifetime separate from the migrated-container lifetime, following the existing V16 recorded-store pattern and the saved SwiftData migration note.++## Error Handling++| Condition | Result |+|---|---|+| Matching note or changed schedule at mark commit | Refuse using existing conflict/invalidated outcome; refresh saved state |+| Torn/unwritable Work group | Existing repository refusal; no action saved |+| Invalid stored action payload or conflicting logical key | Report a scoped no-episode data error; do not silently count the date as marked or permit a mark to overwrite it |+| Missing referenced clear row | Fold its referenced key as clear evidence; no error |+| Missing Work during sync | Retain action, omit absent work from UI; no deletion or age-based diagnosis |+| Save or note-clear maintenance failure | Roll back unsaved changes; preserve last published state and report failure through existing app/broker surfaces |+| Invalid archive action | Reject import validation before touching the live store |++## Testing Strategy++| Coverage | Requirement IDs and cases |+|---|---|+| Pure history fold, Swift Testing | 3.2–3.4, 5.1–5.2, 5.6: concurrent mark/clear, observed re-mark, late clear row, duplicate rows, permutations, repeated import, no clock dependence |+| Repository commands and injected save failure | 1.1–1.5: selected dates past/today/future, existing note, schedule/status race, torn group, idempotent retry, metadata unchanged, rollback |+| Note lifecycle matrix using real commit entry points | 3.1–3.4: capture, re-share, reassignment, deletion, teaching, duplicate collapse, import and sync; note deleted before an offline mark arrives; move away → mark → move back → delete and restore → mark → restore equivalents; unchanged reconcile/import creates no fresh clears; refused writes retain state |+| Calendar and preparation | 3.1–3.4, 5.3: date boundary, DST, non-Gregorian device calendar, time-zone change, clear remains after note removal, stale publication cycle discarded |+| Count and snapshot parity | 4.1–4.3: interval endpoints, unscheduled marks, multiple dates, count-up off, both expected-latest bounds, unknown `releases since`, work detail and sheet match Today |+| UI/text tests and focused iPhone/iPad/Mac verification | 2.1–2.5: existing completed appearance with minus icon, ordering, summary, accessibility, menu callbacks and preserved navigation; no Stats/Noted entry |+| Intent answers | 6.1: marked omitted, unmarked eligible, actual noted works preserved, all-marked empty dialog/list/snippet |+| Persistence, migration, backup and work lifecycle | 5.1–5.5: V16/V17 recorded stores to V18, restart, wire golden, union import in both orders, missing Work hydration, work merge/delete, schedule edits retain marks |++Use the existing Swift Testing package for generated fold tests: seeded sequences over two or three replicas, random partitions and delivery orders, comparing the folded set to a small reference model. Assert union associativity, commutativity and idempotence, clear dominance over unobserved marks, and successful re-mark after observing all clears. Exhaustively test small histories as well as generated ones; no new test framework is needed.++Run focused Core suites via `make test-core CORE_TEST=…` during implementation; then `make test-core`, `make test-quick` (includes the Mac compile), and relevant UI suites through existing Makefile targets at the phase boundary. Keep logs on disk. Actual CloudKit delivery is verified separately with two Development installs; do not launch or install Personal builds without the required at-run approval.++## Risks and Assumptions++- Risk: note-clear indexing adds measurable cost to first publication/reconcile on a large library. | Verify: compare the existing M4 Today/reconcile arms with action-bearing fixtures early in implementation. | If wrong: reuse fetched Entry buckets and cache the decoded index by publication generation; do not weaken clearing semantics or widen budgets without evidence.+- Risk: V18's added table or payload mapping behaves differently under real CloudKit hydration than host fixtures. | Verify: schema contract tests followed by two-device Development sync with opposite arrival orders. | If wrong: fix the model/mapping before enabling the feature; keep existing library rows intact.++## Sources++- [Apple: Syncing model data across devices](https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices): uniqueness constraints are unsupported; model relationships are optional under CloudKit. The action table uses value references and logical deduplication.+- [Apple: SchemaMigrationPlan](https://developer.apple.com/documentation/swiftdata/schemamigrationplan) and [schema migration session](https://developer.apple.com/videos/play/wwdc2025/291/): ordered versioned schemas and lightweight stages.+- Repository integration references: `specs/catch-up-progress/design.md`, `docs/agent-notes/schema-migration.md`, and `LibraryRepository+Groups.swift`'s bulk snapshot contract.
diff --git a/specs/no-episode-today/implementation.md b/specs/no-episode-today/implementation.mdnew file mode 100644index 00000000..14b88d90--- /dev/null+++ b/specs/no-episode-today/implementation.md@@ -0,0 +1,47 @@+# No Episode Today — implementation++## Beginner Level++### What Changed / What This Does++A reader can choose **No episode today** from a scheduled work's release menu, or **No episode on {date}** while viewing another day. The release stays visible but moves behind releases still needing attention. A minus badge distinguishes it from a release with a note. The same menu offers **Undo no episode**.++### Why It Matters++The app stops counting a known non-release as an expected episode, and the Chapters Releasing Today shortcut leaves it out. A later note for that work and day removes the mark permanently. Marks, undos, and note clears travel with the library and its backup.++### Key Concepts++A **civil day** is a calendar date rather than a timestamp, so a time-zone change cannot move the mark to the previous or next day. Each mark or clear is saved as an **action**. The app combines actions to determine whether the date is marked.++## Intermediate Level++### Changes Overview++The live SwiftData schema adds `NoEpisodeAction`. `NoEpisodeHistory` validates and folds immutable actions; `NoEpisodeIndex` groups them by work; `NoEpisodeWriter` records note clears in the same transaction as note changes. Repository mark and undo commands own write locking, eligibility checks, save failures, and refresh outcomes. The Today model passes its selected day to the action, and the release shelf renders pending, noted, and no-episode states.++### Implementation Approach++A mark stores the clear keys it has observed. An unseen clear defeats that mark, which makes a concurrent offline undo win regardless of delivery order. A later deliberate mark can acknowledge the clear and become active again. Note writes preserve stable clear evidence and add fresh evidence when a note moves into a work and day. Calendar-aware preparation reconciles notes before Today or a cold intent reads. Backups retain the complete action history and import it by union.++### Trade-offs++The action table grows until a work is deleted because an old offline device or supported backup can return later. Reads use a shared index and unchanged note scans use a store-history checkpoint to keep Today within its existing performance budget.++## Expert Level++### Technical Deep Dive++For a work and day, the fold unions explicit clear keys with clear keys referenced by marks. The date is active only if a mark acknowledges every clear in that union. Duplicate identical rows collapse by logical key; conflicting payloads are errors. Note facts use logical Entry assignments and `lastSharedAt` under the publication calendar. Targeted history reads validate only the requested work, while whole-library export and maintenance validate all actions. `TodayDayPlan.releaseCount` subtracts active marked dates that fall inside the interval and on current schedule weekdays.++### Architecture Impact++The V18 migration adds a CloudKit-compatible scalar action table and the 17/18 archive contract carries its full history. Existing note mutation, duplicate resolution, import, merge, deletion, presentation, work detail, catch-up, and intent paths now share the action model. The view never writes SwiftData directly.++### Potential Issues++Action retention has unbounded growth by design. The actor-local scan checkpoint depends on SwiftData history tokens and falls back to scanning if a token is unavailable. Host tests cover the fold, repository behavior, and performance, but real CloudKit delivery order still needs the two-device check recorded in `verification-run.md`.++## Completeness Assessment++The feature's specified storage, mark and undo behavior, note precedence, counts, Today presentation, backup, and shortcut filtering are implemented. Automated feature and app unit checks passed. The final broad Core run also passed after the concrete plain-text provider bridge and live Foundation Models error classification were fixed; see `specs/bugfixes/core-host-compatibility/report.md`. Two-device CloudKit delivery remains unverified, and a signed Mac build remains blocked by this host's `errSecInternalComponent` code-signing failure.
diff --git a/specs/no-episode-today/requirements.md b/specs/no-episode-today/requirements.mdnew file mode 100644index 00000000..967ad008--- /dev/null+++ b/specs/no-episode-today/requirements.md@@ -0,0 +1,101 @@+# Requirements: No Episode Today++Transit: T-2374++## Introduction++A scheduled work sometimes has no new episode on its usual release day. The reader needs to mark that release as dealt with without recording a note or changing the weekly schedule. The mark also prevents that date from inflating estimated unread counts.++## Non-Goals++- Detecting missed releases automatically or checking publishers' websites.+- Editing recurring schedules, adding release notifications, or recording why an episode was skipped.+- Treating a no-episode mark as a note, a read episode, or a reading-statistics event.+- A separate history or editor for marks on works no longer visible in the Releasing shelf.+- Supporting backup formats outside the build's supported version pair or guaranteeing sync with pre-feature builds.++## Definitions++- **Selected date**: the calendar date selected in Today, using its existing civil-date semantics.+- **Matching note**: a note assigned to the marked work whose noted day matches the marked date, under Today's existing noted-day rules.+- **No-episode mark**: the reader's assertion that a particular work has no release on a particular date.+- **Completed treatment**: the release shelf's existing treatment for a work noted on the selected date, including reduced cover emphasis, removal of the next-episode badge, and placement after releases needing attention.++## Relationship to Existing Specs++- Extends `update-schedule` with date-specific exceptions to its weekly schedule; supersedes its non-goal excluding missed-release tracking only to the extent of explicit no-episode marks.+- Extends `catch-up-progress` so expected-release arithmetic excludes marked dates. Confirmed latest and last-read episode numbers remain governed by that spec.+- Extends `app-intents` so Chapters Releasing Today excludes no-episode releases.+- Uses the existing Today release shelf on iPhone, iPad, and Mac as the interaction and visual baseline.++## Requirements++### 1. Mark and Undo a Release++**User Story:** As a reader, I want to mark a scheduled release as having no episode, so that it no longer asks for my attention.++**Acceptance Criteria:**++1. <a name="1.1"></a>WHEN a work appears in the selected date's Releasing section without a matching note or no-episode mark, its context menu SHALL offer an action to mark that work as having no episode on that date. +2. <a name="1.2"></a>The action SHALL apply to the selected date, whether past, current, or future; its label SHALL say `No episode today` for the current date and `No episode on {date}` otherwise. +3. <a name="1.3"></a>WHEN a release is marked, its context menu SHALL offer `Undo no episode`; invoking it SHALL clear the selected work's mark for the selected date. +4. <a name="1.4"></a>Marking or undoing SHALL leave the work's weekly schedule, other dates' marks, notes, and confirmed reading-progress values unchanged. +5. <a name="1.5"></a>IF marking or undoing cannot be saved, THEN the app SHALL report the failure and retain the last saved release state. ++### 2. Display a Marked Release++**User Story:** As a reader, I want no-episode releases to look dealt with but distinct from read releases, so that I can see what still needs attention.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHILE a work has a no-episode mark for the selected date and remains scheduled for that date, it SHALL remain on the Releasing shelf with the completed treatment and a no-episode icon distinct from the read checkmark. +2. <a name="2.2"></a>The completed group SHALL contain noted and no-episode releases together in the shelf's existing title order, after releases needing attention. +3. <a name="2.3"></a>The shelf summary SHALL count only works with matching notes as read and SHALL separately report the number marked as no episode when that number is nonzero. +4. <a name="2.4"></a>A marked release's accessibility label SHALL identify the work and state `No episode`; its mark and undo actions SHALL be available through the release's accessible context menu on iPhone, iPad, and Mac. +5. <a name="2.5"></a>Marking a release SHALL create no note and SHALL add nothing to reading statistics or the selected date's Noted section. ++### 3. Notes Clear Marks++**User Story:** As a reader, I want a real note to replace a no-episode mark, so that the shelf reflects what I recorded without extra cleanup.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN a matching note becomes available through capture, reassignment, re-share, sync, or backup import, THEN the mark for that work and date SHALL be cleared and the release SHALL receive the ordinary noted treatment. +2. <a name="3.2"></a>WHEN that note is subsequently deleted, moved to another work, or given a different noted day, THEN the cleared mark SHALL remain cleared, including when a stale copy of the cleared mark later arrives through sync or import; the reader SHALL still be able to make a new mark when no matching note exists. +3. <a name="3.3"></a>WHILE a matching note exists, the app SHALL not offer or accept a no-episode mark for that work and date; a matching note SHALL take precedence over a conflicting mark arriving from another device. +4. <a name="3.4"></a>A note for another work or another date SHALL not clear the mark. ++### 4. Expected Release Counts++**User Story:** As a reader, I want known non-releases excluded from estimates, so that the app does not count episodes that were not released.++**Acceptance Criteria:**++1. <a name="4.1"></a>WHEN estimating releases in a date interval, the app SHALL exclude each marked date that would otherwise contribute a scheduled release, once per work and date, in both catch-up progress and the `releases since` count. +2. <a name="4.2"></a>WHEN a mark is added or cleared, the affected estimates SHALL be recalculated using the remaining marks and the existing catch-up rules; marking SHALL not change confirmed latest or last-read episode numbers. +3. <a name="4.3"></a>A marked date outside the counted interval, or not on a current release weekday, SHALL have no effect on that interval's count. ++### 5. Persistence and Sync++**User Story:** As a reader, I want marks and their removal to follow my library, so that all my devices agree about skipped releases.++**Acceptance Criteria:**++1. <a name="5.1"></a>Marks and their removal SHALL survive app restarts and sync between devices; after the same changes arrive, devices showing the same date with the same calendar context SHALL agree on the no-episode state and affected counts. +2. <a name="5.2"></a>Marking or undoing one work and date SHALL preserve independently changed marks for other works and dates when synced. +3. <a name="5.3"></a>A mark SHALL retain its selected civil date when the device's time zone changes; it SHALL not move to the adjacent date. +4. <a name="5.4"></a>Changing a work's schedule or statuses SHALL retain its marks, applying them only where the existing schedule and status rules make them relevant; deleting the work SHALL remove its marks. +5. <a name="5.5"></a>Backup export and restore between supported builds SHALL preserve no-episode state; updating an existing library SHALL leave works without marks behaving as before. +6. <a name="5.6"></a>WHEN devices independently mark and undo the same work and date without seeing each other's changes, THEN synchronization SHALL resolve the conflict to unmarked regardless of arrival order; a deliberate new mark made after observing the cleared state SHALL be allowed when no matching note exists. ++### 6. Chapters Releasing Today Shortcut++**User Story:** As a reader, I want the release shortcut to omit known non-releases, so that its answer reflects the episodes I can expect.++**Acceptance Criteria:**++1. <a name="6.1"></a>The Chapters Releasing Today shortcut SHALL omit works marked as having no episode on the date it answers for, while preserving its existing behavior for other works; clearing a mark SHALL restore the work's eligibility under the shortcut's existing rules. ++## Review Status++Approved by the owner on 2026-09-28, including the separate summary count, adjusted `releases since` count, and undo through visible release rows only. Design-critic review and validation by two independent local peers found no material issues; local peers were used because external review tools were unavailable.
diff --git a/specs/no-episode-today/tasks.md b/specs/no-episode-today/tasks.mdnew file mode 100644index 00000000..ccf98003--- /dev/null+++ b/specs/no-episode-today/tasks.md@@ -0,0 +1,158 @@+---+references:+ - specs/no-episode-today/requirements.md+ - specs/no-episode-today/design.md+ - specs/no-episode-today/decision_log.md+---+# No Episode Today — Implementation Tasks++## Core storage and behavior++- [x] 1. Write history-fold and wire-value tests <!-- id:ou5icxp -->+ - Add NoEpisodeHistoryTests in AsterismCoreTests: clear dominance, deliberate re-mark, missing referenced-clear rows, logical duplicates, invalid versions/dates/keys, conflicting payloads, and canonical round trips.+ - Use Swift Testing with exhaustive small histories and seeded two-/three-replica generators; compare against a reference model under partitions, reordered delivery and duplicate delivery. Assert union associativity, commutativity and idempotence.+ - Keep work/date scopes separate and test Gregorian civil dates under DST and non-Gregorian display calendars. Run focused make test-core CORE_TEST=NoEpisodeHistoryTests; demonstrate the missing behavior before implementation.+ - Stream: 1+ - Requirements: [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.6](requirements.md#5.6)+ - References: design.md, decision_log.md++- [x] 2. Implement the pure action history and remove-wins fold <!-- id:ou5icxq -->+ - Create NoEpisodeHistory.swift with versioned immutable payloads, canonical encoding, validation, scoped unions and active-date derivation as defined in design.md. Marks acknowledge all known clear keys; references count as clear evidence before their rows arrive.+ - Use no clock or storage access. Make task 1 green; these values are consumed by persistence in tasks 3–4, not shipped as a separate unused subsystem.+ - Blocked-by: ou5icxp (Write history-fold and wire-value tests)+ - Stream: 1+ - Requirements: [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.6](requirements.md#5.6)+ - References: design.md, decision_log.md++- [x] 3. Write V18 storage, migration and archive contract tests <!-- id:ou5icxr -->+ - Extend model/marker contracts and add V16/V17 recorded-store conversions to V18, with seed containers released before migration. Verify preservation of existing fields, empty initial action table, app markers 16/17/18 and extension marker 18 only.+ - Add action-table tests for duplicate physical rows, restart, missing Work hydration, strict payload failure, and logical-key conflicts. Add format-17/schema-18 golden and checksum tests, malformed-action rejection before live writes, and unsupported-envelope rejection.+ - Exercise archive union in both orders, retained clears/acknowledgements, repeat import as no-op, and stale supported-format archives after a clear. Schema/CloudKit compatibility contracts are the early guard for the design’s model-mapping risk.+ - Blocked-by: ou5icxq (Implement the pure action history and remove-wins fold)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6)+ - References: design.md, decision_log.md++- [x] 4. Implement V18 action storage and the 17/18 archive path <!-- id:ou5icxs -->+ - Freeze V17 exactly, retain V16 and its migration stage, add nested NoEpisodeAction and V18 typealiases, and register the schema in bootstrap, scratch import, empty-library reset and all schema enumerations. Update store digests and model/marker validation; add no relationship or uniqueness constraint.+ - Implement NoEpisodeIndex and the insertion/validation part of NoEpisodeWriter. Replace the supported archive pair with 17/18 across codecs/types/exporter, projection/builders, importer/version gates, reference checks and golden fixtures. Union logical actions before note imports without Work.modifiedAt guards; retain dangling Work references.+ - Land schema and archive wiring together so envelope/live-schema contracts are not left mismatched. Make task 3 green with focused Core suites before any downstream task; keep action writes internal until the commands and note hooks are integrated.+ - Blocked-by: ou5icxr (Write V18 storage, migration and archive contract tests)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6)+ - References: design.md, decision_log.md++- [x] 5. Write mark-command and local note-lifetime regressions <!-- id:ou5icxt -->+ - Add repository tests for past/current/future dates, concurrent independent dates, already-marked/unmarked retries, matching-note refusal, changed schedule/status, torn groups, and injected save failure. Assert unchanged Work metadata, progress values, Stats and Noted content.+ - Test real capture/update/delete/move/re-share entry points, including drained re-share. Cover note deletion before an offline mark arrives and move away → mark → move back → delete; the mark must stay cleared. Ordinary text edits create no fresh occurrence.+ - Assert before/after clears and the note mutation roll back together. Inject one calendar per commit and verify cross-date/work isolation and civil-date stability.+ - Blocked-by: ou5icxs (Implement V18 action storage and the 17/18 archive path)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.6](requirements.md#5.6)+ - References: design.md, decision_log.md++- [x] 6. Implement commands and atomic clearing in local note writes <!-- id:ou5icxu -->+ - Implement LibraryRepository+NoEpisode mark/undo/preparation APIs and LibraryProviding forwarding/test doubles. Add the repository calendar dependency through app and share-extension factories. Keep lock, eligibility recheck, rollback and LibraryWriteOutcome semantics at the repository boundary.+ - Complete NoEpisodeWriter with stable note keys, fresh clears for actual destination arrivals even without visible marks, and overlap clearing before removal. Helpers mutate the caller’s context and never save independently.+ - Wire LibraryRepository capture/updateEntry/deleteEntry/moveEntry and LibraryRepository+Capture commitReShareUpdate/recordDrainedReShare. Keep projections and drafts read-only; make task 5 green.+ - Blocked-by: ou5icxt (Write mark-command and local note-lifetime regressions)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.6](requirements.md#5.6)+ - References: design.md, decision_log.md++- [x] 7. Write reconciliation, bulk-note and work-lifecycle regressions <!-- id:ou5icxv -->+ - Cover commitCapture/commitReparse, composed teaching, Entry duplicate resolution/collapse/detachment, accepted backup note restoration, and Work merge/collapse/resolution/deletion using their real commit APIs.+ - Add repeated restore/reattachment cases where the mark already acknowledges the stable note key. Exercise both arrival/full reconciliation tiers, fresh overlap clears, no-op repeated reconciliation/import, conflicting offline actions and clear rows arriving after their references.+ - Assert merge preserves action keys and acknowledgements, work deletion removes history, status/schedule changes retain history, missing Work hydration never deletes it, and refused operations roll back note and action changes together.+ - Blocked-by: ou5icxu (Implement commands and atomic clearing in local note writes)+ - Stream: 1+ - Requirements: [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6)+ - References: design.md, decision_log.md++- [x] 8. Integrate clearing with import, reconciliation and work lifecycle <!-- id:ou5icxw -->+ - Wire LibraryRepository+ReparseCapture, +ComposedTeaching, +DuplicateResolution, DuplicateReconciler and +ConfirmImport accepted Entry changes to the same before/after hook. Rejected or no-op imports must not manufacture new arrivals; scratch preview changes stay isolated.+ - Add the idempotent note-clear/validation phase to reconcileAfterSync on both tiers and report writes through ReconciliationOutcome. Fold stable evidence first, then append a fresh clear only for a remaining live-note/active-mark overlap.+ - Wire action reassignment/union into +WorkMerge, Work duplicate collapse/resolution and action removal into +WorkDeletion/empty-library reset. Make task 7 green before read/UI integration.+ - Blocked-by: ou5icxv (Write reconciliation, bulk-note and work-lifecycle regressions)+ - Stream: 1+ - Requirements: [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6)+ - References: design.md, decision_log.md++- [x] 9. Write snapshot, release-count and scale regression tests <!-- id:ou5icxx -->+ - Extend TodayDayPlan, TodaySchedule, CatchUpProgress and repository snapshot tests: interval endpoints, unscheduled/out-of-range/duplicate dates, count-up off, both expected-latest bounds, unknown releases-since, and notes taking precedence.+ - Assert parity across the fast Today publication, work/detail snapshots, Set latest sheet and WorkDetailView inputs. Keep isNotedOnDay note-only and distinguish pending/noted/noEpisode from catch-up progress state.+ - Extend existing M4 Today/reconcile automated performance cases with action-bearing fixtures and unchanged-reconcile assertions. Exercise first publication and large histories using existing budgets; this is the early indexing-risk gate, before app/UI tasks.+ - Blocked-by: ou5icxw (Integrate clearing with import, reconciliation and work lifecycle)+ - Stream: 1+ - Requirements: [2.1](requirements.md#2.1), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [5.1](requirements.md#5.1), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+ - References: design.md, decision_log.md++- [x] 10. Wire indexed history into all reads and release calculations <!-- id:ou5icxy -->+ - Update WorkSnapshot, every group-snapshot overload/caller in LibraryRepository and +Groups, +TodayPresentation.todaySchedule, +WorkDetail and +CatchUpProgress. Fetch/bucket action history once per bulk read; no default-empty history in production or Work inverse traversal.+ - Carry active dates through ScheduledWork/TodaySchedule, add ReleaseRow releaseState/isCompleted, and subtract only marked scheduled dates in (start, end] from the existing arithmetic. Update both CatchUpProgress bounds, releases-since, sheet and WorkDetailView callers without changing confirmed values.+ - Update Today/M4 fixtures through shared helpers and make task 9 green. Resolve measured indexing regressions before downstream tasks by reusing buckets and, if needed, a publication-generation cache as designed; do not widen budgets or repeat unaffected suites.+ - Blocked-by: ou5icxx (Write snapshot, release-count and scale regression tests)+ - Stream: 1+ - Requirements: [2.1](requirements.md#2.1), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [5.1](requirements.md#5.1), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+ - References: design.md, decision_log.md++## App integration and verification++- [x] 11. Write app publication and cold-intent preparation tests <!-- id:ou5icxz -->+ - Extend AppLibraryModel and IntentLibraryBroker tests for startup, refreshAll, calendar changes and cold intent preparation: prepare then read with one captured calendar, stale CalendarKey cycles discarded, and no writes inside presentation reads.+ - Cover a previously acknowledged note key overlapping a mark, preparation save failure, last published state preservation, and a time-zone change followed by note removal. Use injected calendars and repository spies without launching a Personal build.+ - Blocked-by: ou5icxy (Wire indexed history into all reads and release calculations)+ - Stream: 1+ - Requirements: [1.5](requirements.md#1.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [5.1](requirements.md#5.1), [5.3](requirements.md#5.3)+ - References: design.md, decision_log.md++- [x] 12. Integrate calendar-aware preparation into app and intent reads <!-- id:ou5icy0 -->+ - Wire prepareNoEpisodeNotes into AppLibraryModel.publishToday/refreshAll/calendar handling and cold IntentLibraryBroker preparation before publication. Preserve existing generation gates, library lifecycle and error surfaces.+ - Use the cycle’s captured calendar and idempotent preparation; do not move writes into Today views, todayPresentation or projections. Make task 11 green and retain the launch path’s independence from works().+ - Blocked-by: ou5icxz (Write app publication and cold-intent preparation tests)+ - Stream: 1+ - Requirements: [1.5](requirements.md#1.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [5.1](requirements.md#5.1), [5.3](requirements.md#5.3)+ - References: design.md, decision_log.md++- [x] 13. Write release-shelf action, presentation and accessibility tests <!-- id:ou5icy1 -->+ - Extend TodayShelfTextTests/TodayDisplayPlanTests and AppLibraryModel mutation tests for title-stable pending/completed ordering, read-only read count plus no-episode count, minus/checkmark distinction, and accessible labels.+ - Add focused Today UI regressions for mark/undo, selected date captured at tap, repeated taps disabled, note auto-clear, and preserved Open Work Page/Go to Work actions. Cover iPhone and wide-layout context menus using the existing seeded UI infrastructure.+ - Exercise save failure versus successful-save/refresh-failure separately; assert no synthetic note or Stats entry and updated estimates after refresh.+ - Blocked-by: ou5icy0 (Integrate calendar-aware preparation into app and intent reads)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [4.2](requirements.md#4.2)+ - References: design.md, decision_log.md++- [x] 14. Implement release-shelf marking and completed presentation <!-- id:ou5icy2 -->+ - Wire TodayView → ReleaseShelf → ReleaseShelfItem callbacks through AppLibraryModel to the repository; capture selected date, disable in-flight actions and reuse existing refusal/alert handling and post-commit refresh.+ - Update ReleaseShelfText and the cover using the existing completed styling, minus badge, note-only read count and separate no-episode count. Retain title order within pending/completed partitions, menu navigation and accessible action names.+ - Make task 13 green on focused simulator suites and compile the Mac path via the Makefile; no new editor or history UI.+ - Blocked-by: ou5icy1 (Write release-shelf action, presentation and accessibility tests)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [4.2](requirements.md#4.2)+ - References: design.md, decision_log.md++- [x] 15. Write shortcut output and empty-result regression tests <!-- id:ou5icy3 -->+ - Extend IntentAnswersTests and existing intent-result tests for mixed marked/pending/noted works, mark clearing, all-marked results, and cold prepared reads.+ - Assert filtering precedes dialog, snippet and WorkEntity creation; actual noted works retain existing shortcut eligibility.+ - Blocked-by: ou5icy2 (Implement release-shelf marking and completed presentation)+ - Stream: 1+ - Requirements: [6.1](requirements.md#6.1), [3.1](requirements.md#3.1), [3.3](requirements.md#3.3)+ - References: design.md, decision_log.md++- [x] 16. Filter no-episode releases from shortcut answers <!-- id:ou5icy4 -->+ - Update IntentAnswers.releasingToday to omit releaseState.noEpisode before mapping ReleaseAnswer. Wire or adjust ChaptersReleasingTodayIntent only where needed so all output forms share that answer.+ - Make task 15 green with existing empty-result handling and ordering preserved; avoid a second independent schedule calculation.+ - Blocked-by: ou5icy3 (Write shortcut output and empty-result regression tests)+ - Stream: 1+ - Requirements: [6.1](requirements.md#6.1), [3.1](requirements.md#3.1), [3.3](requirements.md#3.3)+ - References: design.md, decision_log.md++- [x] 17. Run integrated feature tests and required build gates <!-- id:ou5icy5 -->+ - Run make test-core, make test-quick (including Mac compile), focused Today/intent simulator checks through make test-only, relevant wide-layout checks through existing Makefile targets, and required linters/validators. Reuse passing task-10 performance evidence unless later changes invalidate it.+ - Use run_silent and retain full logs on disk; one owner per run. Keep feature failures separate from inherited failures and return to the relevant red/green pair for fixes.+ - Host tests cannot establish real CloudKit delivery. Keep the design’s two-Development-device verification outstanding until it is actually performed; no Personal install/run is authorized by this task list.+ - Blocked-by: ou5icy4 (Filter no-episode releases from shortcut answers)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [6.1](requirements.md#6.1)+ - References: design.md, decision_log.md
diff --git a/specs/no-episode-today/verification-run.md b/specs/no-episode-today/verification-run.mdnew file mode 100644index 00000000..2ffa89f2--- /dev/null+++ b/specs/no-episode-today/verification-run.md@@ -0,0 +1,25 @@+# No Episode Today — verification run++Date: 2026-09-29. Branch: `T-2374/no-episode-today`.++## Automated checks++| Check | Result |+|---|---|+| `make test-core` | Passed. Includes the no-episode repository and shortcut answer tests. |+| `make test-quick SKIP_MAC=1` | Passed after updating existing app call-order expectations for the new preparation step. |+| `make test-only TEST=AsterismTests/AppLibraryModelSnapshotPublicationTests` | Passed: captured calendar, preparation failure, mark/undo write and refresh outcomes. |+| `make test-only TEST=AsterismTests/IntentLibraryBrokerTests` | Passed again after review fixes: a cold preparation followed by a failed read still leaves ExportOwed; a preparation failure leaves no marker. |+| `make test-only TEST=AsterismTests/TodayShelfTextTests` | Passed again after review fixes: past/current/future menu labels, completed ordering, separate read/no-episode counts, badge and accessible words. |+| `make test-only TEST=AsterismUITests/TodayUITests/testNoEpisodeShelfMenusMarkUndoAndKeepWorkNavigation` | Passed on iPhone 18 Pro simulator. Covers mark, undo, summary, Open Work Page and Go to Work. |+| `make test-only TEST=AsterismUITests/TodayUITests/testNoEpisodeActionAndLabelAtAccessibilitySize` | Passed on iPhone 18 Pro simulator at accessibility XXXL. Covers the vertical fallback's no-episode label and mark menu, including a marked row below the lazy List fold. |+| `make test-only SIMULATOR='iPad Pro 11-inch (M5)' TEST=AsterismUITests/WideLayoutUITests/testNoEpisodeMenuWorksBesideWideDetailColumn` | Passed on iPad simulator. |+| `make verify-identity` | Passed. No style linter or formatter is configured. |++The full `make test-quick` prerequisite and standalone `make build-mac` both stopped at CodeSign for `AsterismShareExtensionMac.debug.dylib`, the same host signing failure seen before this phase. The raw Makefile log identifies `errSecInternalComponent` from `/usr/bin/codesign` using the configured development certificate. A `make build-mac` attempt with `CODE_SIGNING_ALLOWED=NO` reached the identity script, which correctly rejected the absent processed entitlements. An ad-hoc signing override was rejected because the app and extension entitlements require a development certificate. Swift compilation and linking reached the signing point, but a clean signed Mac build remains unverified on this host.++Task 10's passing host performance evidence remains applicable: the app changes do not alter its measured Core read or reconcile paths. Its Today read measured 1.07–1.09 s against 2 s, unchanged reconciliation 27–28 ms against 100 ms, and the valid target exited 0. No Personal build was installed or launched.++## Still to verify on devices++Two Development devices need a real CloudKit delivery check: mark while offline on one, undo on the other, sync in both arrival orders, and confirm unmarked wins; then verify a note arriving at the marked work/date permanently clears it after the note is removed. Host tests cover the fold and repository behavior, but cannot prove CloudKit delivery or this device-level outcome.
The final Core run exited 0 with 3,293 passed, 55 skipped, and zero failed test declarations. The JUnit input is converted from the captured Swift Testing text output, with one row per reported test.
The two-device offline mark/undo and note-arrival checks in verification-run.md remain open; host tests cannot prove CloudKit delivery order.
The Mac target previously reached code signing but this host returned errSecInternalComponent. The final app unit run used the documented SKIP_MAC=1 escape hatch.