asterism commits 14 reviewed files 195 touched

Pre-push review: T-2375/hiatus-end-date

Save-day hiatus boundaries, announced returns and pause-aware release estimates.

At a glance

  • Read-only return resolution preserves authored fingerprints.
  • Earlier releases and gaps survive new hiatus saves.
  • Two-device offline-return/date-sync verification remains pending before merge.

Verdict

Ready to push

No actionable automated findings across reuse, quality, efficiency and spec reviews. Core verification passed. Two-Development-device verification remains required before merge.

Review findings

1 raised · 0 fixed · 1 skipped

Jump to findings →

Tests

Pass rate: 100% (3338 of 3338)

New tests: 60

Diff coverage: 95% (6463 of 6785 added lines)

Jump to tests →

Commits

Three-level explanation

What Changed A work on hiatus can have an announced return date. The Status editor saves, changes or removes it with the other work edits. Cancel and failed Save retain the existing behavior.

Why It Matters Today can show expected releases after the return, and chapter estimates omit paused days. Saving a new hiatus today preserves yesterday's releases. Return follows the normal weekdays and never creates an extra release.

Key Concepts The authored status records the reader's choice. Effective status answers whether the work is ongoing on a particular calendar day. Pause intervals retain the days excluded from estimates, even after the visible return date disappears.

Changes Overview `WorkPublicationState` stores authored status, closed pauses and an optional current pause. V19 adds one optional Work attribute; archive 18/19 preserves the complete value. Existing V16–V18 upgrades remain supported.

Implementation Approach `WorkPublicationWriter` stages explicit publication edits inside `LibraryRepository.updateWork`'s existing transaction with one captured clock/calendar. `WorkMetadataDraft.publicationEdit` distinguishes unchanged metadata saves from publication edits. Current and selected days flow explicitly to status, Today, shortcuts and catch-up calculations. Work Detail retains an editor basis and drafts across refresh.

Trade-offs Read-only expiry works without background execution or main-app launch. The whole envelope follows the selected authored carrier through copies and merges. Completed pauses consume growing per-work history but preserve estimates across repeated hiatuses; the reader does not edit that history.

Technical Deep Dive Pauses use half-open civil-day intervals [start, return); a successfully saved new hiatus captures its start once. Canonical Gregorian date strings preserve calendar identity across zones. Whole-week release counting subtracts disjoint pause intersections, then no-episode marks outside pauses; membership uses binary search over closed intervals. Same-day pause/return contributes no excluded interval. Unknown-start legacy pauses preserve their paused baseline.

Architecture Impact Authored fingerprints remain stable across midnight. Snapshot presentation resolves effective status while persistence, duplicate selection, merge and backup retain the authored envelope. Status/date-only edits preserve independently elected catch-up confirmation and override bytes. Schedule and finished-status changes retain explicit rebasing rules.

Potential Issues Concurrent offline schedule rebases retain the existing independent-confirmation limitation (Q13). Backward-clock authoring inside retained closed pause evidence retains its documented refusal. The two-Development-device offline-return/date-sync check remains a before-merge prerequisite; automated and phone-only evidence cannot establish it.

Important changes — detailed

Publication state resolves civil-day pauses

Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift

Why it matters. Retain historical releases and count only eligible weekdays.

What to look at. status(on:), excludingPauses

Takeaway. Half-open intervals make the return day eligible.
Rationale. Decision 1 and Q17: explicit-day reads avoid background writes and retroactive exclusion.

Atomic edits retain catch-up bounds

Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift

Why it matters. Save-day boundaries and authored metadata commit together.

What to look at. updateWork

Takeaway. Separate unchanged intent from explicit publication edits.
Rationale. Decision 3: retain confirmation/read bounds so return-day accrual is not suppressed.

Today shares selected-day eligibility

Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift

Why it matters. Historical and projected rows agree with shortcut and no-episode commands.

What to look at. TodaySchedule.admits/isReleaseEligible

Takeaway. Candidate membership is broader than one day’s eligibility.
Rationale. Q8 and Q17: project future returns while preserving earlier releases.

Editor preserves drafts through day refresh

Asterism/Asterism/ViewModels/WorkDetailModel.swift

Why it matters. Return expiry does not overwrite unrelated draft changes.

What to look at. seedPublicationDraft, publicationEdit, load

Takeaway. Keep authored edit bases independent from presentation time.
Rationale. Decision 1: passing time cannot become a content conflict.

V19/archive preserve the selected envelope

Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift

Why it matters. Existing libraries and supported backups carry coherent authored pause evidence.

What to look at. schemas and stages

Takeaway. Copy one complete value with its carrier.
Rationale. Decision 2 and Q12: avoid partial status/date delivery and retain approved migration stages.

Key decisions

Read-only expiry

Decision 1: status resolves from an explicit day without a transition write.

One authored envelope

Decision 2: select publication history with its content carrier.

Preserve estimate bounds

Decision 3: publication-only edits preserve confirmation and override values.

Review findings

SeverityAreaFindingResolution
minorCivilDateCodec.spellingFormatter duplicates CivilDay.description’s spelling.Skipped: small stable codec boundary; no material benefit from changing it.

Tests

Source: local run at 2026-10-01T12:48:28.275633+10:00 · snapshot d414b18aefda958e507de3983e632a6e1637686a

Baseline: none

Execution: passed · JUnit: 1 file · Coverage: 1 file · Baseline: absent

Coverage scope: as the project configures it

Totals: 3338 passed · 0 failed · 55 skipped · 0 errored · 0 flaky

New and removed tests

Derived by declaration name, from the diff (no baseline run).

Diff coverage

FileAdded linesCoveredDiff coverage
Asterism/Asterism/ContentView.swift2—no coverage data
Asterism/Asterism/Intents/AddPageToReadFlow.swift2—no coverage data
Asterism/Asterism/Localizable.xcstrings22—no coverage data
Asterism/Asterism/Support/PublicationPresentation.swift14—no coverage data
Asterism/Asterism/UITestLaunchSupport.swift9—no coverage data
Asterism/Asterism/ViewModels/AppLibraryModel.swift67—no coverage data
Asterism/Asterism/ViewModels/SettingsBackupModel.swift11—no coverage data
Asterism/Asterism/ViewModels/WorkDetailModel.swift93—no coverage data
Asterism/Asterism/ViewModels/WorksListOptions.swift10—no coverage data
Asterism/Asterism/Views/DuplicateResolutionView.swift8—no coverage data
Asterism/Asterism/Views/WorkDetailView.swift89—no coverage data
Asterism/Asterism/Views/WorkMergeView.swift8—no coverage data
Asterism/Asterism/Views/WorksGroupView.swift2—no coverage data
Asterism/Asterism/Views/WorksView.swift24—no coverage data
Asterism/AsterismTests/BackupExportStageTests.swift16—no coverage data
Asterism/AsterismTests/DuplicateSurfaceTests.swift3—no coverage data
Asterism/AsterismTests/EmptyLibraryModelTests.swift6—no coverage data
Asterism/AsterismTests/Helpers/TestFixtures.swift2—no coverage data
Asterism/AsterismTests/IntegrationSafetyNetTests.swift18—no coverage data
Asterism/AsterismTests/PublicationEditorTests.swift164—no coverage data
Asterism/AsterismTests/PublicationPresentationTests.swift59—no coverage data
Asterism/AsterismTests/SettingsBackupModelTests.swift16—no coverage data
Asterism/AsterismTests/SettingsImportTests.swift5—no coverage data
Asterism/AsterismTests/TodayFixtureSeedingTests.swift13—no coverage data
Asterism/AsterismTests/WorkDetailModelTests.swift5—no coverage data
Asterism/AsterismTests/WorkMergeModelTests.swift5—no coverage data
Asterism/AsterismTests/WorkStatusPresentationTests.swift1—no coverage data
Asterism/AsterismTests/WorksListOptionsTests.swift37—no coverage data
Asterism/AsterismTests/WorksRedesignTests.swift3—no coverage data
Asterism/AsterismTests/WorksRowPresentationTests.swift11—no coverage data
Asterism/AsterismUITests/PublicationReturnDateUITests.swift268—no coverage data
Asterism/AsterismUITests/TodayUITests.swift10—no coverage data
CHANGELOG.md42—no coverage data
CLAUDE.md4—no coverage data
Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift2116100%
Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swift2—no coverage data
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift1—no coverage data
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18Models.swift2951914%
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift4223100%
Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift796092%
Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift25—no coverage data
Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swift1—no coverage data
Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift21100%
Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swift6—no coverage data
Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift4—no coverage data
Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swift4—no coverage data
Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift423100%
Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swift2—no coverage data
Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swift30817391%
Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swift48129095%
Packages/AsterismCore/Sources/AsterismCore/BackupV18Types.swift108025588%
Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift119100%
Packages/AsterismCore/Sources/AsterismCore/CivilDateCodec.swift2317100%
Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift1313100%
Packages/AsterismCore/Sources/AsterismCore/DuplicateResolution.swift62100%
Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift1—no coverage data
Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift127100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift11100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift11100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift2715100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift2513100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift1515100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift11100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift77100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift1614100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift44100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift11100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift22100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift6467%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift312997%
Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift96100%
Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swift1—no coverage data
Packages/AsterismCore/Sources/AsterismCore/Models.swift261100%
Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift32100%
Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift135100%
Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift44100%
Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift51100%
Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift168100%
Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift100%
Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift4332100%
Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift1614100%
Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift170114100%
Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swift5738100%
Packages/AsterismCore/Sources/AsterismCore/WorkVariantUnion.swift149100%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift4747100%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift9995100%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swift3737100%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swift1716100%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift211990%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift4008295999%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18Fixtures.swift113653290%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift22115193%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18RestoreAssertions.swift5639100%
Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift44100%
Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift65100%
Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift1—no coverage data
Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift4038100%
Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift98100%
Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift1—no coverage data
Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swift32100%
Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift1515100%
Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift44100%
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift3129100%
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift1212100%
Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swift44100%
Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift77100%
Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swift400%
Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-17-18-golden.json0—no coverage data
Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-18-19-golden.json1—no coverage data
Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift2322100%
Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift33100%
Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift55100%
Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swift200%
Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swift600%
Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift66100%
Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift77100%
Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swift500%
Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift33100%
Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift3331100%
Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift33100%
Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swift77100%
Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swift33100%
Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift2222100%
Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift66100%
Packages/AsterismCore/Tests/AsterismCoreTests/PublicationArchiveTests.swift131108100%
Packages/AsterismCore/Tests/AsterismCoreTests/PublicationProgressTests.swift10184100%
Packages/AsterismCore/Tests/AsterismCoreTests/PublicationScheduleTests.swift130114100%
Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swift21100%
Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift66100%
Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift1212100%
Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift1—no coverage data
Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift33100%
Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift1515100%
Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift76100%
Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift44100%
Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift9479100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift33100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift88100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift3027100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationMergeTests.swift645096%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationProjectionTests.swift131109100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationStateTests.swift156137100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationValidationTests.swift2112100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationWriterTests.swift274232100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkSnapshotMembershipTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift22100%
Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift66100%
Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift55100%
Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swift98100%
Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift22100%
docs/agent-notes/device-installation.md14—no coverage data
specs/OVERVIEW.md15—no coverage data
specs/hiatus-end-date/decision_log.md115—no coverage data
specs/hiatus-end-date/design.md166—no coverage data
specs/hiatus-end-date/prerequisites.md32—no coverage data
specs/hiatus-end-date/requirements.md98—no coverage data
specs/hiatus-end-date/tasks.md211—no coverage data
specs/hiatus-end-date/verification-run.md95—no coverage data
specs/hiatus-end-date/implementation.md46—no coverage data

Aggregate diff coverage: 95% (6463 of 6785 measurable added lines).

Overall coverage

Head 93.6% (108074 of 115414 lines)

150 of 195 changed files matched coverage data.

Blast radius

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 87b9283c94b867ea843b3b2389aa645abd4bcf74.

Dependents none found Changed Dependencies none found Asterism/Asterism Asterism/Asterism/Intents Asterism/Asterism/Support Asterism/Asterism/ViewModels Asterism/Asterism/Views Asterism/AsterismTests Asterism/AsterismTests/Helpers Asterism/AsterismUITests …rismCore/Sources/AsterismCore …urces/AsterismCore/Thumbnails …mCore/Tests/AsterismCoreTests Asterism/Asterism/ContentView.swift…sm/Asterism/ContentView.swift Asterism/Asterism/Localizable.xcstrings…sterism/Localizable.xcstrings Asterism/Asterism/UITestLaunchSupport.swift…ism/UITestLaunchSupport.swift Asterism/Asterism/Intents/AddPageToReadFlow.swift…tents/AddPageToReadFlow.swift Asterism/Asterism/Support/PublicationPresentation.swift…PublicationPresentation.swift Asterism/Asterism/ViewModels/AppLibraryModel.swift…wModels/AppLibraryModel.swift Asterism/Asterism/ViewModels/SettingsBackupModel.swift…els/SettingsBackupModel.swift Asterism/Asterism/ViewModels/WorkDetailModel.swift…wModels/WorkDetailModel.swift Asterism/Asterism/ViewModels/WorksListOptions.swift…Models/WorksListOptions.swift Asterism/Asterism/Views/DuplicateResolutionView.swift…DuplicateResolutionView.swift Asterism/Asterism/Views/WorkDetailView.swift…sm/Views/WorkDetailView.swift Asterism/Asterism/Views/WorkMergeView.swift…ism/Views/WorkMergeView.swift Asterism/Asterism/Views/WorksGroupView.swift…sm/Views/WorksGroupView.swift Asterism/Asterism/Views/WorksView.swift…sterism/Views/WorksView.swift Asterism/AsterismTests/BackupExportStageTests.swift…/BackupExportStageTests.swift Asterism/AsterismTests/DuplicateSurfaceTests.swift…s/DuplicateSurfaceTests.swift Asterism/AsterismTests/EmptyLibraryModelTests.swift…/EmptyLibraryModelTests.swift Asterism/AsterismTests/IntegrationSafetyNetTests.swift…tegrationSafetyNetTests.swift Asterism/AsterismTests/PublicationEditorTests.swift…/PublicationEditorTests.swift Asterism/AsterismTests/PublicationPresentationTests.swift…cationPresentationTests.swift Asterism/AsterismTests/SettingsBackupModelTests.swift…ettingsBackupModelTests.swift Asterism/AsterismTests/SettingsImportTests.swift…sts/SettingsImportTests.swift Asterism/AsterismTests/TodayFixtureSeedingTests.swift…odayFixtureSeedingTests.swift Asterism/AsterismTests/WorkDetailModelTests.swift…ts/WorkDetailModelTests.swift Asterism/AsterismTests/WorkMergeModelTests.swift…sts/WorkMergeModelTests.swift Asterism/AsterismTests/WorkStatusPresentationTests.swift…StatusPresentationTests.swift Asterism/AsterismTests/WorksListOptionsTests.swift…s/WorksListOptionsTests.swift Asterism/AsterismTests/WorksRedesignTests.swift…ests/WorksRedesignTests.swift Asterism/AsterismTests/WorksRowPresentationTests.swift…rksRowPresentationTests.swift Asterism/AsterismTests/Helpers/TestFixtures.swift…ts/Helpers/TestFixtures.swift Asterism/AsterismUITests/PublicationReturnDateUITests.swift…cationReturnDateUITests.swift Asterism/AsterismUITests/TodayUITests.swift…ismUITests/TodayUITests.swift Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift…e/ArchiveRecordBuilders.swift Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swift…re/AsterismCapabilities.swift Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift…mCore/AsterismSchemaV18.swift Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18Models.swift…AsterismSchemaV18Models.swift Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift…mCore/AsterismSchemaV19.swift Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift…BackupArchiveProjection.swift Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift…pArchiveReferenceChecks.swift Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swift…rismCore/BackupExporter.swift Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift…e/BackupGroupProjection.swift Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swift…re/BackupImportCreators.swift Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift…ore/BackupImportRecords.swift Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swift…e/BackupImportWorkTypes.swift Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift…rismCore/BackupImporter.swift Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swift…/BackupJSONCodecSupport.swift Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swift…rismCore/BackupV18Codec.swift Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swift…mCore/BackupV18Exporter.swift Packages/AsterismCore/Sources/AsterismCore/BackupV18Types.swift…rismCore/BackupV18Types.swift Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift…ismCore/CatchUpProgress.swift Packages/AsterismCore/Sources/AsterismCore/CivilDateCodec.swift…rismCore/CivilDateCodec.swift Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift…ore/DuplicateReconciler.swift Packages/AsterismCore/Sources/AsterismCore/DuplicateResolution.swift…ore/DuplicateResolution.swift Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift…rismCore/EntryCitations.swift Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift…erismCore/GroupOrdering.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift…Repository+BackupImport.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift…itory+BackupImportGates.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift…aryRepository+Bootstrap.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift…epository+ConfirmImport.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift…ory+DuplicateResolution.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift…ibraryRepository+Export.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift…ibraryRepository+Groups.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift…braryRepository+Intents.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift…aryRepository+NoEpisode.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift…raryRepository+Redirect.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift…itory+TodayPresentation.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift…aryRepository+WorkMerge.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift…mCore/LibraryRepository.swift Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift…erismCore/LibraryWrites.swift Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swift…re/MembershipReconciler.swift Packages/AsterismCore/Sources/AsterismCore/Models.swift…ces/AsterismCore/Models.swift Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift…smCore/NoEpisodeHistory.swift Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift…Core/ProjectionContract.swift Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift…/AsterismCore/RecordRow.swift Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift…smCore/RepositoryDrafts.swift Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift…/AsterismCore/Snapshots.swift Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift…terismCore/TodayDayPlan.swift Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift…smCore/WorkMergePlanner.swift Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift…re/WorkPublicationState.swift Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swift…e/WorkPublicationWriter.swift Packages/AsterismCore/Sources/AsterismCore/WorkVariantUnion.swift…smCore/WorkVariantUnion.swift Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift…ails/CoveredWorkFixture.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift…ortDegradedRefusalTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift…BackupGoldenExportTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swift…kupGroupProjectionTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swift…ckupGroupRoundTripTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift…pImportTransactionTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift…s/BackupV18ArchiveTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18Fixtures.swift…Tests/BackupV18Fixtures.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift…kupV18ImportMatrixTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18RestoreAssertions.swift…kupV18RestoreAssertions.swift Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift…ts/BootstrapActionTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift…ootstrapClassifierTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift…strapStateCoverageTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift…sts/CatchUpArchiveTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift…UpRebaseRepositoryTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift…ests/CatchUpWriterTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift…/CertificationPathTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift…geRecordingSaveStrategy.swift Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swift…DuplicateMachineryTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift…itationBlobRefreshTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift…uleGroupValidationTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swift…CreatorConvergenceTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift…s/CreditReconcilerTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift…sSiteDuplicateScanTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift…eDuplicateWorkloadTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift…plicatePublicationTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift…teReconcilerTestSupport.swift Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift…uplicateResolutionTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift…ests/DuplicateScanTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift…Tests/EmptyLibraryTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swift…numTolerancePolicyTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift…eTests/FanOutWriteTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swift…reArchiveGeneratorTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift…/FrozenLibraryPathTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift…reTests/GroupFetchTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift…ests/GroupOrderingTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift…IdentityResolutionTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift…eTests/IntentReadsTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift…braryToleranceScanTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift…ValidatorToleranceTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift…pFirstCaptureStateTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swift…lkChunkPerformanceTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swift…teScalePerformanceTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift…sts/MarkerContractTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift…enerationSeventeenTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swift…mbershipReconcilerTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swift…s/MembershipTestSupport.swift Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift…mbershipValidationTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift…BootstrapLifecycleTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift…ests/ModelContractTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift…/MultiSiteReadPathTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swift…MultiSiteReviewFixTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swift…oEpisodeRepositoryTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift…s/NoEpisodeStorageTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift…endingCaptureDrainTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swift…DuplicateMachineryTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift…stCollapseRedirectTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/PublicationArchiveTests.swift…PublicationArchiveTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/PublicationProgressTests.swift…ublicationProgressTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/PublicationScheduleTests.swift…ublicationScheduleTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swift…oreTests/RecordRowTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swift…reshUnionInvariantTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift…eleaseDayWritePathTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift…/RepositoryCaptureTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift…/RepositoryReShareTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift…RepositoryTeachingTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift…ts/RepositoryWorksTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift…ests/RuleSelectionTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift…s/SeriesRepositoryTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift…sts/SiteReconcilerTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swift…iteUnionProjectionTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift…ests/StoreMetadataTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift…humbnailBytesReachTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift…humbnailStoreProbeTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift…ests/ToReadMatcherTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift…Tests/TodayDayPlanTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift…RLOptionalSequenceTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swift…ts/UnknownSiteModeTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift…s/V16RecordedStoreTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift…s/V17RecordedStoreTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift…s/V18RecordedStoreTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift…ts/WorkEditCreditsTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift…CoreTests/WorkEditTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift…s/WorkMergePlannerTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift…orkMergeRepositoryTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift…rkMergeToReadMatchTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationMergeTests.swift…rkPublicationMergeTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationProjectionTests.swift…licationProjectionTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationStateTests.swift…rkPublicationStateTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationValidationTests.swift…licationValidationTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationWriterTests.swift…kPublicationWriterTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkSnapshotMembershipTests.swift…SnapshotMembershipTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift…humbnailRepositoryTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift…orkTypeConvergenceTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift…s/WorkTypeOrderingTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift…s/WorkTypePlumbingTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift…/WorkTypeWritePathTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift…teSiteRelationshipTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift…rkURLCompatibilityTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swift…gHostWorkURLImportTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift…stWorkURLValidatorTests.swift
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

195 files: 184 code · 11 docs. Click to expand.

Code (184)

Asterism/Asterism/ContentView.swift Modified
diff --git a/Asterism/Asterism/ContentView.swift b/Asterism/Asterism/ContentView.swiftindex 9baa061d..723ba409 100644--- a/Asterism/Asterism/ContentView.swift+++ b/Asterism/Asterism/ContentView.swift@@ -629,6 +629,8 @@ struct ContentView: View {             // so a per-screen write would miss a surface on the list. From here             // it reaches both trees, everything they push, and the sheets, which             // inherit the presenting view's environment.+            .environment(\.publicationDay, model.currentDay)+            .environment(\.calendar, model.calendar)             .environment(\.siteNames, model.siteNames)             // `work-thumbnails` Q70: the cover loader, written beside the site             // names and for their reason — one write at the top of the window
Asterism/Asterism/Intents/AddPageToReadFlow.swift Modified
diff --git a/Asterism/Asterism/Intents/AddPageToReadFlow.swift b/Asterism/Asterism/Intents/AddPageToReadFlow.swiftindex c9ceb7ea..d31ea650 100644--- a/Asterism/Asterism/Intents/AddPageToReadFlow.swift+++ b/Asterism/Asterism/Intents/AddPageToReadFlow.swift@@ -105,7 +105,8 @@ struct AddPageToReadFlow {         case .created(let work):             let summary = WorkSummary(                 id: work.id, displayTitle: work.displayTitle,-                readingStatus: work.readingStatus, workStatus: work.workStatus)+                readingStatus: work.readingStatus,+                workStatus: work.effectiveWorkStatus(on: CivilDay(Date(), calendar: .current)))             IntentLog.note("\(intent): created", content: "\(work.displayTitle) | \(rawURL)")             return Outcome(                 dialog: "Added “\(work.displayTitle)” as \(ReadingStatusPresentation.name(work.readingStatus)).",
Asterism/Asterism/Localizable.xcstrings Modified
diff --git a/Asterism/Asterism/Localizable.xcstrings b/Asterism/Asterism/Localizable.xcstringsindex 552793d5..34faddc7 100644--- a/Asterism/Asterism/Localizable.xcstrings+++ b/Asterism/Asterism/Localizable.xcstrings@@ -818,6 +818,17 @@     "Go to Work" : {       "comment" : "A button that opens a web page for a work item.",       "isCommentAutoGenerated" : true+    },+    "Hiatus Return Date" : {+      "comment" : "The title of a sheet that lets the user set a hiatus",+      "isCommentAutoGenerated" : true+    },+    "Hiatus return date" : {+      "comment" : "A date picker for setting a work's hiatus return date.",+      "isCommentAutoGenerated" : true+    },+    "Hiatus return date, %@" : {+     },     "How these two works are related — “adaptation”, “sequel”, anything you like." : {       "comment" : "A description of what the user can enter in the",@@ -1396,6 +1407,10 @@       "comment" : "A button that removes an alias.",       "isCommentAutoGenerated" : true     },+    "Remove date" : {+      "comment" : "A button that removes a date from a work's return date.",+      "isCommentAutoGenerated" : true+    },     "Remove from credits" : {       "comment" : "A button that removes a creator role from a user's credits.",       "isCommentAutoGenerated" : true@@ -1408,6 +1423,10 @@       "comment" : "The label of a button that removes a member from a series.",       "isCommentAutoGenerated" : true     },+    "Remove hiatus return date" : {+      "comment" : "A button that removes a date from a work's hiatus.",+      "isCommentAutoGenerated" : true+    },     "Remove the credit for %@" : {       "comment" : "The button that removes a credit from a work. The argument is the name of the creator.",       "isCommentAutoGenerated" : true@@ -1485,6 +1504,9 @@     },     "Retry" : { +    },+    "Returns %@" : {+     },     "Review URL identity evidence and conflicts for this Work's site" : { 
Asterism/Asterism/Support/PublicationPresentation.swift Modified
diff --git a/Asterism/Asterism/Support/PublicationPresentation.swift b/Asterism/Asterism/Support/PublicationPresentation.swiftnew file mode 100644index 00000000..d7e90b1f--- /dev/null+++ b/Asterism/Asterism/Support/PublicationPresentation.swift@@ -0,0 +1,14 @@+import AsterismCore+import SwiftUI++/// The library publication's day travels through sheets and picker rows too.+private struct PublicationDayKey: EnvironmentKey {+    static let defaultValue: CivilDay? = nil+}++extension EnvironmentValues {+    var publicationDay: CivilDay? {+        get { self[PublicationDayKey.self] }+        set { self[PublicationDayKey.self] = newValue }+    }+}
Asterism/Asterism/UITestLaunchSupport.swift Modified
diff --git a/Asterism/Asterism/UITestLaunchSupport.swift b/Asterism/Asterism/UITestLaunchSupport.swiftindex 9d855845..9bd1425c 100644--- a/Asterism/Asterism/UITestLaunchSupport.swift+++ b/Asterism/Asterism/UITestLaunchSupport.swift@@ -60,6 +60,9 @@ enum UITestFixtureKind: Equatable {     /// tag or an empty work, so without this every filter dimension offers one     /// value and every sort draws the same list.     case worksOptions+    case hiatusReturn+    /// An ongoing daily release for save-day historical eligibility journeys.+    case hiatusHistory     /// A small legal library the series screens, the series filter and the     /// related-works section have something to say about     /// (`series-and-related-works`): five works over two hostnames, two of them@@ -157,6 +160,8 @@ enum UITestLaunchSupport {     static let seededPendingCapturesScenario = "seeded-pending-captures"     /// The five works the Works list's sort and filter journey runs over.     static let seededWorksOptionsScenario = "seeded-works-options"+    static let seededHiatusReturnScenario = "seeded-hiatus-return"+    static let seededHiatusHistoryScenario = "seeded-hiatus-history"     /// The five works, three series and two links the series journeys run over.     static let seededSeriesScenario = "seeded-series"     /// The four works, three creators, five roles and six credits the creator@@ -435,6 +440,10 @@ enum UITestLaunchSupport {             fixture = .pendingCaptures         case seededWorksOptionsScenario:             fixture = .worksOptions+        case seededHiatusReturnScenario:+            fixture = .hiatusReturn+        case seededHiatusHistoryScenario:+            fixture = .hiatusHistory         case seededSeriesScenario:             fixture = .series         case seededCreatorsScenario:
Asterism/Asterism/ViewModels/AppLibraryModel.swift Modified
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex d0bbc197..09f584dc 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -175,6 +175,7 @@ public final class AppLibraryModel {     /// a seam a caller can move mid-life is a seam the published values can be     /// out of step with.     @ObservationIgnored private let calendarSource: @MainActor () -> Calendar+    @ObservationIgnored private let nowSource: @MainActor () -> Date      /// The day-change subscription, created once at construction and held for     /// the life of the model (Q44).@@ -329,8 +330,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 BackupV17SnapshotProviding).-    private var backupRepository: (any BackupV17SnapshotProviding)?+    /// Retains the concrete repository for backup export (conforms to BackupV18SnapshotProviding).+    private var backupRepository: (any BackupV18SnapshotProviding)?     /// 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.@@ -379,13 +380,15 @@ public final class AppLibraryModel {         mirroringDeclarationFailure: String? = nil,         locator: any SharedContainerLocating = SystemSharedContainerLocator(),         capabilities: AsterismCapabilities = .current,-        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current }+        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current },+        nowSource: @escaping @MainActor () -> Date = { Date() }     ) {         // One read through the seam, seeding both published values (Q39, Q44).         let calendar = calendarSource()         self.calendarSource = calendarSource+        self.nowSource = nowSource         self.calendar = calendar-        self.currentDay = CivilDay(.now, calendar: calendar)+        self.currentDay = CivilDay(nowSource(), calendar: calendar)         self.capabilities = capabilities         self.explicitConfiguration = nil         self.appGroupIdentifier = appGroupIdentifier@@ -401,13 +404,15 @@ public final class AppLibraryModel {     public init(         configuration: LibraryConfiguration,         capabilities: AsterismCapabilities = .current,-        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current }+        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current },+        nowSource: @escaping @MainActor () -> Date = { Date() }     ) {         // One read through the seam, seeding both published values (Q39, Q44).         let calendar = calendarSource()         self.calendarSource = calendarSource+        self.nowSource = nowSource         self.calendar = calendar-        self.currentDay = CivilDay(.now, calendar: calendar)+        self.currentDay = CivilDay(nowSource(), calendar: calendar)         self.capabilities = capabilities         self.explicitConfiguration = configuration         self.appGroupIdentifier = nil@@ -425,13 +430,15 @@ public final class AppLibraryModel {         uiTestFixture: UITestFixtureKind,         capabilities: AsterismCapabilities = .current,         calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current },+        nowSource: @escaping @MainActor () -> Date = { Date() },         worksReadFault: (@MainActor () throws -> Void)? = nil     ) {         // One read through the seam, seeding both published values (Q39, Q44).         let calendar = calendarSource()         self.calendarSource = calendarSource+        self.nowSource = nowSource         self.calendar = calendar-        self.currentDay = CivilDay(.now, calendar: calendar)+        self.currentDay = CivilDay(nowSource(), calendar: calendar)         self.capabilities = capabilities         self.explicitConfiguration = configuration         self.appGroupIdentifier = nil@@ -463,13 +470,15 @@ public final class AppLibraryModel {         configuration: LibraryConfiguration? = nil,         mirroringDeclarationFailure: String? = nil,         capabilities: AsterismCapabilities = .current,-        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current }+        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current },+        nowSource: @escaping @MainActor () -> Date = { Date() }     ) {         // One read through the seam, seeding both published values (Q39, Q44).         let calendar = calendarSource()         self.calendarSource = calendarSource+        self.nowSource = nowSource         self.calendar = calendar-        self.currentDay = CivilDay(.now, calendar: calendar)+        self.currentDay = CivilDay(nowSource(), calendar: calendar)         self.capabilities = capabilities         self.explicitConfiguration = configuration         self.appGroupIdentifier = nil@@ -490,13 +499,15 @@ public final class AppLibraryModel {     init(         startupFailureMessage: String,         capabilities: AsterismCapabilities = .current,-        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current }+        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current },+        nowSource: @escaping @MainActor () -> Date = { Date() }     ) {         // One read through the seam, seeding both published values (Q39, Q44).         let calendar = calendarSource()         self.calendarSource = calendarSource+        self.nowSource = nowSource         self.calendar = calendar-        self.currentDay = CivilDay(.now, calendar: calendar)+        self.currentDay = CivilDay(nowSource(), calendar: calendar)         self.capabilities = capabilities         self.explicitConfiguration = nil         self.appGroupIdentifier = nil@@ -1274,7 +1285,7 @@ public final class AppLibraryModel {             // restored-selection prune run against this publication (Req 3.5).             workTitlesByID = presentation.workTitles             self.calendar = cycle.calendar-            currentDay = CivilDay(Date(), calendar: cycle.calendar)+            currentDay = CivilDay(nowSource(), calendar: cycle.calendar)             snapshotGeneration += 1             thumbnailLoader.update(generation: snapshotGeneration)             return snapshotGeneration@@ -1350,7 +1361,7 @@ public final class AppLibraryModel {             // so a reader never holds one cycle's rows beside another cycle's             // idea of what day it is.             self.calendar = cycle.calendar-            currentDay = CivilDay(Date(), calendar: cycle.calendar)+            currentDay = CivilDay(nowSource(), calendar: cycle.calendar)             // Decision 3: the works snapshot has been read, so the Works and             // Stats screens may draw. Inside the publish block, beside the             // snapshot the gate stands in front of.@@ -1548,8 +1559,12 @@ public final class AppLibraryModel {         #else         let coverFetcher: any CoverFetching = CoverCandidateFetcher()         #endif+        let initialCalendar = calendar         return WorkDetailModel(-            workID: id, library: repo, calendar: calendar, capabilities: capabilities,+            workID: id, library: repo, calendar: initialCalendar,+            currentDaySource: { [weak self] in self?.currentDay ?? CivilDay(Date(), calendar: initialCalendar) },+            calendarSource: { [weak self] in self?.calendar ?? initialCalendar },+            capabilities: capabilities,             coverFetcher: coverFetcher,             onMutation: { [weak self] in                 await self?.clearConflicts(resolvedBy: id)@@ -2865,11 +2880,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() -> BackupV17Exporter? {+    private func backupExporter() -> BackupV18Exporter? {         guard let repo = backupRepository, let config = resolvedConfiguration else { return nil }         let stagingDir = config.rootDirectory             .appending(path: "Library/Caches/BackupExports")-        return BackupV17Exporter(repository: repo, stagingDirectory: stagingDir)+        return BackupV18Exporter(repository: repo, stagingDirectory: stagingDir)     }      /// The per-entry markdown export model (Req 1.5), staged beside the backup@@ -3137,7 +3152,7 @@ public final class AppLibraryModel {                 genericNotes: "Ada keeps the lighthouse at Kestrel Head, and the crew call "                     + "her Nightjar. Brede rows the tender out at dusk. Selkie is moored "                     + "below the light.",-                workStatus: reloaded.workStatus, readingStatus: reloaded.readingStatus,+                publicationEdit: .unchanged, readingStatus: reloaded.readingStatus,                 verdict: reloaded.verdict,                 releaseDays: reloaded.releaseDays,                 membership: reloaded.membership,@@ -3279,12 +3294,28 @@ public final class AppLibraryModel {             basis: WorkEditBasis(work: reloaded),             draft: WorkMetadataDraft(                 displayTitle: title, typeAssignment: type, genreTags: tags, genericNotes: "",-                workStatus: workStatus, readingStatus: readingStatus, verdict: verdict,+                publicationEdit: .set(status: workStatus, returnDate: nil), readingStatus: readingStatus, verdict: verdict,                 releaseDays: releaseDays,                 membership: reloaded.membership,                 thumbnail: .keep), calendar: calendar)     } +    /// The ordinary Works fixture with a pending return on tomorrow's local day.+    private func seedHiatusReturnFixture(in repo: LibraryRepository) async throws {+        try await seedWorksOptionsFixture(in: repo)+        guard let work = try await repo.works().works.first(where: { $0.displayTitle == "Ashfall" }) else {+            throw LibraryRepositoryError.invalidInput(operation: "seeding hiatus return fixture", reason: "missing Ashfall")+        }+        _ = try await repo.updateWork(id: work.id, basis: WorkEditBasis(work: work),+            draft: WorkMetadataDraft(displayTitle: work.displayTitle,+                typeAssignment: work.typeDisplay.assignment, genreTags: work.genreTags,+                genericNotes: work.genericNotes,+                publicationEdit: .set(status: .hiatus, returnDate: currentDay.adding(days: 1, calendar: calendar)),+                readingStatus: work.readingStatus, verdict: work.verdict,+                releaseDays: work.releaseDays, membership: work.membership, thumbnail: .keep),+            calendar: calendar)+    }+     /// `update-schedule`: the smallest library the Today screen has something     /// to say about.     ///@@ -3313,10 +3344,8 @@ public final class AppLibraryModel {     ///   future one, absent on the previous day, and lights no release row and     ///   no strip dot anywhere (`catch-up-mode` Q3, Q5, Q8, Q12). Its entry a     ///   day back is what gives its row the `Last noted … · yesterday` line.-    /// - **Paper Lantern is on hiatus with days on both weekdays**, so it is-    ///   scheduled by its days and excluded by its status on both days at once-    ///   (Req 6.1). It is the only work either day's releases section can be-    ///   wrong about.+    /// - **Paper Lantern enters hiatus on the launch day with both weekdays**:+    ///   its previous-day release remains visible, while the launch day is paused.     /// - The strip's dots fall on exactly those two weekdays; the other five     ///   days of the week hold neither a release nor a note, which is where     ///   both empty lines are reachable.@@ -3424,7 +3453,7 @@ public final class AppLibraryModel {                 draft: WorkMetadataDraft(                     displayTitle: title, typeAssignment: current.typeDisplay.assignment,                     genreTags: current.genreTags, genericNotes: "",-                    workStatus: .ongoing, readingStatus: .reading, verdict: "",+                    publicationEdit: .unchanged, readingStatus: .reading, verdict: "",                     releaseDays: [weekday], membership: current.membership,                     thumbnail: .keep), calendar: calendar)             if marked {@@ -3449,7 +3478,7 @@ public final class AppLibraryModel {             draft: WorkMetadataDraft(                 displayTitle: title, typeAssignment: reloaded.typeDisplay.assignment,                 genreTags: reloaded.genreTags, genericNotes: "",-                workStatus: .ongoing, readingStatus: .catchingUp, verdict: "",+                publicationEdit: .unchanged, readingStatus: .catchingUp, verdict: "",                 releaseDays: releaseDays, membership: reloaded.membership,                 thumbnail: .keep),             calendar: calendar)@@ -3536,7 +3565,7 @@ public final class AppLibraryModel {                 displayTitle: title,                 typeAssignment: reloaded.typeDisplay.assignment,                 genreTags: reloaded.genreTags, genericNotes: "",-                workStatus: workStatus, readingStatus: readingStatus, verdict: "",+                publicationEdit: .set(status: workStatus, returnDate: nil), readingStatus: readingStatus, verdict: "",                 releaseDays: releaseDays,                 membership: reloaded.membership,                 thumbnail: .keep), calendar: calendar)@@ -3643,7 +3672,7 @@ public final class AppLibraryModel {             draft: WorkMetadataDraft(                 displayTitle: title, typeAssignment: reloaded.typeDisplay.assignment,                 genreTags: [], genericNotes: "",-                workStatus: reloaded.workStatus, readingStatus: readingStatus,+                publicationEdit: .unchanged, readingStatus: readingStatus,                 verdict: readingStatus == .abandoned ? "The fog plot went nowhere." : "",                 releaseDays: reloaded.releaseDays,                 membership: membership,@@ -3778,7 +3807,7 @@ public final class AppLibraryModel {             draft: WorkMetadataDraft(                 displayTitle: title, typeAssignment: reloaded.typeDisplay.assignment,                 genreTags: [], genericNotes: "",-                workStatus: reloaded.workStatus, readingStatus: .reading, verdict: "",+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "",                 releaseDays: reloaded.releaseDays,                 membership: reloaded.membership,                 // Nil rather than an empty draft for a work with no credits: the@@ -3916,6 +3945,17 @@ public final class AppLibraryModel {             try await seedWorksOptionsFixture(in: repository)             return         }+        if fixture == .hiatusReturn {+            try await seedHiatusReturnFixture(in: repository)+            return+        }+        if fixture == .hiatusHistory {+            try await seedWorksOptionsWork(+                title: "Ashfall", hostname: "beta.test", slug: "ashfall",+                type: .none, tags: [], workStatus: .ongoing, readingStatus: .reading,+                verdict: "", releaseDays: ReleaseDay.allCases, in: repository)+            return+        }          if fixture == .series {             try await seedSeriesFixture(in: repository)
Asterism/Asterism/ViewModels/SettingsBackupModel.swift Modified
diff --git a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift b/Asterism/Asterism/ViewModels/SettingsBackupModel.swiftindex 86340e9a..c66dd474 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 `BackupV17Exporter` to this protocol via extension below.+/// surface. Conforms `BackupV18Exporter` 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: BackupV17Metadata) async throws -> BackupExportResult+    func export(metadata: BackupV18Metadata) async throws -> BackupExportResult     func cleanup(_ result: BackupExportResult)     func scavengeStaleFiles() } -extension BackupV17Exporter: BackupExporting {}+extension BackupV18Exporter: BackupExporting {}  // MARK: - Export Stage @@ -87,7 +87,7 @@ nonisolated struct ExportRefusal: Error, Equatable, Sendable {         stagedFileURL = nil          do {-            let metadata = BackupV17Metadata(+            let metadata = BackupV18Metadata(                 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? BackupV17ExportError,+        guard let exportError = error as? BackupV18ExportError,               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 BackupV17ExportError:+        case let error as BackupV18ExportError:             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: BackupV17ExportError) -> String {+    private static func exportMessage(for error: BackupV18ExportError) -> 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 == BackupV17ExportError.thumbnailField:+        where field == BackupV18ExportError.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 BackupV17ExportError:+        case let e as BackupV18ExportError:             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.     ///-    /// `BackupV17ExportError.description` is written for the reader and names+    /// `BackupV18ExportError.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: BackupV17ExportError) -> String {+    private static func exportDiagnosticCategory(_ error: BackupV18ExportError) -> String {         switch error {         case .unrepresentableValue(_, let field, _):             "export: unrepresentable \(field)"
Asterism/Asterism/ViewModels/WorkDetailModel.swift Modified
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel.swift b/Asterism/Asterism/ViewModels/WorkDetailModel.swiftindex 47770ff1..e008150d 100644--- a/Asterism/Asterism/ViewModels/WorkDetailModel.swift+++ b/Asterism/Asterism/ViewModels/WorkDetailModel.swift@@ -213,6 +213,39 @@ public final class WorkDetailModel {     /// side and Req 3.3's auto-revert on the other. A raw property write from a     /// control would step past both.     public private(set) var draftWorkStatus: WorkStatus = .ongoing+    public private(set) var draftReturnDate: CivilDay?+    private var baselinePublicationStatus: WorkStatus = .ongoing+    private var baselineReturnDate: CivilDay?+    private var editorWorkBasis: WorkEditBasis?++    public var currentDay: CivilDay {+        currentDaySource?() ?? CivilDay(nowSource(), calendar: calendar)+    }+    public var publicationCalendar: Calendar { calendar }+    public var effectiveWorkStatus: WorkStatus {+        work?.effectiveWorkStatus(on: currentDay) ?? .ongoing+    }+    public var pendingReturnDate: CivilDay? { work?.publicationState?.pendingReturn(on: currentDay) }+    public var publicationEdit: WorkPublicationEdit {+        guard draftWorkStatus != baselinePublicationStatus || draftReturnDate != baselineReturnDate else {+            return .unchanged+        }+        return .set(status: draftWorkStatus, returnDate: draftReturnDate)+    }++    public func setReturnDate(_ day: CivilDay?) {+        guard draftWorkStatus == .hiatus else { return }+        draftReturnDate = day+    }++    private func seedPublicationDraft(from snapshot: WorkSnapshot) {+        let day = currentDay+        draftWorkStatus = snapshot.effectiveWorkStatus(on: day)+        draftReturnDate = snapshot.publicationState?.pendingReturn(on: day)+        baselinePublicationStatus = draftWorkStatus+        baselineReturnDate = draftReturnDate+        editorWorkBasis = WorkEditBasis(work: snapshot)+    }     /// The reader's side (Req 2.2).     public private(set) var draftReadingStatus: ReadingStatus = .reading     /// The verdict, always written whatever the reading status is (Req 2.5): a@@ -249,7 +282,13 @@ public final class WorkDetailModel {     public var releaseDaysNote: String? {         guard !draftReleaseDays.isEmpty else { return nil }         if draftReadingStatus == .catchingUp { return ReleaseDaysText.catchingUpNote }-        guard draftWorkStatus != .ongoing || draftReadingStatus != .reading else { return nil }+        if draftWorkStatus == .hiatus, draftReadingStatus == .reading,+           let returnDate = draftReturnDate, returnDate > currentDay {+            return "Release days resume on the return date"+        }+        let hasReleaseProjection = draftWorkStatus == .ongoing+            || (draftWorkStatus == .hiatus && draftReturnDate != nil)+        guard !hasReleaseProjection || draftReadingStatus != .reading else { return nil }         return ReleaseDaysText.note     } @@ -411,7 +450,11 @@ public final class WorkDetailModel {     /// neither this model's unit suite nor a UI-test launch ever touches a     /// network (`work-thumbnails` Req 4.1, design Testing Strategy).     private let coverFetcher: any CoverFetching-    private let calendar: Calendar+    private let initialCalendar: Calendar+    private let currentDaySource: (@MainActor () -> CivilDay)?+    private let calendarSource: (@MainActor () -> Calendar)?+    private let nowSource: @Sendable () -> Date+    private var calendar: Calendar { calendarSource?() ?? initialCalendar }     private let onMutation: @Sendable () async -> Void     /// Where a refused write goes (Req 2.10, Q47): the draft stays here, the     /// conflict goes to the model that owns the banner and the listing.@@ -422,6 +465,9 @@ public final class WorkDetailModel {         workID: UUID,         library: any LibraryProviding,         calendar: Calendar,+        currentDaySource: (@MainActor () -> CivilDay)? = nil,+        calendarSource: (@MainActor () -> Calendar)? = nil,+        nowSource: @escaping @Sendable () -> Date = { Date.now },         locale: Locale = .current,         capabilities: AsterismCapabilities = .current,         /// Find cover and the paste-URL branch's one seam@@ -433,7 +479,10 @@ public final class WorkDetailModel {     ) {         self.workID = workID         self.library = library-        self.calendar = calendar+        self.initialCalendar = calendar+        self.currentDaySource = currentDaySource+        self.calendarSource = calendarSource+        self.nowSource = nowSource         self.locale = locale         self.capabilities = capabilities         self.coverFetcher = coverFetcher@@ -441,7 +490,7 @@ public final class WorkDetailModel {         self.onConflict = onConflict     } -    public func load() async {+    public func load(preservingDrafts: Bool = true) async {         state = .loading         do {             let detail = try await library.workDetail(id: workID)@@ -453,28 +502,30 @@ public final class WorkDetailModel {             let snapshot = detail.work             coverFetchPages = Self.coverFetchPages(of: snapshot)             loadedRemovableHostnames = Self.removableHostnames(of: snapshot)-            draftTitle = snapshot.displayTitle-            draftAssignment = snapshot.typeDisplay.assignment-            typeOptions = await pickerOptions(carrying: snapshot.typeDisplay)-            draftTags = snapshot.genreTags-            draftNotes = snapshot.genericNotes-            draftWorkStatus = snapshot.workStatus-            draftReadingStatus = snapshot.readingStatus-            draftVerdict = snapshot.verdict-            // Req 1.2: the **tolerant** set, so a spelling this build cannot-            // name has no toggle to show. The raw column is what the dirty-            // check reads, which is how that work still offers a Save (Req 1.6).-            draftReleaseDays = Set(snapshot.releaseDays)-            // `work-thumbnails`: the cover draft is reassigned **only outside-            // edit mode**. A reload while the editor is open — the one a record-            // step's commit runs — would otherwise throw away a crop the reader-            // has confirmed but not yet saved, which is the only copy of itself.-            if !isEditing { restoreThumbnailDraft(from: snapshot) }-            autoRevertedReading = false-            restoreSeriesDraftFromSnapshot()-            seriesOptions = await seriesPickerOptions(carrying: snapshot.series)-            restoreCreditDraftFromPresentation()-            await reloadRoleOptions()+            if !isEditing || !preservingDrafts {+                draftTitle = snapshot.displayTitle+                draftAssignment = snapshot.typeDisplay.assignment+                typeOptions = await pickerOptions(carrying: snapshot.typeDisplay)+                draftTags = snapshot.genreTags+                draftNotes = snapshot.genericNotes+                seedPublicationDraft(from: snapshot)+                draftReadingStatus = snapshot.readingStatus+                draftVerdict = snapshot.verdict+                // Req 1.2: the **tolerant** set, so a spelling this build cannot+                // name has no toggle to show. The raw column is what the dirty+                // check reads, which is how that work still offers a Save (Req 1.6).+                draftReleaseDays = Set(snapshot.releaseDays)+                // `work-thumbnails`: the cover draft is reassigned **only outside+                // edit mode**. A reload while the editor is open — the one a record+                // step's commit runs — would otherwise throw away a crop the reader+                // has confirmed but not yet saved, which is the only copy of itself.+                if !isEditing { restoreThumbnailDraft(from: snapshot) }+                autoRevertedReading = false+                restoreSeriesDraftFromSnapshot()+                seriesOptions = await seriesPickerOptions(carrying: snapshot.series)+                restoreCreditDraftFromPresentation()+                await reloadRoleOptions()+            }             // T-2328: a staged removal only means something while the row it             // names is still there. A link another device removed, or a site a             // merge took off, drops out of the staging with it.@@ -486,7 +537,7 @@ public final class WorkDetailModel {             // Before the projection below, which is *about* the selected site.             resetWorkURLHostnameIfNeeded()             state = .ready-            await loadWorkURL()+            if !isEditing || !preservingDrafts { await loadWorkURL() }         } catch {             state = .error(message: error.localizedDescription)             Self.logger.error("Work load failed: \(String(describing: error), privacy: .public)")@@ -1993,7 +2044,7 @@ public final class WorkDetailModel {             || draftAssignment != work.typeDisplay.assignment             || draftTags != work.genreTags             || draftNotes != work.genericNotes-            || draftWorkStatus != work.workStatus+            || publicationEdit != .unchanged             || draftReadingStatus != work.readingStatus             // Compared whatever the reading status is (Req 2.5): a verdict the             // reader typed before hiding the field is a change the checkmark has@@ -2042,6 +2093,7 @@ public final class WorkDetailModel {         // deliberately leaves the draft alone while the editor is open — so         // entering the editor has to be the other place it is stated.         restoreThumbnailDraft(from: work)+        if let work { seedPublicationDraft(from: work) }         isEditing = true     } @@ -2192,7 +2244,7 @@ public final class WorkDetailModel {         draftAssignment = work.typeDisplay.assignment         draftTags = work.genreTags         draftNotes = work.genericNotes-        draftWorkStatus = work.workStatus+        seedPublicationDraft(from: work)         draftReadingStatus = work.readingStatus         draftVerdict = work.verdict         // Req 1.3's cancel: the toggles go back to what the row holds, as the@@ -2250,6 +2302,7 @@ public final class WorkDetailModel {         guard status != draftWorkStatus else { return }         let previous = draftWorkStatus         draftWorkStatus = status+        if status != .hiatus { draftReturnDate = nil }         if previous == .finished, draftReadingStatus == .finished {             // Req 2.5: the verdict text stays; only the field goes.             draftReadingStatus = .reading@@ -2271,7 +2324,7 @@ public final class WorkDetailModel {         guard let work,             draftReadingStatus == .finished,             draftWorkStatus != .finished,-            draftWorkStatus != work.workStatus || draftReadingStatus != work.readingStatus+            publicationEdit != .unchanged || draftReadingStatus != work.readingStatus         else { return nil }         return FinishedReadingPrompt(id: workID, thenCommits: true)     }@@ -2667,6 +2720,13 @@ public final class WorkDetailModel {     ///   `workDetail` reads for one confirmation is one too many.     private func save(reloading: Bool) async {         guard !isSubmitting else { return }+        if case .set(_, let returnDate) = publicationEdit,+           let returnDate, returnDate < currentDay {+            let message = "Choose today or a later hiatus return date"+            errorMessage = message+            state = .error(message: message)+            return+        }         // Req 2.2: the position is refused **here**, before any repository call,         // with the editor left open and the text exactly as typed. The rule is         // `SeriesPosition.parse`'s and the sentence is the series screen's, so@@ -2693,7 +2753,7 @@ public final class WorkDetailModel {                 // `updateWork` writes all three to every row (Req 7.1), so a                 // draft carrying anything but the reader's own values would                 // write their change away with nothing to see.-                workStatus: draftWorkStatus,+                publicationEdit: publicationEdit,                 readingStatus: draftReadingStatus,                 verdict: draftVerdict,                 // `update-schedule` Req 1.3: the schedule rides this one commit@@ -2717,7 +2777,7 @@ public final class WorkDetailModel {                 // an ordinary save from reading a byte of cover (Q37, Q49).                 thumbnail: thumbnailWrite             )-            let basis = work.map(WorkEditBasis.init(work:))+            let basis = editorWorkBasis ?? work.map(WorkEditBasis.init(work:))                 ?? WorkEditBasis(                     displayTitle: draftTitle, typeAssignment: draftAssignment,                     genreTags: draftTags,@@ -2809,7 +2869,7 @@ public final class WorkDetailModel {             }             await onMutation()             if reloading {-                await load()+                await load(preservingDrafts: false)             } else {                 state = .ready             }
Asterism/Asterism/ViewModels/WorksListOptions.swift Modified
diff --git a/Asterism/Asterism/ViewModels/WorksListOptions.swift b/Asterism/Asterism/ViewModels/WorksListOptions.swiftindex d8cbd940..2fb5db91 100644--- a/Asterism/Asterism/ViewModels/WorksListOptions.swift+++ b/Asterism/Asterism/ViewModels/WorksListOptions.swift@@ -277,9 +277,9 @@ nonisolated struct WorksFilter: Equatable, Sendable {             || workStatus != nil || readingStatus != nil || releaseDays != nil     } -    func apply(to works: [WorkSnapshot]) -> [WorkSnapshot] {+    func apply(to works: [WorkSnapshot], on day: CivilDay) -> [WorkSnapshot] {         guard isActive else { return works }-        return works.filter(matches)+        return works.filter { matches($0, on: day) }     }      /// The same filter with any value the options no longer offer dropped —@@ -315,7 +315,7 @@ nonisolated struct WorksFilter: Equatable, Sendable {         return pruned     } -    private func matches(_ work: WorkSnapshot) -> Bool {+    private func matches(_ work: WorkSnapshot, on day: CivilDay) -> Bool {         if let type, WorksTypeSelection.selection(for: work.typeDisplay) != type { return false }         // Genre tags are compared as stored — trimmed and deduplicated         // case-sensitively on write — so two tags differing only in case are@@ -332,7 +332,7 @@ nonisolated struct WorksFilter: Equatable, Sendable {         // Compared against the *resolved* statuses, so a stored spelling this         // build does not know is filtered as the default it reads as         // (Reqs 1.3, 2.7).-        if let workStatus, work.workStatus != workStatus { return false }+        if let workStatus, work.effectiveWorkStatus(on: day) != workStatus { return false }         if let readingStatus, work.readingStatus != readingStatus { return false }         // Req 11.2: asked of the *tolerant* set, so a row holding only a         // spelling this build cannot name answers "No release days" — what the@@ -859,13 +859,13 @@ nonisolated enum WorksGroup: String, CaseIterable, Hashable, Sendable {      var initialReadingStatus: ReadingStatus { self == .catchingUp ? .catchingUp : .toRead } -    func members(of works: [WorkSnapshot]) -> [WorkSnapshot] {+    func members(of works: [WorkSnapshot], on day: CivilDay) -> [WorkSnapshot] {         works.filter { work in             switch self {             case .catchingUp: work.readingStatus == .catchingUp-            case .reading: work.readingStatus == .reading && work.workStatus != .hiatus+            case .reading: work.readingStatus == .reading && work.effectiveWorkStatus(on: day) != .hiatus             case .toRead: work.readingStatus == .toRead-            case .onHiatus: work.workStatus == .hiatus+            case .onHiatus: work.effectiveWorkStatus(on: day) == .hiatus                 && [.reading, .catchingUp].contains(work.readingStatus)             case .finished: work.readingStatus == .finished             case .abandoned: work.readingStatus == .abandoned@@ -938,9 +938,9 @@ nonisolated enum WorksRowDetail {         return [chapter.map { "Last noted \($0)" } ?? "Last noted", when].joined(separator: " · ")     }     static func releasesToday(_ work: WorkSnapshot, now: Date = .now, calendar: Calendar = .current) -> Bool {-        TodaySchedule.admits(readingStatus: work.readingStatus, workStatus: work.workStatus,-            releaseDays: work.releaseDays) == .scheduled-            && work.releaseDays.contains(CivilDay(now, calendar: calendar).weekday(calendar: calendar))+        TodaySchedule.isReleaseEligible(readingStatus: work.readingStatus,+            workStatus: work.authoredWorkStatus, releaseDays: work.releaseDays,+            publicationState: work.publicationState, on: CivilDay(now, calendar: calendar), calendar: calendar)     }     static func isNewToday(_ work: WorkSnapshot, now: Date = .now, calendar: Calendar = .current) -> Bool {         releasesToday(work, now: now, calendar: calendar)
Asterism/Asterism/Views/DuplicateResolutionView.swift Modified
diff --git a/Asterism/Asterism/Views/DuplicateResolutionView.swift b/Asterism/Asterism/Views/DuplicateResolutionView.swiftindex c90a0faf..a4750233 100644--- a/Asterism/Asterism/Views/DuplicateResolutionView.swift+++ b/Asterism/Asterism/Views/DuplicateResolutionView.swift@@ -11,6 +11,9 @@ import SwiftUI struct DuplicateResolutionView: View {     @State private var model: DuplicateResolutionModel     @Environment(\.dismiss) private var dismiss+    @Environment(\.publicationDay) private var publishedDay+    @Environment(\.calendar) private var calendar+    private var currentDay: CivilDay { publishedDay ?? CivilDay(Date(), calendar: calendar) }      init(model: DuplicateResolutionModel) {         _model = State(initialValue: model)@@ -300,7 +303,7 @@ struct DuplicateResolutionView: View {                 }                 // V10 (Req 7.2): a status the copies disagree on is part of the                 // decision, so it is on the row that the reader picks.-                if let line = Self.workStatusLine(variant, differing: model.differingFields) {+                if let line = Self.workStatusLine(variant, differing: model.differingFields, on: currentDay) {                     Text(line)                         .font(.caption)                         .foregroundStyle(.secondary)@@ -362,10 +365,11 @@ struct DuplicateResolutionView: View {     /// the filter pills. The words were duplicated here only until that table     /// landed (Q54); this sheet is its fourth consumer, not a second table.     static func workStatusLine(-        _ variant: WorkVariantChoice, differing: [DuplicateResolutionField]+        _ variant: WorkVariantChoice, differing: [DuplicateResolutionField],+        on day: CivilDay     ) -> String? {-        guard differing.contains(.workStatus) else { return nil }-        return WorkStatusPresentation.accessibilityLabel(variant.workStatus)+        guard differing.contains(.workStatus) || differing.contains(.publicationState) else { return nil }+        return WorkStatusPresentation.accessibilityLabel(variant.publicationState?.status(on: day) ?? variant.workStatus)     }      static func readingStatusLine(
Asterism/Asterism/Views/WorkDetailView.swift Modified
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex e5d202ce..31c128b6 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -27,6 +27,8 @@ import UniformTypeIdentifiers struct WorkDetailView: View {     @State private var model: WorkDetailModel     @State private var pendingLatestRefresh = false+    @State private var isPickingReturnDate = false+    @State private var pickedReturnDate = Date.distantPast     @Environment(\.dismiss) private var dismiss     @Environment(\.openURL) private var openURL     /// `site-display-names`: what the site picker and the identity review menu@@ -190,6 +192,7 @@ struct WorkDetailView: View {             || editingCredit != nil || expandedEditCharacterID != nil             || expandedEditPlaceID != nil || isPresentingCoverPicker || isShowingCoverViewer             || model.isPresentingCoverCandidates || model.pendingCrop != nil+            || isPickingReturnDate     }      var body: some View {@@ -779,7 +782,7 @@ struct WorkDetailView: View {             // a glyph with its name. A status on its default adds nothing —             // which is what the presentation table's nil symbol says — so the             // line is unchanged for the works the reader has said nothing about.-            let workStatus = model.work?.workStatus ?? .ongoing+            let workStatus = model.effectiveWorkStatus             if let symbol = WorkStatusPresentation.systemImage(workStatus) {                 Label(WorkStatusPresentation.name(workStatus), systemImage: symbol)                     .font(.caption)@@ -787,6 +790,14 @@ struct WorkDetailView: View {                     .accessibilityLabel(WorkStatusPresentation.accessibilityLabel(workStatus))                     .accessibilityIdentifier("work-detail-status-work")             }+            if let returnDate = model.pendingReturnDate {+                let dateLabel = returnDateLabel(returnDate)+                Text("Returns \(dateLabel)")+                    .font(.caption)+                    .foregroundStyle(AsterismColors.secondaryText)+                    .accessibilityLabel("Hiatus return date, \(dateLabel)")+                    .accessibilityIdentifier("work-detail-return-date-pending")+            }             let readingStatus = model.work?.readingStatus ?? .reading             if let symbol = ReadingStatusPresentation.systemImage(readingStatus) {                 Label(ReadingStatusPresentation.name(readingStatus), systemImage: symbol)@@ -1153,6 +1164,10 @@ struct WorkDetailView: View {                     identifier: WorkStatusPresentation.controlIdentifier)                     .constellationCaptionedField("Work status") +                if model.draftWorkStatus == .hiatus {+                    returnDateField+                }+                 ConstellationSegmentedControl(                     values: ReadingStatus.allCases,                     selection: Binding(@@ -1211,6 +1226,79 @@ struct WorkDetailView: View {             .accessibilityElement(children: .contain)             .accessibilityIdentifier("work-detail-status-card")         }+        .sheet(isPresented: $isPickingReturnDate) { returnDatePicker }+    }++    private var returnDateCalendar: Calendar {+        var calendar = Calendar(identifier: .gregorian)+        calendar.timeZone = model.publicationCalendar.timeZone+        calendar.locale = model.publicationCalendar.locale+        calendar.firstWeekday = model.publicationCalendar.firstWeekday+        return calendar+    }++    private func returnDateLabel(_ day: CivilDay) -> String {+        let formatter = DateFormatter()+        formatter.calendar = returnDateCalendar+        formatter.timeZone = returnDateCalendar.timeZone+        formatter.locale = .current+        formatter.dateStyle = .medium+        return formatter.string(from: day.date(in: returnDateCalendar))+    }++    private var returnDateField: some View {+        VStack(alignment: .leading, spacing: 8) {+            Button {+                pickedReturnDate = (model.draftReturnDate ?? model.currentDay).date(in: returnDateCalendar)+                isPickingReturnDate = true+            } label: {+                Text(model.draftReturnDate.map(returnDateLabel) ?? "Set date…")+            }+            .buttonStyle(.plain)+            .accessibilityLabel("Hiatus return date, \(model.draftReturnDate.map(returnDateLabel) ?? "Set date")")+            .accessibilityHint("Opens a date picker")+            .accessibilityIdentifier("work-detail-return-date-button")+            if model.draftReturnDate != nil {+                Button("Remove date") { model.setReturnDate(nil) }+                    .buttonStyle(.plain)+                    .accessibilityLabel("Remove hiatus return date")+                    .accessibilityIdentifier("work-detail-return-date-remove")+            }+        }+        .constellationCaptionedField("Return date")+    }++    private var returnDatePicker: some View {+        NavigationStack {+            DatePicker("Hiatus return date", selection: $pickedReturnDate,+                       in: model.currentDay.date(in: returnDateCalendar)...,+                       displayedComponents: .date)+                .datePickerStyle(.graphical)+                .labelsHidden()+                .padding(16)+                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)+                .environment(\.calendar, returnDateCalendar)+                .environment(\.timeZone, returnDateCalendar.timeZone)+                .accessibilityLabel("Hiatus return date")+                .accessibilityIdentifier("work-detail-return-date-picker")+                .navigationTitle("Hiatus Return Date")+                .inlineNavigationTitle()+                .toolbar {+                    ToolbarItem(placement: .cancellationAction) {+                        Button(role: .close) { isPickingReturnDate = false }+                            .accessibilityLabel("Cancel")+                            .accessibilityIdentifier("work-detail-return-date-picker-close")+                    }+                    ToolbarItem(placement: .confirmationAction) {+                        Button(role: .confirm) {+                            model.setReturnDate(CivilDay(pickedReturnDate, calendar: returnDateCalendar))+                            isPickingReturnDate = false+                        }+                        .accessibilityLabel("Done")+                        .accessibilityIdentifier("work-detail-return-date-picker-done")+                    }+                }+        }     }      // MARK: - Series and related works (Req 2.3, `series-and-related-works`)
Asterism/Asterism/Views/WorkMergeView.swift Modified
diff --git a/Asterism/Asterism/Views/WorkMergeView.swift b/Asterism/Asterism/Views/WorkMergeView.swiftindex f1b3a282..359bfaa0 100644--- a/Asterism/Asterism/Views/WorkMergeView.swift+++ b/Asterism/Asterism/Views/WorkMergeView.swift@@ -8,6 +8,9 @@ import SwiftUI struct WorkMergeView: View {     @State private var model: WorkMergeModel     @Environment(\.dismiss) private var dismiss+    @Environment(\.publicationDay) private var publishedDay+    @Environment(\.calendar) private var calendar+    private var currentDay: CivilDay { publishedDay ?? CivilDay(Date(), calendar: calendar) }     /// `site-display-names` Q16: the destination row's spoken sentence names     /// the same sites its `SiteLabel`s show. The preview's own site rows read     /// the lookup through `SiteLabel` and need nothing here.@@ -151,7 +154,7 @@ struct WorkMergeView: View {         .accessibilityIdentifier("merge-destination-\(work.id.uuidString)")         .accessibilityLabel(             WorkMergeView.destinationLabel(-                work, unavailable: unavailable, siteNames: siteNames))+                work, unavailable: unavailable, siteNames: siteNames, on: currentDay))     }      /// One sentence per candidate, naming what the row shows: the title, the@@ -164,7 +167,7 @@ struct WorkMergeView: View {     /// sit before the refusal, which is a finished sentence of its own and has     /// to stay the last thing the row says.     static func destinationLabel(-        _ work: WorkSnapshot, unavailable: String?, siteNames: SiteNames+        _ work: WorkSnapshot, unavailable: String?, siteNames: SiteNames, on day: CivilDay     ) -> String {         var parts = ["Merge into \(work.displayTitle)"]         if !work.memberships.isEmpty {@@ -173,7 +176,7 @@ struct WorkMergeView: View {         }         if let typeName = work.typeDisplay.name { parts.append(typeName) }         parts.append(Pluralisation.count(work.entries.count, "note", "notes"))-        let clause = WorksRowPresentation.statusClause(for: work)+        let clause = WorksRowPresentation.statusClause(for: work, on: day)         let described = parts.joined(separator: ", ") + clause         guard let unavailable else { return described }         // The refusal is a finished sentence of its own, and so is a status@@ -439,9 +442,11 @@ struct WorkMergeView: View {         case .targetGenreTags: "Target tags"         case .sourceGenreTags: "Source tags"         case .targetWorkStatus: "Target work status"+        case .targetPublicationState: "Target hiatus dates"         case .targetReadingStatus: "Target reading status"         case .targetVerdict: "Target verdict"         case .sourceWorkStatus: "Source work status"+        case .sourcePublicationState: "Source hiatus dates"         case .sourceReadingStatus: "Source reading status"         case .sourceVerdict: "Source verdict"         // V11 (`series-and-related-works` Req 9.5). One label for both sides,
Asterism/Asterism/Views/WorksGroupView.swift Modified
diff --git a/Asterism/Asterism/Views/WorksGroupView.swift b/Asterism/Asterism/Views/WorksGroupView.swiftindex 8a9dbea9..64ee687b 100644--- a/Asterism/Asterism/Views/WorksGroupView.swift+++ b/Asterism/Asterism/Views/WorksGroupView.swift@@ -48,13 +48,13 @@ struct WorksSearchContent<Hub: View>: View {      private var filter: WorksFilter { WorksSearchToken.filter(from: tokens) }     private var active: Bool { !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || filter.isActive }-    private var members: [WorkSnapshot] { group?.members(of: library.snapshot.works) ?? library.snapshot.works }+    private var members: [WorkSnapshot] { group?.members(of: library.snapshot.works, on: library.currentDay) ?? library.snapshot.works }     private var values: [WorksSearchToken] { WorksSearchToken.values(options: library.filterOptions, siteNames: siteNames) }     private var suggestions: [WorksSearchToken] { WorksSearchToken.suggestions(query: query, values: values, group: group) }     private var rows: [WorkSnapshot] {         // A dimension prefix is navigation through suggestions, not a title query.         let searchingDimension = query.contains(":") && !suggestions.isEmpty-        let narrowed = filter.apply(to: WorksSearchFilter(query: searchingDimension ? "" : query).apply(to: members))+        let narrowed = filter.apply(to: WorksSearchFilter(query: searchingDimension ? "" : query).apply(to: members), on: library.currentDay)         if let group { return group.sorted(narrowed, by: WorksGroupSort(rawValue: storedSort) ?? .groupDefault) }         return WorksSort(storedValue: storedSort).apply(to: narrowed)     }
Asterism/Asterism/Views/WorksView.swift Modified
diff --git a/Asterism/Asterism/Views/WorksView.swift b/Asterism/Asterism/Views/WorksView.swiftindex b7457b15..adcdd1c9 100644--- a/Asterism/Asterism/Views/WorksView.swift+++ b/Asterism/Asterism/Views/WorksView.swift@@ -4,6 +4,9 @@ import SwiftUI  /// Library home and the shared row affordances used by its destinations. struct WorksView: View {+    @Environment(\.publicationDay) private var publishedDay+    @Environment(\.calendar) var calendar+    var currentDay: CivilDay { publishedDay ?? CivilDay(Date(), calendar: calendar) }     let snapshot: WorksSnapshot     let onSelectWork: (UUID) -> Void     let onSelectEntry: (UUID) -> Void@@ -164,7 +167,7 @@ struct WorksView: View {                 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10),                     count: dynamicTypeSize.isAccessibilitySize ? 1 : 2), spacing: 10) {                     ForEach([WorksGroup.catchingUp, .reading, .toRead], id: \.self) { group in-                        let members = group.sorted(group.members(of: snapshot.works))+                        let members = group.sorted(group.members(of: snapshot.works, on: currentDay))                         tile(group.title, count: members.count, covers: Array(members.prefix(3)),                             stat: tileStat(group, members: members), accent: group == .catchingUp,                             identifier: "library-tile-\(group.rawValue)") { select(.group(group)) }@@ -183,7 +186,7 @@ struct WorksView: View {                         Divider().overlay(AsterismColors.cardBorder)                         destinationRow(group.title, symbol: group == .onHiatus ? "pause.circle" :                             (ReadingStatusPresentation.systemImage(group == .finished ? .finished : .abandoned) ?? "book.closed"),-                            count: group.members(of: snapshot.works).count, id: group.rawValue) {+                            count: group.members(of: snapshot.works, on: currentDay).count, id: group.rawValue) {                                 select(.group(group))                             }                     }@@ -221,7 +224,7 @@ struct WorksView: View {     private func tileStat(_ group: WorksGroup, members: [WorkSnapshot]) -> String {         switch group {         case .reading:-            let count = members.filter { WorksRowDetail.releasesToday($0) }.count+            let count = members.filter { WorksRowDetail.releasesToday($0, now: currentDay.date(in: calendar), calendar: calendar) }.count             return count == 0 ? "" : "\(count) release today"         case .toRead:             return members.map(\.createdAt).min().map { "oldest from " + $0.formatted(.dateTime.month(.wide)) } ?? ""@@ -305,14 +308,14 @@ struct WorksView: View {             } label: {                 WorkRow(work: work, showsSeries: showsSeries,                     detailText: group?.detail(for: work, site: siteNames.label(for: work.primaryHostname)),-                    showsNewToday: group == .reading && WorksRowDetail.isNewToday(work))+                    showsNewToday: group == .reading && WorksRowDetail.isNewToday(work, now: currentDay.date(in: calendar), calendar: calendar))                     .frame(maxWidth: .infinity, alignment: .leading)                     .contentShape(Rectangle())             }             .buttonStyle(.plain)             .accessibilityIdentifier("work-row-\(work.id.uuidString)")             .accessibilityLabel(-                WorksRowPresentation.openLabel(for: work, siteNames: siteNames))+                WorksRowPresentation.openLabel(for: work, siteNames: siteNames, on: currentDay))             .accessibilityValue(group?.detail(for: work, site: siteNames.label(for: work.primaryHostname)) ?? "")              if let item, let onResolveDuplicate {@@ -418,12 +421,12 @@ enum WorksRowPresentation {     /// hostnames — the merge picker draws this same row with its `SiteLabel`s     /// visible, and a sentence that spoke hostnames there would say something     /// different from what is on screen.-    static func openLabel(for work: WorkSnapshot, siteNames: SiteNames) -> String {+    static func openLabel(for work: WorkSnapshot, siteNames: SiteNames, on day: CivilDay) -> String {         let sites = work.memberships.map { siteNames.label(for: $0.hostname) }         let sited = sites.isEmpty             ? "Open Work \(work.displayTitle)"             : "Open Work \(work.displayTitle) from \(sites.joined(separator: ", "))"-        return sited + statusClause(for: work)+        return sited + statusClause(for: work, on: day)     }      /// `work-and-reading-status` Req 5.5: what the row's glyphs are worth to a@@ -439,10 +442,10 @@ enum WorksRowPresentation {     /// A label appears exactly where the row draws a glyph: the table's     /// `systemImage` is the one rule for "this value is marked", so the words     /// and the mark cannot drift apart.-    private static func statusLabels(for work: WorkSnapshot) -> [String] {+    private static func statusLabels(for work: WorkSnapshot, on day: CivilDay) -> [String] {         var labels: [String] = []-        if WorkStatusPresentation.systemImage(work.workStatus) != nil {-            labels.append(WorkStatusPresentation.accessibilityLabel(work.workStatus))+        if WorkStatusPresentation.systemImage(work.effectiveWorkStatus(on: day)) != nil {+            labels.append(WorkStatusPresentation.accessibilityLabel(work.effectiveWorkStatus(on: day)))         }         if ReadingStatusPresentation.systemImage(work.readingStatus) != nil {             labels.append(ReadingStatusPresentation.accessibilityLabel(work.readingStatus))@@ -456,8 +459,8 @@ enum WorksRowPresentation {     /// hostnames comma-separated, so a comma here would read as one more site.     /// The separator also keeps the clauses behind the " from " the UI     /// journeys' title parser reads up to.-    static func statusClause(for work: WorkSnapshot) -> String {-        let labels = statusLabels(for: work)+    static func statusClause(for work: WorkSnapshot, on day: CivilDay) -> String {+        let labels = statusLabels(for: work, on: day)         guard !labels.isEmpty else { return "" }         return ". " + labels.joined(separator: ". ")     }@@ -465,8 +468,8 @@ enum WorksRowPresentation {     /// The `work-title` element's own label (Req 5.5). An abandoned row states     /// its state in words as well as in colour and opacity, which are the two     /// channels Req 5.2 dims it through.-    static func titleLabel(for work: WorkSnapshot) -> String {-        work.displayTitle + statusClause(for: work)+    static func titleLabel(for work: WorkSnapshot, on day: CivilDay) -> String {+        work.displayTitle + statusClause(for: work, on: day)     }      /// One "Not the same work" pill: the Work it names, and what to call it.@@ -532,6 +535,9 @@ enum WorksRowPresentation { /// picker row that had drifted from the library row would be a second answer to /// "what does a Work look like". struct WorkRow: View {+    @Environment(\.publicationDay) private var publishedDay+    @Environment(\.calendar) private var calendar+    private var day: CivilDay { publishedDay ?? CivilDay(Date(), calendar: calendar) }     let work: WorkSnapshot     /// Whether the site line names **every** membership rather than standing in     /// for the first with a glyph (Req 4.1). Off on the library list, where the@@ -558,7 +564,7 @@ struct WorkRow: View {             title: work.displayTitle,             // Req 5.5: the dimming is colour and opacity, neither of which is a             // channel every reader has, so the status is spoken.-            titleLabel: WorksRowPresentation.titleLabel(for: work),+            titleLabel: WorksRowPresentation.titleLabel(for: work, on: day),             primaryHostname: work.primaryHostname,             typeDisplay: work.typeDisplay,             // Req 5.2: the whole row steps back, the way an ignored teach chip@@ -585,10 +591,10 @@ struct WorkRow: View {             },             trailing: {                 // Req 5.1's marks, after the type tag and before the Spacer.-                if let symbol = WorkStatusPresentation.systemImage(work.workStatus) {+                if let symbol = WorkStatusPresentation.systemImage(work.effectiveWorkStatus(on: day)) {                     Self.statusGlyph(-                        symbol, hue: WorkStatusPresentation.hue(work.workStatus),-                        label: WorkStatusPresentation.accessibilityLabel(work.workStatus),+                        symbol, hue: WorkStatusPresentation.hue(work.effectiveWorkStatus(on: day)),+                        label: WorkStatusPresentation.accessibilityLabel(work.effectiveWorkStatus(on: day)),                         identifier: "work-status-glyph")                 }                 if let symbol = ReadingStatusPresentation.systemImage(work.readingStatus) {
Asterism/AsterismTests/BackupExportStageTests.swift Modified
diff --git a/Asterism/AsterismTests/BackupExportStageTests.swift b/Asterism/AsterismTests/BackupExportStageTests.swiftindex c8ddcb09..9cca591d 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(-            BackupV17ExportError.tornGroups(+            BackupV18ExportError.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: [-        BackupV17ExportError.referencesStillArriving(detail: "rule 1"),-        BackupV17ExportError.unrepresentableValue(+        BackupV18ExportError.referencesStillArriving(detail: "rule 1"),+        BackupV18ExportError.unrepresentableValue(             record: "Character", field: "factsData", value: "…"),-        BackupV17ExportError.snapshotFailed(reason: "read"),-        BackupV17ExportError.encodingFailed(reason: "encode"),-        BackupV17ExportError.stagingFailed(reason: "stage"),+        BackupV18ExportError.snapshotFailed(reason: "read"),+        BackupV18ExportError.encodingFailed(reason: "encode"),+        BackupV18ExportError.stagingFailed(reason: "stage"),     ])-    @MainActor func otherRefusalsOfferNoRoute(error: BackupV17ExportError) async {+    @MainActor func otherRefusalsOfferNoRoute(error: BackupV18ExportError) 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(-            BackupV17ExportError.unrepresentableValue(+            BackupV18ExportError.unrepresentableValue(                 record: "Work “Actual Title”",-                field: BackupV17ExportError.thumbnailField,+                field: BackupV18ExportError.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: BackupV17ExportError.unrepresentableValue(+            for: BackupV18ExportError.unrepresentableValue(                 record: "Work “Actual Title”",-                field: BackupV17ExportError.thumbnailField,+                field: BackupV18ExportError.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: BackupV17ExportError.unrepresentableValue(+            for: BackupV18ExportError.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: BackupV17ExportError.tornGroups(+            for: BackupV18ExportError.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 `BackupV17Exporter` does.+/// mock — removes the staged file on cleanup, as `BackupV18Exporter` 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(-        BackupV17ExportError.snapshotFailed(reason: "not configured"))+        BackupV18ExportError.snapshotFailed(reason: "not configured")) -    func export(metadata: BackupV17Metadata) async throws -> BackupExportResult {+    func export(metadata: BackupV18Metadata) async throws -> BackupExportResult {         exportCallCount += 1         return try exportResult.get()     }
Asterism/AsterismTests/DuplicateSurfaceTests.swift Modified
diff --git a/Asterism/AsterismTests/DuplicateSurfaceTests.swift b/Asterism/AsterismTests/DuplicateSurfaceTests.swiftindex c1605af0..74ca3012 100644--- a/Asterism/AsterismTests/DuplicateSurfaceTests.swift+++ b/Asterism/AsterismTests/DuplicateSurfaceTests.swift@@ -165,7 +165,7 @@ struct DuplicateSurfaceTests {             workStatus: .hiatus, readingStatus: .reading, verdict: "put it down")          #expect(-            DuplicateResolutionView.workStatusLine(variant, differing: [.workStatus])+            DuplicateResolutionView.workStatusLine(variant, differing: [.workStatus], on: TestFixtures.publicationDay)                 == "Work: On hiatus")         #expect(             DuplicateResolutionView.readingStatusLine(variant, differing: [.readingStatus])@@ -176,7 +176,7 @@ struct DuplicateSurfaceTests {          // A field the set agrees on is not a decision, so its arm prints         // nothing — the sheet's standing rule for every other field.-        #expect(DuplicateResolutionView.workStatusLine(variant, differing: [.verdict]) == nil)+        #expect(DuplicateResolutionView.workStatusLine(variant, differing: [.verdict], on: TestFixtures.publicationDay) == nil)         #expect(DuplicateResolutionView.readingStatusLine(variant, differing: [.verdict]) == nil)         #expect(DuplicateResolutionView.verdictLine(variant, differing: [.workStatus]) == nil)         // An empty verdict has nothing to show even where the set differs in it,@@ -195,7 +195,7 @@ struct DuplicateSurfaceTests {         #expect(             WorkStatus.allCases.map {                 DuplicateResolutionView.workStatusLine(-                    Self.workVariant(workStatus: $0), differing: [.workStatus])+                    Self.workVariant(workStatus: $0), differing: [.workStatus], on: TestFixtures.publicationDay)             } == ["Work: Ongoing", "Work: Finished", "Work: On hiatus"])         #expect(             ReadingStatus.allCases.map {
Asterism/AsterismTests/EmptyLibraryModelTests.swift Modified
diff --git a/Asterism/AsterismTests/EmptyLibraryModelTests.swift b/Asterism/AsterismTests/EmptyLibraryModelTests.swiftindex 6b54ff4e..f5dcd34e 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(-            BackupV17ExportError.tornGroups(TornGroupsPayload(count: 3, blockingWorkSet: nil)))+            BackupV18ExportError.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(-            BackupV17ExportError.referencesStillArriving(detail: "rule 1"))+            BackupV18ExportError.referencesStillArriving(detail: "rule 1"))          await harness.confirm() @@ -397,7 +397,7 @@ struct EmptyLibraryModelTests {         harness.model.cancelConfirmation()          harness.exporter.exportResult = .failure(-            BackupV17ExportError.encodingFailed(reason: "encode"))+            BackupV18ExportError.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 `BackupV17Exporter` does.+/// cleanup as `BackupV18Exporter` does. private final class RecordingBackupExporter: BackupExporting, @unchecked Sendable {     var exportCallCount = 0     var cleanupCallCount = 0     var exportResult: Result<BackupExportResult, Error> = .failure(-        BackupV17ExportError.snapshotFailed(reason: "not configured"))+        BackupV18ExportError.snapshotFailed(reason: "not configured")) -    func export(metadata: BackupV17Metadata) async throws -> BackupExportResult {+    func export(metadata: BackupV18Metadata) async throws -> BackupExportResult {         exportCallCount += 1         return try exportResult.get()     }
Asterism/AsterismTests/Helpers/TestFixtures.swift Modified
diff --git a/Asterism/AsterismTests/Helpers/TestFixtures.swift b/Asterism/AsterismTests/Helpers/TestFixtures.swiftindex 58a09a11..a940de07 100644--- a/Asterism/AsterismTests/Helpers/TestFixtures.swift+++ b/Asterism/AsterismTests/Helpers/TestFixtures.swift@@ -3,6 +3,7 @@ import Foundation  /// Factory helpers for creating test snapshot fixtures. enum TestFixtures {+    static let publicationDay = CivilDateCodec.parse("2026-09-30")!     static let fixedDate = Date(timeIntervalSince1970: 1_750_000_000)     static let laterDate = Date(timeIntervalSince1970: 1_750_000_060)     static let earlierDate = Date(timeIntervalSince1970: 1_750_000_000 - 60)@@ -246,7 +247,7 @@ enum TestFixtures {             modifiedAt: modifiedAt,             entries: entries,             groupState: groupState,-            workStatus: workStatus,+            authoredWorkStatus: workStatus,             readingStatus: readingStatus,             verdict: verdict,             membership: membership,
Asterism/AsterismTests/IntegrationSafetyNetTests.swift Modified
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex 1851ed20..f1cad6ee 100644--- a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift+++ b/Asterism/AsterismTests/IntegrationSafetyNetTests.swift@@ -149,16 +149,16 @@ struct IntegrationSafetyNetTests {                     UUID(uuidString: "0E7A0000-0000-4000-8000-0000000000A1")!),                 genreTags: ["science fiction", "serial"],                 genericNotes: "Work-level notes",-                workStatus: .ongoing, readingStatus: .reading, verdict: ""+                publicationEdit: .unchanged, readingStatus: .reading, verdict: ""             , releaseDays: [], membership: nil,             thumbnail: .keep)         , calendar: .current)          let stagingDirectory = fixture.baseDirectory.appending(path: "validated-backups")-        let exporter = BackupV17Exporter(repository: repository, stagingDirectory: stagingDirectory)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: stagingDirectory)         let exportedAt = Date(timeIntervalSince1970: 1_784_246_400)         let result = try await exporter.export(-            metadata: BackupV17Metadata(+            metadata: BackupV18Metadata(                 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 BackupV17Codec.decode(encoded)-        let source = try await repository.backupV17Snapshot()+        let decoded = try BackupV18Codec.decode(encoded)+        let source = try await repository.backupV18Snapshot()          #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 BackupV17Codec.decode(Data(contentsOf: backupURL))+                let document = try BackupV18Codec.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 = BackupV17Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+        let exporter = BackupV18Exporter(repository: sourceRepo, stagingDirectory: stagingDir)         let exportResult = try await exporter.export(-            metadata: BackupV17Metadata(appBuild: "fill-test", exportedAt: Date())+            metadata: BackupV18Metadata(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 = BackupV17Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+        let exporter = BackupV18Exporter(repository: sourceRepo, stagingDirectory: stagingDir)         let exportResult = try await exporter.export(-            metadata: BackupV17Metadata(appBuild: "restore-test", exportedAt: Date())+            metadata: BackupV18Metadata(appBuild: "restore-test", exportedAt: Date())         )         defer { exporter.cleanup(exportResult) }         let plan = try BackupImporter.plan(from: try Data(contentsOf: exportResult.fileURL))@@ -694,7 +694,7 @@ struct IntegrationSafetyNetTests {                 typeAssignment: .none,                 genreTags: ["tag-a"],                 genericNotes: "Source notes to audit",-                workStatus: .ongoing, readingStatus: .reading, verdict: ""+                publicationEdit: .unchanged, readingStatus: .reading, verdict: ""             , releaseDays: [], membership: nil,             thumbnail: .keep)         , calendar: .current)@@ -842,15 +842,15 @@ struct IntegrationSafetyNetTests {         )          let stagingDir = fixture.baseDirectory.appending(path: "corrupt-stage")-        let exporter = BackupV17Exporter(repository: repo, stagingDirectory: stagingDir)+        let exporter = BackupV18Exporter(repository: repo, stagingDirectory: stagingDir)         let exportResult = try await exporter.export(-            metadata: BackupV17Metadata(appBuild: "corrupt-test", exportedAt: Date())+            metadata: BackupV18Metadata(appBuild: "corrupt-test", exportedAt: Date())         )         defer { exporter.cleanup(exportResult) }          // Verify good backup decodes         let goodData = try Data(contentsOf: exportResult.fileURL)-        let decoded = try BackupV17Codec.decode(goodData)+        let decoded = try BackupV18Codec.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 BackupV17Codec.decode(corruptData)+            _ = try BackupV18Codec.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 = BackupV17Exporter(repository: repo, stagingDirectory: stagingDir)+        let exporter = BackupV18Exporter(repository: repo, stagingDirectory: stagingDir)         let exportResult = try await exporter.export(-            metadata: BackupV17Metadata(appBuild: "url-backup-test", exportedAt: Date())+            metadata: BackupV18Metadata(appBuild: "url-backup-test", exportedAt: Date())         )         defer { exporter.cleanup(exportResult) }         let backupData = try Data(contentsOf: exportResult.fileURL)-        let decoded = try BackupV17Codec.decode(backupData)+        let decoded = try BackupV18Codec.decode(backupData)          // Site should be present in the payload.         let site = decoded.payload.sites.first { $0.hostname == "backupurl.test" }
Asterism/AsterismTests/PublicationEditorTests.swift Modified
diff --git a/Asterism/AsterismTests/PublicationEditorTests.swift b/Asterism/AsterismTests/PublicationEditorTests.swiftnew file mode 100644index 00000000..a7694ba4--- /dev/null+++ b/Asterism/AsterismTests/PublicationEditorTests.swift@@ -0,0 +1,164 @@+import AsterismCore+import Foundation+import Testing+@testable import Asterism++@Suite("Publication editor drafts")+@MainActor+struct PublicationEditorTests {+    @MainActor private final class DayContext {+        var day = CivilDateCodec.parse("2026-09-30")!+        var calendar: Calendar = {+            var value = Calendar(identifier: .gregorian)+            value.timeZone = TimeZone(secondsFromGMT: 0)!+            return value+        }()+    }+    private func day(_ text: String) -> CivilDay { CivilDateCodec.parse(text)! }+    private func model(state: WorkPublicationState? = nil, context: DayContext,+                       failure: Bool = false) -> (WorkDetailModel, MockLibraryProvider) {+        let work = WorkSnapshot(id: UUID(), displayTitle: "Serial", lastParsedTitle: nil,+            memberships: [], genericNotes: "original", genreTags: [], titleProvenance: .manual,+            createdAt: .distantPast, modifiedAt: .distantPast, entries: [],+            authoredWorkStatus: state?.authoredStatus ?? .ongoing, publicationState: state)+        let mock = MockLibraryProvider()+        mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: work))+        if failure { mock.updateWorkResult = .failure(MockLibraryProvider.MockError.simulatedFailure("save failed")) }+        let model = WorkDetailModel(workID: work.id, library: mock, calendar: context.calendar,+            currentDaySource: { context.day }, calendarSource: { context.calendar }, onMutation: {})+        return (model, mock)+    }+    private func pending() throws -> WorkPublicationState {+        try WorkPublicationState(status: .hiatus, currentPause: .init(+            start: day("2026-09-10"), returnDate: day("2026-10-01")))+    }++    @Test("Pending dates seed editor drafts; changing only a date is dirty and cancel restores it")+    func pendingAndCancel() async throws {+        let context = DayContext()+        let (model, mock) = model(state: try pending(), context: context)+        await model.load()+        model.beginEditing()+        #expect(model.draftWorkStatus == .hiatus)+        #expect(model.draftReturnDate == day("2026-10-01"))+        #expect(model.pendingReturnDate == day("2026-10-01"))+        #expect(!model.hasUnsavedChanges)+        model.setReturnDate(day("2026-10-10"))+        #expect(model.hasUnsavedChanges)+        #expect(model.publicationEdit == .set(status: .hiatus, returnDate: day("2026-10-10")))+        model.cancelEditing()+        #expect(model.draftReturnDate == day("2026-10-01"))+        #expect(model.publicationEdit == .unchanged)+        #expect(mock.updateWorkCallCount == 0)+    }++    @Test("Removing a pending date and selecting today ride the metadata save")+    func removeAndToday() async throws {+        for selected in [nil, day("2026-09-30")] {+            let context = DayContext()+            let (model, mock) = model(state: try pending(), context: context)+            await model.load()+            model.beginEditing()+            model.setReturnDate(selected)+            await model.save()+            #expect(mock.lastUpdateWorkDraft?.publicationEdit == .set(status: .hiatus, returnDate: selected))+        }+    }++    @Test("A failed save retains the selected date and other drafts")+    func failedSaveRetainsDraft() async throws {+        let context = DayContext()+        let (model, _) = model(state: try pending(), context: context, failure: true)+        await model.load()+        model.beginEditing()+        model.setReturnDate(day("2026-10-10"))+        model.draftTitle = "Edited title"+        await model.save()+        #expect(model.isEditing)+        #expect(model.draftTitle == "Edited title")+        #expect(model.draftReturnDate == day("2026-10-10"))+        #expect(model.errorMessage != nil)+    }++    @Test("Ongoing and finished clear a pending date; a renewed hiatus cannot reuse it")+    func statusClearsDate() async throws {+        for status in [WorkStatus.ongoing, .finished] {+            let context = DayContext()+            let (model, _) = model(state: try pending(), context: context)+            await model.load()+            model.beginEditing()+            model.setDraftWorkStatus(status)+            #expect(model.draftReturnDate == nil)+            model.setDraftWorkStatus(.hiatus)+            #expect(model.draftReturnDate == nil)+            #expect(model.publicationEdit == .set(status: .hiatus, returnDate: nil))+        }+    }++    @Test("Midnight changes presentation without replacing an active draft or its authored save basis")+    func midnightPreservesEditing() async throws {+        let context = DayContext()+        let state = try pending()+        let (model, mock) = model(state: state, context: context)+        await model.load()+        model.beginEditing()+        model.draftTitle = "Edited title"+        model.draftWorkURL = "https://example.com/work"+        context.day = day("2026-10-02")+        await model.load()+        #expect(model.effectiveWorkStatus == .ongoing)+        #expect(model.pendingReturnDate == nil)+        #expect(model.draftTitle == "Edited title")+        #expect(model.draftWorkURL == "https://example.com/work")+        #expect(model.draftReturnDate == day("2026-10-01"))+        #expect(model.publicationEdit == .unchanged)+        await model.save()+        #expect(mock.lastUpdateWorkDraft?.publicationEdit == .unchanged)+        #expect(mock.lastUpdateWorkBasis?.publicationStateData == (try state.canonicalData()))+    }++    @Test("Expired state seeds ongoing with no pending date and unrelated saves preserve its evidence")+    func elapsedEditorStartsOngoing() async throws {+        let context = DayContext()+        context.day = day("2026-10-02")+        let (model, mock) = model(state: try pending(), context: context)+        await model.load()+        model.beginEditing()+        #expect(model.draftWorkStatus == .ongoing)+        #expect(model.draftReturnDate == nil)+        #expect(!model.hasUnsavedChanges)+        model.draftNotes = "edited note"+        await model.save()+        #expect(mock.lastUpdateWorkDraft?.publicationEdit == .unchanged)+    }++    @Test("A newly selected date that passes before saving fails visibly without losing the draft")+    func expiredSelection() async throws {+        let context = DayContext()+        let (model, mock) = model(state: try pending(), context: context)+        await model.load()+        model.beginEditing()+        model.setReturnDate(context.day)+        context.day = day("2026-10-01")+        await model.save()+        #expect(model.isEditing)+        #expect(model.draftReturnDate == day("2026-09-30"))+        #expect(model.errorMessage != nil)+        #expect(mock.updateWorkCallCount == 0)+    }+    @Test("Dated hiatus explains resumed release days while catching-up keeps precedence")+    func releaseDaysNote() async throws {+        let context = DayContext()+        let (model, _) = model(state: try pending(), context: context)+        await model.load()+        model.beginEditing()+        model.draftReleaseDays = [.monday]+        #expect(model.releaseDaysNote == "Release days resume on the return date")+        model.setDraftReadingStatus(.catchingUp)+        #expect(model.releaseDaysNote == ReleaseDaysText.catchingUpNote)+        model.setDraftReadingStatus(.reading)+        model.setReturnDate(context.day)+        #expect(model.releaseDaysNote == nil)+    }++}
Asterism/AsterismTests/PublicationPresentationTests.swift Modified
diff --git a/Asterism/AsterismTests/PublicationPresentationTests.swift b/Asterism/AsterismTests/PublicationPresentationTests.swiftnew file mode 100644index 00000000..3b8d62f6--- /dev/null+++ b/Asterism/AsterismTests/PublicationPresentationTests.swift@@ -0,0 +1,59 @@+import AsterismCore+import Foundation+import Testing+@testable import Asterism++@MainActor+@Suite("Publication presentation follows the published civil day")+struct PublicationPresentationTests {+    private var calendar: Calendar {+        var value = Calendar(identifier: .gregorian)+        value.timeZone = TimeZone(secondsFromGMT: 0)!+        return value+    }+    private func day(_ text: String) -> CivilDay { CivilDateCodec.parse(text)! }+    private func work() throws -> WorkSnapshot {+        let state = try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: day("2026-09-20"), returnDate: day("2026-09-30")))+        return WorkSnapshot(id: UUID(), displayTitle: "Returns", lastParsedTitle: nil,+            memberships: [], genericNotes: "", genreTags: [], titleProvenance: .manual,+            createdAt: day("2026-09-20").date(in: calendar), modifiedAt: day("2026-09-20").date(in: calendar),+            entries: [], authoredWorkStatus: .hiatus, releaseDays: ReleaseDay.allCases, publicationState: state)+    }++    @Test("Groups, filters and release marks resolve current day, never candidate membership")+    func filtersGroupsAndReleases() throws {+        let work = try work()+        let before = day("2026-09-29"), returned = day("2026-09-30")+        #expect(WorksGroup.onHiatus.members(of: [work], on: before).count == 1)+        #expect(WorksGroup.onHiatus.members(of: [work], on: returned).isEmpty)+        #expect(WorksGroup.reading.members(of: [work], on: returned).count == 1)+        #expect(WorksFilter(workStatus: .hiatus).apply(to: [work], on: before).count == 1)+        #expect(WorksFilter(workStatus: .ongoing).apply(to: [work], on: returned).count == 1)+        #expect(!WorksRowDetail.releasesToday(work, now: before.date(in: calendar), calendar: calendar))+        #expect(WorksRowDetail.releasesToday(work, now: returned.date(in: calendar), calendar: calendar))+        #expect(work.authoredWorkStatus == .hiatus)+    }++    @Test("Refresh publishes an injected clock day and calendar without changing authored snapshots")+    func refreshedDayAndZone() async throws {+        let work = try work()+        let library = MockLibraryProvider()+        library.worksResult = .success(WorksSnapshot(works: [work], unattachedEntries: []))+        var now = day("2026-09-29").date(in: calendar)+        var zone = calendar+        let model = AppLibraryModel(readyRepository: library, calendarSource: { zone }, nowSource: { now })+        _ = await model.refreshAll()+        #expect(model.currentDay == day("2026-09-29"))+        #expect(WorksGroup.onHiatus.members(of: model.worksSnapshot.works, on: model.currentDay).count == 1)+        now = day("2026-09-30").date(in: calendar)+        _ = await model.refreshAll()+        #expect(model.currentDay == day("2026-09-30"))+        #expect(WorksGroup.reading.members(of: model.worksSnapshot.works, on: model.currentDay).count == 1)+        zone.timeZone = TimeZone(identifier: "America/Los_Angeles")!+        _ = await model.refreshAll()+        #expect(model.currentDay == day("2026-09-29"))+        #expect(model.calendar.timeZone == zone.timeZone)+        #expect(model.worksSnapshot.works.first?.publicationState == work.publicationState)+    }+}
Asterism/AsterismTests/SettingsBackupModelTests.swift Modified
diff --git a/Asterism/AsterismTests/SettingsBackupModelTests.swift b/Asterism/AsterismTests/SettingsBackupModelTests.swiftindex 0cec680a..8a28a4c7 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(-            BackupV17ExportError.tornGroups(+            BackupV18ExportError.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(-            BackupV17ExportError.tornGroups(+            BackupV18ExportError.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(-            BackupV17ExportError.tornGroups(+            BackupV18ExportError.tornGroups(                 TornGroupsPayload(                     count: 1,                     blockingWorkSet: DuplicateSetKey(@@ -394,7 +394,7 @@ struct SettingsBackupModelTests {          let mock = MockBackupExporting()         mock.exportResult = .failure(-            BackupV17ExportError.tornGroups(+            BackupV18ExportError.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: BackupV17Metadata? = mock.lastMetadata+        let metadata: BackupV18Metadata? = 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(-            BackupV17ExportError.tornGroups(+            BackupV18ExportError.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: [-        BackupV17ExportError.referencesStillArriving(detail: "rule 1"),-        BackupV17ExportError.unrepresentableValue(+        BackupV18ExportError.referencesStillArriving(detail: "rule 1"),+        BackupV18ExportError.unrepresentableValue(             record: "Character", field: "factsData", value: "…"),-        BackupV17ExportError.snapshotFailed(reason: "read"),-        BackupV17ExportError.encodingFailed(reason: "encode"),-        BackupV17ExportError.stagingFailed(reason: "stage"),+        BackupV18ExportError.snapshotFailed(reason: "read"),+        BackupV18ExportError.encodingFailed(reason: "encode"),+        BackupV18ExportError.stagingFailed(reason: "stage"),     ])-    @MainActor func everyNineTenRefusalHasAMessage(error: BackupV17ExportError) async {+    @MainActor func everyNineTenRefusalHasAMessage(error: BackupV18ExportError) async {         let mock = MockBackupExporting()         mock.exportResult = .failure(error) @@ -495,9 +495,9 @@ struct SettingsBackupModelTests {     @MainActor func coverRefusalNamesTheWork() async {         let mock = MockBackupExporting()         mock.exportResult = .failure(-            BackupV17ExportError.unrepresentableValue(+            BackupV18ExportError.unrepresentableValue(                 record: "Work “Actual Title”",-                field: BackupV17ExportError.thumbnailField,+                field: BackupV18ExportError.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: BackupV17Metadata?+    var lastMetadata: BackupV18Metadata?      var exportResult: Result<BackupExportResult, Error> = .failure(MockBackupError.notConfigured)     var exportDelay: Duration? -    func export(metadata: BackupV17Metadata) async throws -> BackupExportResult {+    func export(metadata: BackupV18Metadata) async throws -> BackupExportResult {         exportCallCount += 1         lastMetadata = metadata         if let delay = exportDelay {
Asterism/AsterismTests/SettingsImportTests.swift Modified
diff --git a/Asterism/AsterismTests/SettingsImportTests.swift b/Asterism/AsterismTests/SettingsImportTests.swiftindex 28f5cb05..1bb21b8e 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 = BackupV17Payload(+        let payload = BackupV18Payload(             entries: [-                BackupV17Entry(+                BackupV18Entry(                     id: UUID(), captureTitle: "Chapter 1", captureTitleSource: .host,                     rawURL: rawURL, canonicalURL: nil, hostname: hostname,                     entryIdentityKey: rawURL,@@ -84,13 +84,13 @@ struct SettingsBackupImportModelTests {             ],             works: [],             sites: [-                BackupV17Site(+                BackupV18Site(                     hostname: hostname, displayName: hostname, mode: .untaught)             ],             titlePatterns: [], urlRules: [], workTypes: [])-        return try! BackupV17Codec.encode(+        return try! BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(+            metadata: BackupV18Metadata(                 appBuild: "test", exportedAt: Date(timeIntervalSince1970: 1_800_000_000)))     }() 
Asterism/AsterismTests/TodayFixtureSeedingTests.swift Modified
diff --git a/Asterism/AsterismTests/TodayFixtureSeedingTests.swift b/Asterism/AsterismTests/TodayFixtureSeedingTests.swiftindex bdbc8a97..f6b04c8a 100644--- a/Asterism/AsterismTests/TodayFixtureSeedingTests.swift+++ b/Asterism/AsterismTests/TodayFixtureSeedingTests.swift@@ -18,7 +18,7 @@ import Testing /// about the Today screen: the screen's derivation is /// `TodayDayPlanTests`' subject in Core, and the one assertion here that touches /// it (`TodaySchedule.build`) is there because the fixture's whole point is that-/// two works are scheduled; the catch-up examples are a separate bucket.+/// three works are schedule candidates; the catch-up examples are a separate bucket. @Suite("The today UI fixture, seeded") struct TodayFixtureSeedingTests { @@ -43,14 +43,14 @@ struct TodayFixtureSeedingTests {          // Req 6.1's exclusion needs one work that days alone would schedule and         // a status keeps off the day.-        #expect(kite.workStatus == .ongoing)-        #expect(salt.workStatus == .ongoing)-        #expect(lantern.workStatus == .hiatus)+        #expect(kite.authoredWorkStatus == .ongoing)+        #expect(salt.authoredWorkStatus == .ongoing)+        #expect(lantern.authoredWorkStatus == .hiatus)         #expect([kite, salt, lantern].allSatisfy { $0.readingStatus == .reading })         // `catch-up-mode` Q3 and Q12: the catch-up work is finished and         // unscheduled, so only the three scheduled-shape works read as         // `reading` and the fourth is the section's whole content.-        #expect(ember.workStatus == .finished)+        #expect(ember.authoredWorkStatus == .finished)         #expect(ember.readingStatus == .catchingUp)         #expect(ember.releaseDays.isEmpty)         #expect([frost, copper, harbor].allSatisfy { $0.readingStatus == .catchingUp })@@ -87,10 +87,15 @@ struct TodayFixtureSeedingTests {                 work.entries.allSatisfy { $0.firstCapturedAt <= $0.lastSharedAt }             }) -        // And what the fixture is for: two works on the day, the hiatus one off-        // it, and a dot on each of the two weekdays.+        // The known-start hiatus remains a historical candidate, but is paused+        // on its Save day. Candidate membership alone is not a release.         let schedule = TodaySchedule.build(works: works, calendar: calendar)-        #expect(schedule.works.map(\.title) == ["Kite Season", "Salt Harvest"])+        #expect(schedule.works.map(\.title) == ["Kite Season", "Paper Lantern", "Salt Harvest"])+        for (day, eligible) in [(previousDay, true), (currentDay, false)] {+            #expect(TodaySchedule.isReleaseEligible(readingStatus: lantern.readingStatus,+                workStatus: lantern.authoredWorkStatus, releaseDays: lantern.releaseDays,+                publicationState: lantern.publicationState, on: day, calendar: calendar) == eligible)+        }         #expect(schedule.dueWeekdays == Set([currentWeekday, previousWeekday]))         // Q8: the catch-up work is its own list and adds no dot.         #expect(schedule.catchingUp.map(\.title)
Asterism/AsterismTests/WorkDetailModelTests.swift Modified
diff --git a/Asterism/AsterismTests/WorkDetailModelTests.swift b/Asterism/AsterismTests/WorkDetailModelTests.swiftindex ceedebea..88909116 100644--- a/Asterism/AsterismTests/WorkDetailModelTests.swift+++ b/Asterism/AsterismTests/WorkDetailModelTests.swift@@ -1075,7 +1075,7 @@ struct WorkDetailModelTests {          #expect(model.finishedReadingPrompt == nil)         #expect(mock.updateWorkCallCount == 1)-        #expect(mock.lastUpdateWorkDraft?.workStatus == .ongoing)+        #expect(mock.lastUpdateWorkDraft?.publicationEdit == .unchanged)         #expect(mock.lastUpdateWorkDraft?.readingStatus == .finished)         #expect(!model.isEditing)     }@@ -1115,7 +1115,7 @@ struct WorkDetailModelTests {         #expect(mock.updateWorkCallCount == 1)         // What was *sent*, not what the drafts hold afterwards: a committed save         // reloads the screen, and the drafts are then the store's again.-        #expect(mock.lastUpdateWorkDraft?.workStatus == .finished)+        #expect(mock.lastUpdateWorkDraft?.publicationEdit == .set(status: .finished, returnDate: nil))         #expect(mock.lastUpdateWorkDraft?.readingStatus == .finished)         #expect(!model.isEditing)     }@@ -1135,7 +1135,7 @@ struct WorkDetailModelTests {          #expect(mock.updateWorkCallCount == 1)         // The work status is left alone; only the reading side moves.-        #expect(mock.lastUpdateWorkDraft?.workStatus == .hiatus)+        #expect(mock.lastUpdateWorkDraft?.publicationEdit == .set(status: .hiatus, returnDate: nil))         #expect(mock.lastUpdateWorkDraft?.readingStatus == .abandoned)         #expect(!model.isEditing)     }@@ -1319,7 +1319,7 @@ struct WorkDetailModelTests {          await model.commitEditing() -        #expect(mock.lastUpdateWorkDraft?.workStatus == .hiatus)+        #expect(mock.lastUpdateWorkDraft?.publicationEdit == .set(status: .hiatus, returnDate: nil))         #expect(mock.lastUpdateWorkDraft?.readingStatus == .abandoned)         #expect(mock.lastUpdateWorkDraft?.verdict == "gave up at the timeskip")         #expect(mock.lastUpdateWorkBasis?.workStatus == .finished)@@ -1347,7 +1347,7 @@ struct WorkDetailModelTests {         #expect(mock.lastUpdateWorkBasis?.workStatus == .finished)         #expect(mock.lastUpdateWorkBasis?.readingStatus == .finished)         #expect(mock.lastUpdateWorkBasis?.verdict == "read it twice")-        #expect(mock.lastUpdateWorkDraft?.workStatus == .finished)+        #expect(mock.lastUpdateWorkDraft?.publicationEdit == .set(status: .finished, returnDate: nil))         #expect(mock.lastUpdateWorkDraft?.readingStatus == .finished)         #expect(mock.lastUpdateWorkDraft?.verdict == "read it twice")     }
Asterism/AsterismTests/WorkMergeModelTests.swift Modified
diff --git a/Asterism/AsterismTests/WorkMergeModelTests.swift b/Asterism/AsterismTests/WorkMergeModelTests.swiftindex a20a185a..8d542fe1 100644--- a/Asterism/AsterismTests/WorkMergeModelTests.swift+++ b/Asterism/AsterismTests/WorkMergeModelTests.swift@@ -708,7 +708,7 @@ struct MergeDestinationPickerTests {                 assignment: .configured(UUID()), name: "Webtoon", kind: .active),             entries: [TestFixtures.makeEntry(hostname: "a.example")]) -        let label = WorkMergeView.destinationLabel(work, unavailable: nil, siteNames: .empty)+        let label = WorkMergeView.destinationLabel(work, unavailable: nil, siteNames: .empty, on: TestFixtures.publicationDay)          #expect(label.contains("Zephyr"))         #expect(label.contains("a.example"))@@ -717,7 +717,7 @@ struct MergeDestinationPickerTests {         #expect(label.contains("1 note"))          let refused = WorkMergeView.destinationLabel(-            work, unavailable: "Needs attention.", siteNames: .empty)+            work, unavailable: "Needs attention.", siteNames: .empty, on: TestFixtures.publicationDay)         #expect(refused.contains("Needs attention."))     } @@ -733,7 +733,7 @@ struct MergeDestinationPickerTests {             workStatus: .hiatus, readingStatus: .abandoned)          #expect(-            WorkMergeView.destinationLabel(work, unavailable: nil, siteNames: .empty)+            WorkMergeView.destinationLabel(work, unavailable: nil, siteNames: .empty, on: TestFixtures.publicationDay)                 == "Merge into Zephyr, on a.example, 1 note. Work: On hiatus. Reading: Abandoned")          // The refusal is a capitalised sentence of its own, so it follows the@@ -743,8 +743,7 @@ struct MergeDestinationPickerTests {                 work,                 unavailable:                     "a.example needs attention in Check Library before this Work can be merged into.",-                siteNames: .empty-            )+                siteNames: .empty, on: TestFixtures.publicationDay)                 == "Merge into Zephyr, on a.example, 1 note. Work: On hiatus. Reading: Abandoned. "                 + "a.example needs attention in Check Library before this Work can be merged into.") @@ -753,7 +752,7 @@ struct MergeDestinationPickerTests {             displayTitle: "Zephyr", hostname: "a.example",             entries: [TestFixtures.makeEntry(hostname: "a.example")])         #expect(-            WorkMergeView.destinationLabel(plain, unavailable: nil, siteNames: .empty)+            WorkMergeView.destinationLabel(plain, unavailable: nil, siteNames: .empty, on: TestFixtures.publicationDay)                 == "Merge into Zephyr, on a.example, 1 note")     } 
Asterism/AsterismTests/WorkStatusPresentationTests.swift Modified
diff --git a/Asterism/AsterismTests/WorkStatusPresentationTests.swift b/Asterism/AsterismTests/WorkStatusPresentationTests.swiftindex fd749fdc..11f797cd 100644--- a/Asterism/AsterismTests/WorkStatusPresentationTests.swift+++ b/Asterism/AsterismTests/WorkStatusPresentationTests.swift@@ -133,7 +133,7 @@ struct WorkStatusPresentationTests {         for status in WorkStatus.allCases {             #expect(                 DuplicateResolutionView.workStatusLine(-                    Self.variant(workStatus: status), differing: [.workStatus])+                    Self.variant(workStatus: status), differing: [.workStatus], on: TestFixtures.publicationDay)                     == WorkStatusPresentation.accessibilityLabel(status))         }         for status in ReadingStatus.allCases {
Asterism/AsterismTests/WorksListOptionsTests.swift Modified
diff --git a/Asterism/AsterismTests/WorksListOptionsTests.swift b/Asterism/AsterismTests/WorksListOptionsTests.swiftindex 5ac837cf..5c0c2e77 100644--- a/Asterism/AsterismTests/WorksListOptionsTests.swift+++ b/Asterism/AsterismTests/WorksListOptionsTests.swift@@ -274,7 +274,7 @@ struct WorksFilterTests {         let works = [work(1), work(2)]         let filter = WorksFilter()         #expect(!filter.isActive)-        #expect(filter.apply(to: works).map(\.id) == works.map(\.id))+        #expect(filter.apply(to: works, on: TestFixtures.publicationDay).map(\.id) == works.map(\.id))     }      @Test("Any one dimension makes the filter active")@@ -308,7 +308,7 @@ struct WorksFilterTests {             work(3, typeDisplay: typed("Novel", kind: .active)),         ]         let filter = WorksFilter(type: .named(WorkTypeName.normalize("MANGA")))-        #expect(filter.apply(to: works).map(\.id) == [id(1), id(2)])+        #expect(filter.apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1), id(2)])     }      @Test("Untyped matches works with no type and works whose type has not arrived")@@ -319,14 +319,14 @@ struct WorksFilterTests {             work(3, typeDisplay: typed("Manga", kind: .active)),         ]         #expect(-            WorksFilter(type: .untyped).apply(to: works).map(\.id) == [id(1), id(2)])+            WorksFilter(type: .untyped).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1), id(2)])     }      @Test("A removed type is still matched by its name")     func removedTypeStillMatches() {         let works = [work(1, typeDisplay: typed("Manhwa", kind: .removed)), work(2)]         let filter = WorksFilter(type: .named(WorkTypeName.normalize("Manhwa")))-        #expect(filter.apply(to: works).map(\.id) == [id(1)])+        #expect(filter.apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      // MARK: - Tag@@ -338,7 +338,7 @@ struct WorksFilterTests {             work(2, tags: ["Shonen"]),             work(3),         ]-        #expect(WorksFilter(tag: "shonen").apply(to: works).map(\.id) == [id(1)])+        #expect(WorksFilter(tag: "shonen").apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      // MARK: - Site@@ -351,13 +351,13 @@ struct WorksFilterTests {             work(3, hostnames: ["c.example"]),         ]         #expect(-            WorksFilter(hostname: "b.example").apply(to: works).map(\.id) == [id(1), id(2)])+            WorksFilter(hostname: "b.example").apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1), id(2)])     }      @Test("A work with no membership matches no site")     func membershiplessWorkMatchesNoSite() {         let works = [work(1, hostnames: [])]-        #expect(WorksFilter(hostname: "example.com").apply(to: works).isEmpty)+        #expect(WorksFilter(hostname: "example.com").apply(to: works, on: TestFixtures.publicationDay).isEmpty)     }      // MARK: - Work and reading status (`work-and-reading-status` Req 6.1)@@ -369,9 +369,9 @@ struct WorksFilterTests {             work(2, workStatus: .finished),             work(3, workStatus: .hiatus),         ]-        #expect(WorksFilter(workStatus: .finished).apply(to: works).map(\.id) == [id(2)])-        #expect(WorksFilter(workStatus: .ongoing).apply(to: works).map(\.id) == [id(1)])-        #expect(WorksFilter(workStatus: .hiatus).apply(to: works).map(\.id) == [id(3)])+        #expect(WorksFilter(workStatus: .finished).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(2)])+        #expect(WorksFilter(workStatus: .ongoing).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])+        #expect(WorksFilter(workStatus: .hiatus).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(3)])     }      @Test("A reading status matches works carrying exactly that value")@@ -382,11 +382,11 @@ struct WorksFilterTests {             work(3, readingStatus: .abandoned),             work(4, readingStatus: .toRead),         ]-        #expect(WorksFilter(readingStatus: .finished).apply(to: works).map(\.id) == [id(2)])-        #expect(WorksFilter(readingStatus: .abandoned).apply(to: works).map(\.id) == [id(3)])+        #expect(WorksFilter(readingStatus: .finished).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(2)])+        #expect(WorksFilter(readingStatus: .abandoned).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(3)])         // `to-read` Req 1.1: the fifth value narrows the list like the other four.-        #expect(WorksFilter(readingStatus: .toRead).apply(to: works).map(\.id) == [id(4)])-        #expect(WorksFilter(readingStatus: .reading).apply(to: works).map(\.id) == [id(1)])+        #expect(WorksFilter(readingStatus: .toRead).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(4)])+        #expect(WorksFilter(readingStatus: .reading).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      /// Both dimensions have a value spelled `finished`, and they are separate@@ -398,8 +398,8 @@ struct WorksFilterTests {             work(1, workStatus: .finished, readingStatus: .reading),             work(2, workStatus: .ongoing, readingStatus: .finished),         ]-        #expect(WorksFilter(workStatus: .finished).apply(to: works).map(\.id) == [id(1)])-        #expect(WorksFilter(readingStatus: .finished).apply(to: works).map(\.id) == [id(2)])+        #expect(WorksFilter(workStatus: .finished).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])+        #expect(WorksFilter(readingStatus: .finished).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(2)])     }      // MARK: - AND across dimensions (Q3)@@ -431,14 +431,14 @@ struct WorksFilterTests {             filter.apply(                 to: [                     match, wrongTag, wrongSite, wrongType, wrongWorkStatus, wrongReadingStatus,-                ]+                ], on: TestFixtures.publicationDay             ).map(\.id) == [id(1)])     }      @Test("A combination nothing matches returns nothing")     func noMatchReturnsNothing() {         let works = [work(1, tags: ["shonen"], hostnames: ["a.example"])]-        #expect(WorksFilter(tag: "shonen", hostname: "b.example").apply(to: works).isEmpty)+        #expect(WorksFilter(tag: "shonen", hostname: "b.example").apply(to: works, on: TestFixtures.publicationDay).isEmpty)     }      @Test("Filtering preserves the order it was handed")@@ -446,7 +446,7 @@ struct WorksFilterTests {         let works = [             work(3, tags: ["t"]), work(1, tags: ["t"]), work(2, tags: ["t"]),         ]-        #expect(WorksFilter(tag: "t").apply(to: works).map(\.id) == [id(3), id(1), id(2)])+        #expect(WorksFilter(tag: "t").apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(3), id(1), id(2)])     }      // MARK: - Pruning against a new snapshot@@ -671,7 +671,7 @@ struct WorksFilterOptionsTests {                 hostnames: ["b.example"]),         ]         let all = WorksFilterOptions(works: works, siteNames: .empty)-        let filtered = WorksFilter(hostname: "a.example").apply(to: works)+        let filtered = WorksFilter(hostname: "a.example").apply(to: works, on: TestFixtures.publicationDay)         #expect(filtered.count == 1)         // The vocabularies the pickers offer are the full snapshot's, so a         // reader can still pick "Novel" on a.example and land on the empty@@ -724,7 +724,7 @@ struct WorksSeriesFilterTests {             work(2, series: display(101, "Quiet Shelf")),             work(3),         ]-        #expect(WorksFilter(series: .series(id(100))).apply(to: works).map(\.id) == [id(1)])+        #expect(WorksFilter(series: .series(id(100))).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      /// Req 4.2's other half: a work whose series row has not arrived is not in@@ -736,13 +736,13 @@ struct WorksSeriesFilterTests {             work(2),             work(3, series: unresolvedDisplay(200)),         ]-        #expect(WorksFilter(series: .noSeries).apply(to: works).map(\.id) == [id(2), id(3)])+        #expect(WorksFilter(series: .noSeries).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(2), id(3)])     }      @Test("A series selection does not match a work whose series has not arrived")     func anUnresolvedMembershipIsNotInItsSeries() {         let works = [work(1, series: unresolvedDisplay(200))]-        #expect(WorksFilter(series: .series(id(200))).apply(to: works).isEmpty)+        #expect(WorksFilter(series: .series(id(200))).apply(to: works, on: TestFixtures.publicationDay).isEmpty)     }      @Test("The series dimension activates the filter and defaults to nothing chosen")@@ -765,7 +765,7 @@ struct WorksSeriesFilterTests {         let wrongSeries = TestFixtures.makeWork(             id: id(3), displayTitle: "C", genreTags: ["shonen"])         let filter = WorksFilter(tag: "shonen", series: .series(ashfall.id))-        #expect(filter.apply(to: [match, wrongTag, wrongSeries]).map(\.id) == [id(1)])+        #expect(filter.apply(to: [match, wrongTag, wrongSeries], on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      // MARK: - Pruning (Req 4.2's revert to Any)@@ -963,7 +963,7 @@ struct WorksCreatorFilterTests {             work(2, creators: [creator(101, "Studio Lantern")]),             work(3),         ]-        #expect(WorksFilter(creator: .creator(id(100))).apply(to: works).map(\.id) == [id(1)])+        #expect(WorksFilter(creator: .creator(id(100))).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      /// A work credits two creators; the filter is not "the first credit" but@@ -973,8 +973,8 @@ struct WorksCreatorFilterTests {         let works = [             work(1, creators: [creator(100, "Mori Ayane"), creator(101, "Studio Lantern")])         ]-        #expect(WorksFilter(creator: .creator(id(100))).apply(to: works).map(\.id) == [id(1)])-        #expect(WorksFilter(creator: .creator(id(101))).apply(to: works).map(\.id) == [id(1)])+        #expect(WorksFilter(creator: .creator(id(100))).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])+        #expect(WorksFilter(creator: .creator(id(101))).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      /// Req 5.1's other half: a work whose every credit is unresolved is credited@@ -990,13 +990,13 @@ struct WorksCreatorFilterTests {             work(4, creators: [unresolvedCreator(201), creator(100, "Mori Ayane")]),         ]         #expect(-            WorksFilter(creator: .noCreators).apply(to: works).map(\.id) == [id(2), id(3)])+            WorksFilter(creator: .noCreators).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(2), id(3)])     }      @Test("A creator selection does not match a work whose credit has not resolved")     func anUnresolvedCreditIsNotThatCreator() {         let works = [work(1, creators: [unresolvedCreator(200)])]-        #expect(WorksFilter(creator: .creator(id(200))).apply(to: works).isEmpty)+        #expect(WorksFilter(creator: .creator(id(200))).apply(to: works, on: TestFixtures.publicationDay).isEmpty)     }      @Test("The creator dimension activates the filter and defaults to nothing chosen")@@ -1020,7 +1020,7 @@ struct WorksCreatorFilterTests {             id: id(3), displayTitle: "C", genreTags: ["shonen"],             credits: [TestFixtures.makeCredit(creator: creator(101, "Studio Lantern"))])         let filter = WorksFilter(tag: "shonen", creator: .creator(mori.id))-        #expect(filter.apply(to: [match, wrongTag, wrongCreator]).map(\.id) == [id(1)])+        #expect(filter.apply(to: [match, wrongTag, wrongCreator], on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      // MARK: - Pruning (Req 5.1's revert to Any)@@ -1212,7 +1212,7 @@ struct WorksReleaseDaysFilterTests {     func noReleaseDaysMatchesTheUnscheduled() {         let works = [work(1), work(2, releaseDays: [.monday]), work(3)]         #expect(-            WorksFilter(releaseDays: .noReleaseDays).apply(to: works).map(\.id)+            WorksFilter(releaseDays: .noReleaseDays).apply(to: works, on: TestFixtures.publicationDay).map(\.id)                 == [id(1), id(3)])     } @@ -1223,7 +1223,7 @@ struct WorksReleaseDaysFilterTests {             work(3, releaseDays: ReleaseDay.allCases),         ]         #expect(-            WorksFilter(releaseDays: .hasReleaseDays).apply(to: works).map(\.id)+            WorksFilter(releaseDays: .hasReleaseDays).apply(to: works, on: TestFixtures.publicationDay).map(\.id)                 == [id(2), id(3)])     } @@ -1237,9 +1237,9 @@ struct WorksReleaseDaysFilterTests {             work(2, workStatus: .ongoing, readingStatus: .reading),         ]         #expect(-            WorksFilter(releaseDays: .hasReleaseDays).apply(to: works).map(\.id) == [id(1)])+            WorksFilter(releaseDays: .hasReleaseDays).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])         #expect(-            WorksFilter(releaseDays: .noReleaseDays).apply(to: works).map(\.id) == [id(2)])+            WorksFilter(releaseDays: .noReleaseDays).apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(2)])     }      /// Req 1.6: the snapshot's `releaseDays` is the tolerant set, so a row whose@@ -1249,8 +1249,8 @@ struct WorksReleaseDaysFilterTests {     func anUnknownSpellingCountsAsNone() {         let unknown = TestFixtures.makeWork(id: id(1), releaseDaysRaw: ["funday"])         #expect(-            WorksFilter(releaseDays: .noReleaseDays).apply(to: [unknown]).map(\.id) == [id(1)])-        #expect(WorksFilter(releaseDays: .hasReleaseDays).apply(to: [unknown]).isEmpty)+            WorksFilter(releaseDays: .noReleaseDays).apply(to: [unknown], on: TestFixtures.publicationDay).map(\.id) == [id(1)])+        #expect(WorksFilter(releaseDays: .hasReleaseDays).apply(to: [unknown], on: TestFixtures.publicationDay).isEmpty)     }      @Test("The dimension is ANDed with the others")@@ -1261,7 +1261,7 @@ struct WorksReleaseDaysFilterTests {             TestFixtures.makeWork(id: id(3), genreTags: ["shonen"]),         ]         let filter = WorksFilter(tag: "shonen", releaseDays: .hasReleaseDays)-        #expect(filter.apply(to: works).map(\.id) == [id(1)])+        #expect(filter.apply(to: works, on: TestFixtures.publicationDay).map(\.id) == [id(1)])     }      // MARK: - Pruning (Req 11.3)
Asterism/AsterismTests/WorksRedesignTests.swift Modified
diff --git a/Asterism/AsterismTests/WorksRedesignTests.swift b/Asterism/AsterismTests/WorksRedesignTests.swiftindex deb2362a..ba7684af 100644--- a/Asterism/AsterismTests/WorksRedesignTests.swift+++ b/Asterism/AsterismTests/WorksRedesignTests.swift@@ -9,9 +9,9 @@ struct WorksRedesignTests {     func hiatusMembership() {         for status in ReadingStatus.allCases {             let work = TestFixtures.makeWork(workStatus: .hiatus, readingStatus: status)-            #expect(WorksGroup.onHiatus.members(of: [work]).isEmpty == ![.reading, .catchingUp].contains(status))-            #expect(WorksGroup.reading.members(of: [work]).isEmpty)-            #expect(WorksGroup.catchingUp.members(of: [work]).isEmpty == (status != .catchingUp))+            #expect(WorksGroup.onHiatus.members(of: [work], on: TestFixtures.publicationDay).isEmpty == ![.reading, .catchingUp].contains(status))+            #expect(WorksGroup.reading.members(of: [work], on: TestFixtures.publicationDay).isEmpty)+            #expect(WorksGroup.catchingUp.members(of: [work], on: TestFixtures.publicationDay).isEmpty == (status != .catchingUp))         }     } 
Asterism/AsterismTests/WorksRowPresentationTests.swift Modified
diff --git a/Asterism/AsterismTests/WorksRowPresentationTests.swift b/Asterism/AsterismTests/WorksRowPresentationTests.swiftindex 4623221e..57236d39 100644--- a/Asterism/AsterismTests/WorksRowPresentationTests.swift+++ b/Asterism/AsterismTests/WorksRowPresentationTests.swift@@ -15,13 +15,13 @@ struct WorksRowPresentationTests {     @MainActor func theLabelNamesEverySite() {         let single = TestFixtures.makeWork(displayTitle: "Zephyr", hostname: "a.example")         #expect(-            WorksRowPresentation.openLabel(for: single, siteNames: .empty)+            WorksRowPresentation.openLabel(for: single, siteNames: .empty, on: TestFixtures.publicationDay)                 == "Open Work Zephyr from a.example")          let merged = TestFixtures.makeWork(             displayTitle: "Zephyr",             memberships: TestFixtures.makeMemberships(["a.example", "b.example"]))-        let label = WorksRowPresentation.openLabel(for: merged, siteNames: .empty)+        let label = WorksRowPresentation.openLabel(for: merged, siteNames: .empty, on: TestFixtures.publicationDay)         #expect(label.contains("a.example"))         #expect(label.contains("b.example"))         // Membership order, which is Req 1.2's — not whichever the set iterated.@@ -40,7 +40,7 @@ struct WorksRowPresentationTests {         // Both renamed to "Alpha", so both wear their hostname (Q5) and the         // sentence still tells the two sites apart.         #expect(-            WorksRowPresentation.openLabel(for: work, siteNames: names)+            WorksRowPresentation.openLabel(for: work, siteNames: names, on: TestFixtures.publicationDay)                 == "Open Work Zephyr from Alpha (a.example), Alpha (b.example)")     } @@ -50,7 +50,7 @@ struct WorksRowPresentationTests {     @MainActor func aMembershiplessWorkIsNamedWithoutASite() {         let work = TestFixtures.makeWork(displayTitle: "Orphan", memberships: [])         #expect(-            WorksRowPresentation.openLabel(for: work, siteNames: .empty) == "Open Work Orphan")+            WorksRowPresentation.openLabel(for: work, siteNames: .empty, on: TestFixtures.publicationDay) == "Open Work Orphan")     }      // MARK: - Status clauses (`work-and-reading-status` Req 5.5, Q32)@@ -66,7 +66,7 @@ struct WorksRowPresentationTests {             workStatus: .finished, readingStatus: .abandoned)          #expect(-            WorksRowPresentation.openLabel(for: work, siteNames: .empty)+            WorksRowPresentation.openLabel(for: work, siteNames: .empty, on: TestFixtures.publicationDay)                 == "Open Work Zephyr from a.example, b.example. Work: Finished. "                 + "Reading: Abandoned")     }@@ -76,7 +76,7 @@ struct WorksRowPresentationTests {     @Test("A work on both defaults adds no clause")     @MainActor func defaultsAddNoClause() {         let work = TestFixtures.makeWork(displayTitle: "Zephyr", hostname: "a.example")-        #expect(WorksRowPresentation.openLabel(for: work, siteNames: .empty) == "Open Work Zephyr from a.example")+        #expect(WorksRowPresentation.openLabel(for: work, siteNames: .empty, on: TestFixtures.publicationDay) == "Open Work Zephyr from a.example")     }      @Test("Each dimension contributes its clause on its own")@@ -84,13 +84,13 @@ struct WorksRowPresentationTests {         let hiatus = TestFixtures.makeWork(             displayTitle: "Zephyr", hostname: "a.example", workStatus: .hiatus)         #expect(-            WorksRowPresentation.openLabel(for: hiatus, siteNames: .empty)+            WorksRowPresentation.openLabel(for: hiatus, siteNames: .empty, on: TestFixtures.publicationDay)                 == "Open Work Zephyr from a.example. Work: On hiatus")          let read = TestFixtures.makeWork(             displayTitle: "Zephyr", hostname: "a.example", readingStatus: .finished)         #expect(-            WorksRowPresentation.openLabel(for: read, siteNames: .empty)+            WorksRowPresentation.openLabel(for: read, siteNames: .empty, on: TestFixtures.publicationDay)                 == "Open Work Zephyr from a.example. Reading: Finished")     } @@ -100,10 +100,10 @@ struct WorksRowPresentationTests {     @MainActor func theTitleElementCarriesTheClauses() {         let abandoned = TestFixtures.makeWork(             displayTitle: "Zephyr", hostname: "a.example", readingStatus: .abandoned)-        #expect(WorksRowPresentation.titleLabel(for: abandoned) == "Zephyr. Reading: Abandoned")+        #expect(WorksRowPresentation.titleLabel(for: abandoned, on: TestFixtures.publicationDay) == "Zephyr. Reading: Abandoned")          let plain = TestFixtures.makeWork(displayTitle: "Zephyr", hostname: "a.example")-        #expect(WorksRowPresentation.titleLabel(for: plain) == "Zephyr")+        #expect(WorksRowPresentation.titleLabel(for: plain, on: TestFixtures.publicationDay) == "Zephyr")     }      /// The UI journeys read a listed title as the substring before " from ",@@ -113,7 +113,7 @@ struct WorksRowPresentationTests {         let work = TestFixtures.makeWork(             displayTitle: "Zephyr", hostname: "a.example", workStatus: .finished,             readingStatus: .abandoned)-        let label = WorksRowPresentation.openLabel(for: work, siteNames: .empty)+        let label = WorksRowPresentation.openLabel(for: work, siteNames: .empty, on: TestFixtures.publicationDay)         let opened = try #require(label.range(of: "Open Work "))         let site = try #require(label.range(of: " from "))         #expect(String(label[opened.upperBound..<site.lowerBound]) == "Zephyr")
Asterism/AsterismUITests/PublicationReturnDateUITests.swift Modified
diff --git a/Asterism/AsterismUITests/PublicationReturnDateUITests.swift b/Asterism/AsterismUITests/PublicationReturnDateUITests.swiftnew file mode 100644index 00000000..d09d75a0--- /dev/null+++ b/Asterism/AsterismUITests/PublicationReturnDateUITests.swift@@ -0,0 +1,268 @@+import UIKit+import XCTest++final class PublicationReturnDateUITests: XCTestCase {+    private let app = XCUIApplication()++    override func setUp() {+        continueAfterFailure = false+        terminateAndWaitForExit(app)+        XCUIDevice.shared.orientation = UIDevice.current.userInterfaceIdiom == .pad ? .landscapeLeft : .portrait+    }++    override func tearDown() {+        terminateAndWaitForExit(app)+        XCUIDevice.shared.orientation = .portrait+    }++    private func launch(accessibilitySize: Bool = false, history: Bool = false) {+        app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = history ? "seeded-hiatus-history" : "seeded-hiatus-return"+        app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+        if accessibilitySize {+            app.launchArguments += ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]+        }+        app.launch()+        waitFor(app.collectionViews["recent-list"], "The isolated library opens", timeout: 60)+        if UIDevice.current.userInterfaceIdiom == .pad && accessibilitySize {+            // Accessibility sizes launch with the sidebar collapsed. Reach+            // the same work through its recent entry instead of changing panes.+            let row = app.elements(withIdentifierPrefix: "recent-entry-")+                .matching(NSPredicate(format: "label CONTAINS %@", "Ashfall")).firstMatch+            let column = app.anyElement("wide-list-column")+            for _ in 0..<8 {+                if row.exists && column.frame.contains(row.frame) { break }+                column.swipeUp()+            }+            XCTAssertTrue(row.exists && column.frame.contains(row.frame), "Ashfall's recent entry is visible")+            row.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+            tap(app.buttons["entry-detail-work-title"], "The entry's work link opens Work Detail")+            waitFor(app.buttons["work-detail-edit-button"], "Work Detail opens")+            return+        }+        if UIDevice.current.userInterfaceIdiom == .pad {+            if !app.buttons["sidebar-library"].waitForExistence(timeout: 3) {+                waitFor(app.buttons["sidebar-toggle"], "The collapsed sidebar can be opened").tap()+            }+            let library = waitFor(app.buttons["sidebar-library"], "The Library sidebar row is present")+            // Wide-layout simulator rows can report non-hittable despite being+            // visible. Keep the coordinate tap inside the actual window.+            XCTAssertTrue(app.windows.firstMatch.frame.contains(library.frame))+            library.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+            let all = waitFor(app.buttons["library-destination-allWorks"], "All works is offered")+            let column = app.anyElement("wide-list-column")+            for _ in 0..<8 where !column.frame.contains(all.frame) {+                app.scrollViews["library-hub"].swipeUp()+            }+            XCTAssertTrue(column.frame.contains(all.frame))+            all.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+            waitFor(app.anyElement("works-group-allWorks"), "All works opens in its column")+        } else {+            openAllWorks(in: app)+        }+        let row = app.elements(withIdentifierPrefix: "work-row-")+            .matching(NSPredicate(format: "label BEGINSWITH %@", "Open Work Ashfall ")).firstMatch+        scrollUntilPresent(row, in: app, "The hiatus work is listed")+        let tabBar = app.tabBars.firstMatch+        if tabBar.exists {+            for _ in 0..<4 where row.frame.maxY > tabBar.frame.minY { app.swipeUp() }+        }+        if UIDevice.current.userInterfaceIdiom == .pad {+            let column = app.anyElement("wide-list-column")+            for _ in 0..<8 where !column.frame.contains(row.frame) { column.swipeUp() }+            XCTAssertTrue(column.frame.contains(row.frame), "The hiatus row is visible in its list column")+            row.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+        } else {+            scrollUntilTappableAndTap(row, in: app, "The hiatus work opens")+        }+        waitFor(app.buttons["work-detail-edit-button"], "Work Detail opens")+    }++    private func edit() {+        waitFor(app.buttons["work-detail-edit-button"], "Edit is available").tap()+        waitFor(app.textFields["work-detail-title-field"], "The editor opens")+    }++    private func tapDate() {+        tap(app.buttons["work-detail-return-date-button"], "The hiatus return date action is reachable")+        waitFor(app.datePickers.firstMatch, "The native date-only picker opens")+    }++    private func show(_ element: XCUIElement, _ message: String) {+        guard UIDevice.current.userInterfaceIdiom == .pad else {+            scrollUntilPresent(element, in: app, message)+            return+        }+        let column = app.anyElement("wide-detail-column")+        for _ in 0..<8 {+            if element.exists && column.frame.contains(element.frame) { return }+            if element.exists && element.frame.minY < column.frame.minY {+                column.swipeDown()+            } else {+                column.swipeUp()+            }+        }+        XCTAssertTrue(element.exists && column.frame.contains(element.frame),+            "\(message); element: \(element.exists ? String(describing: element.frame) : "absent"), column: \(column.frame)")+    }++    private func tap(_ element: XCUIElement, _ message: String) {+        guard UIDevice.current.userInterfaceIdiom == .pad else {+            scrollUntilTappableAndTap(element, in: app, message)+            return+        }+        show(element, message)+        element.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+    }++    private func chooseFuture(months: Int = 1) {+        tapDate()+        let picker = app.datePickers.firstMatch+        let next = waitFor(picker.buttons["Next Month"], "Future months are available")+        for _ in 0..<months { next.tap() }+        let day = picker.buttons.matching(NSPredicate(+            format: "label MATCHES '.*[0-9]+.*' AND label != 'Previous Month' AND label != 'Next Month'"))+            .firstMatch+        waitFor(day, "A future civil day is selectable").tap()+        waitFor(app.buttons["work-detail-return-date-picker-done"], "Done chooses the date").tap()+        waitUntilGone(picker, "The date sheet closes")+    }++    private func save() {+        waitFor(app.buttons["work-detail-save-button"], "Save commits the draft").tap()+        waitUntilGone(app.textFields["work-detail-title-field"], "The editor closes after save")+    }++    private func cancel() {+        waitFor(app.buttons["work-detail-edit-cancel-button"], "Cancel discards the draft").tap()+        waitUntilGone(app.textFields["work-detail-title-field"], "The editor closes after cancel")+    }++    private var pending: XCUIElement { app.anyElement("work-detail-return-date-pending") }++    private func historyJourney(dated: Bool) {+        launch(history: true)+        if UIDevice.current.userInterfaceIdiom == .pad {+            if !app.buttons["sidebar-today"].exists {+                waitFor(app.buttons["sidebar-toggle"], "The sidebar opens").tap()+            }+            let today = waitFor(app.buttons["sidebar-today"], "Today is available")+            today.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+        } else {+            selectTab(.today, in: app)+        }+        waitFor(app.anyElement("today-header-date"), "Today opens")+        let launchDay = Date()+        let calendar = Calendar.current+        let yesterday = calendar.date(byAdding: .day, value: -1, to: launchDay)!+        let formatter = DateFormatter()+        formatter.locale = Locale(identifier: "en_US_POSIX")+        formatter.calendar = Calendar(identifier: .gregorian)+        formatter.timeZone = .current+        formatter.dateFormat = "yyyy-MM-dd"+        func select(_ day: Date) {+            let cell = app.anyElement("today-strip-\(formatter.string(from: day))")+            if !cell.exists {+                let direction = day < launchDay ? "today-week-previous" : "today-week-next"+                waitFor(app.anyElement(direction), "The adjacent week is available").tap()+            }+            waitFor(cell, "The selected day is on the strip").tap()+        }+        let release = app.buttons.matching(NSPredicate(+            format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@",+            "today-release-shelf-item-", "Ashfall,")).firstMatch+        select(yesterday)+        waitFor(release, "Yesterday has its release").tap()+        waitFor(app.buttons["work-detail-edit-button"], "Yesterday's release opens its work")+        edit()+        tap(app.buttons["work-detail-work-status-hiatus"], "Hiatus starts with Save")+        if dated { chooseFuture() }+        save()+        if UIDevice.current.userInterfaceIdiom == .pad {+            let today = waitFor(app.buttons["sidebar-today"], "Today remains available")+            today.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+        } else {+            app.goBack()+        }+        waitFor(app.anyElement("today-header-date"), "The selected day returns")+        waitFor(release, "Yesterday's release survives the saved hiatus")+        select(launchDay)+        waitUntilGone(release, "The Save day is paused")+        select(yesterday)+        waitFor(release, "Browsing back still preserves yesterday")+    }++    func testDatedHiatusPreservesYesterdayAfterSavingToday() { historyJourney(dated: true) }+    func testUndatedHiatusPreservesYesterdayAfterSavingToday() { historyJourney(dated: false) }++    func testSetChangeRemoveAndCancelPreserveTheCommittedReturnDate() {+        launch()+        show(pending, "The seeded tomorrow return is displayed")+        edit()+        let remove = app.buttons["work-detail-return-date-remove"]+        show(app.buttons["work-detail-work-status-hiatus"], "Status is reachable")+        if remove.exists { tap(remove, "Remove clears the starting date") }+        chooseFuture()+        save()+        show(pending, "The saved return is displayed")+        let original = pending.label+        XCTAssertTrue(original.contains("Hiatus return date"), "The display identifies the date for VoiceOver")++        edit()+        chooseFuture(months: 2)+        cancel()+        show(pending, "Cancellation restores the saved date")+        XCTAssertEqual(pending.label, original)++        edit()+        chooseFuture(months: 2)+        save()+        show(pending, "The changed date is displayed")+        XCTAssertNotEqual(pending.label, original)+        let changed = pending.label++        edit()+        tap(remove, "The optional date can be removed")+        XCTAssertEqual(app.buttons["work-detail-return-date-button"].label, "Hiatus return date, Set date")+        cancel()+        show(pending, "Cancelled removal preserves the date")+        XCTAssertEqual(pending.label, changed)+        edit()+        tap(remove, "Remove is still available")+        save()+        XCTAssertFalse(pending.exists)+        show(app.anyElement("work-detail-status-work"), "Undated hiatus remains visible")+        XCTAssertEqual(app.anyElement("work-detail-status-work").label, "Work: On hiatus")+    }++    func testChoosingTodayReturnsImmediatelyAndANewHiatusStartsWithoutADate() {+        launch()+        edit()+        let remove = app.buttons["work-detail-return-date-remove"]+        show(app.buttons["work-detail-work-status-hiatus"], "Status is reachable")+        if remove.exists { tap(remove, "Remove clears the starting date") }+        tapDate()+        waitFor(app.buttons["work-detail-return-date-picker-done"], "Today can be chosen").tap()+        save()+        XCTAssertFalse(pending.exists)+        edit()+        show(app.buttons["work-detail-work-status-ongoing"], "The returned work is ongoing")+        XCTAssertTrue(app.buttons["work-detail-work-status-ongoing"].isSelected)+        tap(app.buttons["work-detail-work-status-hiatus"], "A new hiatus can begin")+        XCTAssertEqual(app.buttons["work-detail-return-date-button"].label, "Hiatus return date, Set date")+        XCTAssertFalse(remove.exists, "The previous return date is not reused")+        save()+    }++    func testReturnDateControlsRemainReachableAtLargestAccessibilityTextSize() {+        launch(accessibilitySize: true)+        edit()+        show(app.buttons["work-detail-work-status-hiatus"], "Status remains reachable")+        chooseFuture()+        let button = app.buttons["work-detail-return-date-button"]+        show(button, "The selected date remains visible")+        XCTAssertTrue(button.label.contains("Hiatus return date"))+        tap(app.buttons["work-detail-return-date-remove"], "Remove remains operable")+        XCTAssertEqual(button.label, "Hiatus return date, Set date")+        cancel()+    }+}
Asterism/AsterismUITests/TodayUITests.swift Modified
diff --git a/Asterism/AsterismUITests/TodayUITests.swift b/Asterism/AsterismUITests/TodayUITests.swiftindex 7a4824b6..670ac49d 100644--- a/Asterism/AsterismUITests/TodayUITests.swift+++ b/Asterism/AsterismUITests/TodayUITests.swift@@ -12,8 +12,8 @@ import XCTest /// 5.3, 5.5, 5.6, 5.8, 10.3), over `seeded-today`: four works on `today.test`, /// three of them carrying release days across the current weekday and the one /// before it — **Kite Season** due today, **Salt Harvest** due the previous-/// weekday, and **Paper Lantern** on hiatus with both days, so it is scheduled-/// by its days and excluded by its status on both of them at once. The fourth,+/// weekday, and **Paper Lantern** on hiatus from the launch day with both days,+/// preserving its previous-day release while excluding the current day. The fourth, /// **Ember Road**, is finished and being caught up on with no days at all /// (`catch-up-mode`), which is what the `Catching up` section lists. Two /// entries are dated the current day and two the previous day, and the site is@@ -715,7 +715,7 @@ final class TodayUITests: XCTestCase {      /// Req 5.5's releases-first placement: on the current day the plan comes     /// before the record. Req 6.1 rides along — Paper Lantern is on hiatus with-    /// the current weekday among its days, and is in neither releases section.+    /// the current weekday among its days, and is excluded from today's releases.     func testTheCurrentDayLeadsWithItsReleases() {         launchToday() @@ -735,7 +735,7 @@ final class TodayUITests: XCTestCase {         // Req 6.1: scheduled by its days, excluded by its status.         XCTAssertFalse(             release.label.contains("Paper Lantern"),-            "Req 6.1: a work on hiatus is never in a releases section")+            "Req 6.1: a work paused on this day is excluded")          // `catch-up-mode`: the third section, after the releases and before the         // notes, with the one work the reader is behind on.@@ -936,13 +936,12 @@ final class TodayUITests: XCTestCase {             app.anyElement("today-section-releases").frame.minY,             "Req 5.5: a past day reads as a record — notes first") -        XCTAssertEqual(releaseRows.count, 1, "Only Salt Harvest is due on the previous weekday")-        XCTAssertTrue(-            releaseRows.firstMatch.label.hasPrefix("Salt Harvest, "),-            "…and it is the work the fixture put there — was \"\(releaseRows.firstMatch.label)\"")-        XCTAssertFalse(-            releaseRows.firstMatch.label.contains("Paper Lantern"),-            "Req 6.1: the work on hiatus is excluded on this day too")+        XCTAssertEqual(releaseRows.count, 2, "Salt Harvest and Paper Lantern were due before hiatus Save")+        let releases = releaseRows.allElementsBoundByIndex.map(\.label)+        for title in ["Salt Harvest", "Paper Lantern"] {+            XCTAssertTrue(releases.contains { $0.hasPrefix("\(title), ") },+                "The previous day preserves \(title)'s release")+        }          let settled = expectation(for: NSPredicate(format: "count == 2"), evaluatedWith: recentRows)         XCTAssertEqual(
Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift b/Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swiftindex 2283b9d4..8d14d7b5 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: BackupV17Work) -> ArchiveThumbnail {+    static func of(_ record: BackupV18Work) -> 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: BackupV17Site) -> Site {+    static func makeSite(_ record: BackupV18Site) -> Site {         let site = Site(hostname: record.hostname, displayName: record.displayName)         site.modeRaw = record.mode.rawValue         return site     }      static func makeTitlePattern(-        _ record: BackupV17TitlePattern, site: Site?+        _ record: BackupV18TitlePattern, site: Site?     ) throws -> TitlePattern {         return try TitlePattern(             id: record.id,@@ -87,7 +87,7 @@ internal enum ArchiveRecordBuilders {     }      static func makeURLRule(-        _ record: BackupV17URLRule, site: Site?+        _ record: BackupV18URLRule, 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: BackupV17WorkType) -> WorkTypeEntity {+    static func makeWorkType(_ record: BackupV18WorkType) -> WorkTypeEntity {         makeWorkType(             id: record.id, name: record.name,             state: ToleratedEnum.read(record.stateRaw, default: .active),@@ -131,14 +131,14 @@ internal enum ArchiveRecordBuilders {     /// `WorkSiteMembership`, which `makeMembership` below builds from the     /// archive's own records.     static func makeWork(-        _ record: BackupV17Work, thumbnail: ArchiveThumbnail = .none-    ) -> Work {+        _ record: BackupV18Work, thumbnail: ArchiveThumbnail = .none+    ) throws -> Work {         let work = Work(             id: record.id,             displayTitle: record.displayTitle,             timestamp: record.createdAt         )-        LibraryRepository.apply(record, to: work, thumbnail: thumbnail)+        try LibraryRepository.apply(record, to: work, thumbnail: thumbnail)         CatchUpWriter.apply(record.catchUpRecord, to: [work])         return work     }@@ -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: BackupV17Membership, work: Work?, site: Site?+        _ record: BackupV18Membership, 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: BackupV17DistinctPair) -> WorkDistinctPair {+    static func makeDistinctPair(_ record: BackupV18DistinctPair) -> 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: BackupV17Series) -> Series {+    static func makeSeries(_ record: BackupV18Series) -> 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: BackupV17Link) -> WorkLink {+    static func makeLink(_ record: BackupV18Link) -> 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: BackupV17Creator) -> Creator {+    static func makeCreator(_ record: BackupV18Creator) -> 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: BackupV17CreatorRole) -> CreatorRole {+    static func makeCreatorRole(_ record: BackupV18CreatorRole) -> 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: BackupV17CreatorRole, position: Int, at positionModifiedAt: Date+        _ record: BackupV18CreatorRole, 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: BackupV17Credit) -> WorkCredit {+    static func makeCredit(_ record: BackupV18Credit) -> 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: BackupV17Entry) -> Entry {+    static func makeEntry(_ record: BackupV18Entry) -> 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: BackupV17Character) -> CharacterRecord {+    static func makeCharacter(_ record: BackupV18Character) -> CharacterRecord {         makeRecord(CharacterRecord.self, record)     } -    static func makeSuppression(_ record: BackupV17Suppression) -> CharacterSuppression {+    static func makeSuppression(_ record: BackupV18Suppression) -> CharacterSuppression {         makeSuppressionRow(CharacterSuppression.self, record)     } -    static func makePlace(_ record: BackupV17Place) -> Place {+    static func makePlace(_ record: BackupV18Place) -> Place {         makeRecord(Place.self, record)     } -    static func makePlaceSuppression(_ record: BackupV17PlaceSuppression) -> PlaceSuppression {+    static func makePlaceSuppression(_ record: BackupV18PlaceSuppression) -> PlaceSuppression {         makeSuppressionRow(PlaceSuppression.self, record)     } }
Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismCapabilities.swiftindex 9fa0cf8d..afcf7e33 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 `BackupV17Codec` stamps. The literal has not moved with+        /// which is what `BackupV18Codec` 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).-    /// `BackupV17Codec` stamps the literal `"multi-site"` rather than reading+    /// `BackupV18Codec` 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`,
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swiftindex f68d6520..4794dfaf 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift@@ -1,7 +1,7 @@ import Foundation import SwiftData -/// The live schema. V18 adds an independent action table with scalar work IDs.+/// Frozen V18 schema. Stored models are in AsterismSchemaV18Models.swift. public enum AsterismSchemaV18: VersionedSchema {     public static let versionIdentifier = Schema.Version(18, 0, 0) @@ -24,18 +24,3 @@ public enum AsterismV18MigrationPlan: SchemaMigrationPlan {          .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-        }-    }-}
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18Models.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18Models.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18Models.swiftnew file mode 100644index 00000000..a27183f9--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18Models.swift@@ -0,0 +1,295 @@+import Foundation+import SwiftData++/// Frozen V18 stored model snapshot. Defaults retain CaptureTitleSource.manual,+/// EntryIdentityBasis.conservative, TitleProvenance.manual, WorkStatus.ongoing,+/// ReadingStatus.reading, SiteMode.untaught, WorkTypeState.active,+/// CharacterSuppressionKind.candidate, CharacterSuppressionStatus.active,+/// URLRuleOrigin.readerTaught and WorkURLIdentityState.none. Thumbnail .externalStorage and all inverses+/// are part of this frozen shape. ReleaseDay and ThumbnailShape spellings,+/// SHA-256 digests, JunkSuffixRule and SegmentPositionSpec retain their contracts.+extension AsterismSchemaV18 {++@Model+public final class Entry {+    public var id: UUID = UUID()+    public var captureTitle: String = ""+    public var captureTitleSourceRaw: String = CaptureTitleSource.manual.rawValue+    public var rawURLString: String = ""+    public var canonicalURLString: String?+    public var hostname: String = ""+    public var site: Site?+    public var entryIdentityKey: String = ""+    public var conservativeIdentityKey: String = ""+    public var identityBasisRaw: String = EntryIdentityBasis.conservative.rawValue+    public var urlWorkIdentity: String?+    public var chapterSequence: String?+    public var chapterTitle: String?+    public var note: String = ""+    public var ratingRaw: String?+    public var firstCapturedAt: Date = Date(timeIntervalSince1970: 0)+    public var lastSharedAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var work: Work?+    public var intentionallyUnattached: Bool = false+    public var characterExtractionFingerprint: String?+    public var citationsData: Data?++    public init() {}+}++@Model+public final class Work {+    public var id: UUID = UUID()+    public var displayTitle: String = ""+    public var lastParsedTitle: String?+    public var genericNotes: String = ""+    public var workTypeID: UUID?+    public var genreTags: [String] = []+    public var titleProvenanceRaw: String = TitleProvenance.manual.rawValue+    public var workStatusRaw: String = WorkStatus.ongoing.rawValue+    public var readingStatusRaw: String = ReadingStatus.reading.rawValue+    public var verdict: String = ""+    public var seriesID: UUID?+    public var seriesPosition: Double?+    public var releaseDaysRaw: [String] = []+    public var catchUpConfirmationData: Data? = nil+    public var lastChapterOverrideData: Data? = nil+    @Attribute(.externalStorage)+    public var thumbnailData: Data?+    public var thumbnailShapeRaw: String?+    public var thumbnailDigest: String?+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var genericNotesExtractionFingerprint: String?+    @Relationship(deleteRule: .nullify, inverse: \Entry.work)+    public var entries: [Entry]?+    @Relationship(deleteRule: .nullify, inverse: \Character.work)+    public var characters: [Character]?+    @Relationship(deleteRule: .nullify, inverse: \CharacterSuppression.work)+    public var characterSuppressions: [CharacterSuppression]?+    @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.work)+    public var siteMemberships: [WorkSiteMembership]? = []++    public init() {}+}++@Model+public final class Site {+    public var hostname: String = ""+    public var displayName: String = ""+    public var modeRaw: String = SiteMode.untaught.rawValue+    @Relationship(deleteRule: .cascade, inverse: \TitlePattern.site)+    public var patterns: [TitlePattern]?+    @Relationship(deleteRule: .cascade, inverse: \URLRulePattern.site)+    public var urlRules: [URLRulePattern]?+    @Relationship(deleteRule: .nullify, inverse: \Entry.site)+    var entries: [Entry]?+    @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.site)+    var workMemberships: [WorkSiteMembership]?++    public init() {}+}++@Model+public final class TitlePattern {+    public var id: UUID = UUID()+    public var version: Int = 1+    public var isActive: Bool = false+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var definitionData: Data?+    public var site: Site?++    public init() {}+}++@Model+public final class URLRulePattern {+    public var id: UUID = UUID()+    public var version: Int = 1+    public var isCurrent: Bool = false+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var originRaw: String = URLRuleOrigin.readerTaught.rawValue+    public var definitionData: Data = Data()+    public var site: Site?++    public init() {}+}++@Model+public final class WorkTypeEntity {+    public var id: UUID = UUID()+    public var name: String = ""+    public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var stateRaw: String = WorkTypeState.active.rawValue+    public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var canonicalID: UUID?+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class Character {+    public var id: UUID = UUID()+    public var name: String = ""+    public var nameKey: String = ""+    public var aliases: [String] = []+    public var note: String = ""+    public var factsData: Data?+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var work: Work?++    public init() {}+}++@Model+public final class CharacterSuppression {+    public var id: UUID = UUID()+    public var work: Work?+    public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+    public var nameKey: String = ""+    public var sourceKindRaw: String?+    public var sourceEntryID: UUID?+    public var evidence: String?+    public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+    public var actionAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class WorkSiteMembership {+    public var id: UUID = UUID()+    public var hostname: String = ""+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var urlIdentity: String?+    public var urlIdentityStateRaw: String = WorkURLIdentityState.none.rawValue+    public var urlIdentityRuleID: UUID?+    public var workURLString: String?+    public var workID: UUID?+    public var work: Work?+    public var site: Site?++    public init() {}+}++@Model+public final class WorkDistinctPair {+    public var id: UUID = UUID()+    public var lowerWorkID: UUID = UUID()+    public var higherWorkID: UUID = UUID()+    public var recordedAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class Series {+    public var id: UUID = UUID()+    public var name: String = ""+    public var notes: String = ""+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class WorkLink {+    public var id: UUID = UUID()+    public var lowerWorkID: UUID = UUID()+    public var higherWorkID: UUID = UUID()+    public var linkType: String = ""+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class Creator {+    public var id: UUID = UUID()+    public var name: String = ""+    public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var notes: String = ""+    public var notesModifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var stateRaw: String = "active"+    public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var canonicalID: UUID?+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class CreatorRole {+    public var id: UUID = UUID()+    public var name: String = ""+    public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var position: Int = 0+    public var positionModifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var stateRaw: String = "active"+    public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var canonicalID: UUID?+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class WorkCredit {+    public var id: UUID = UUID()+    public var workID: UUID = UUID()+    public var creatorID: UUID = UUID()+    public var roleIDs: [String] = []+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class Place {+    public var id: UUID = UUID()+    public var name: String = ""+    public var nameKey: String = ""+    public var aliases: [String] = []+    public var note: String = ""+    public var factsData: Data?+    public var createdAt: Date = Date(timeIntervalSince1970: 0)+    public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+    public var workID: UUID = UUID()++    public init() {}+}++@Model+public final class PlaceSuppression {+    public var id: UUID = UUID()+    public var workID: UUID = UUID()+    public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+    public var nameKey: String = ""+    public var sourceKindRaw: String?+    public var sourceEntryID: UUID?+    public var evidence: String?+    public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+    public var actionAt: Date = Date(timeIntervalSince1970: 0)++    public init() {}+}++@Model+public final class NoEpisodeAction {+    public var workID: UUID = UUID()+    public var key: String = ""+    public var payloadData: Data = Data()++    public init() {}+}++}
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swiftnew file mode 100644index 00000000..c11dfe03--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift@@ -0,0 +1,42 @@+import Foundation+import SwiftData++/// The live schema. V19 adds one optional authored publication-state blob to Work.+public enum AsterismSchemaV19: VersionedSchema {+    public static let versionIdentifier = Schema.Version(19, 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 AsterismV19MigrationPlan: SchemaMigrationPlan {+    public static var schemas: [any VersionedSchema.Type] {+        [AsterismSchemaV16.self, AsterismSchemaV17.self, AsterismSchemaV18.self, AsterismSchemaV19.self]+    }++    public static var stages: [MigrationStage] {+        [.lightweight(fromVersion: AsterismSchemaV16.self, toVersion: AsterismSchemaV17.self),+         .lightweight(fromVersion: AsterismSchemaV17.self, toVersion: AsterismSchemaV18.self),+         .lightweight(fromVersion: AsterismSchemaV18.self, toVersion: AsterismSchemaV19.self)]+    }+}++extension AsterismSchemaV19 {+    @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+        }+    }+}
Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swiftindex fc2cb7ea..d579d383 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: [BackupV17Entry]-    let sites: [BackupV17Site]-    let titlePatterns: [BackupV17TitlePattern]-    let urlRules: [BackupV17URLRule]+    let entries: [BackupV18Entry]+    let sites: [BackupV18Site]+    let titlePatterns: [BackupV18TitlePattern]+    let urlRules: [BackupV18URLRule]     /// 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: [BackupV17Membership]+    let memberships: [BackupV18Membership] }  /// 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 BackupV17ExportError.referencesStillArriving(+                throw BackupV18ExportError.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 BackupV17ExportError.referencesStillArriving(+                throw BackupV18ExportError.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: [BackupV17Site] = []-        var wirePatterns: [BackupV17TitlePattern] = []-        var wireRules: [BackupV17URLRule] = []+        var wireSites: [BackupV18Site] = []+        var wirePatterns: [BackupV18TitlePattern] = []+        var wireRules: [BackupV18URLRule] = []         for site in projected {-            wireSites.append(mapV17SiteRecord(site))+            wireSites.append(mapV18SiteRecord(site))             for projectedPattern in site.patterns             where !omittedTitlePatternIDs.contains(projectedPattern.pattern.id) {                 wirePatterns.append(-                    try mapV17TitlePatternRecord(projectedPattern, hostname: site.hostname))+                    try mapV18TitlePatternRecord(projectedPattern, hostname: site.hostname))             }             for projectedRule in site.urlRules             where !omittedURLRuleIDs.contains(projectedRule.rule.id) {-                wireRules.append(try mapV17URLRuleRecord(projectedRule, hostname: site.hostname))+                wireRules.append(try mapV18URLRuleRecord(projectedRule, hostname: site.hostname))             }         }          return ArchiveCommonProjection(             groups: groups,-            entries: try groups.entries.map { try mapV17EntryRecord($0, citations: citations) },+            entries: try groups.entries.map { try mapV18EntryRecord($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 BackupV17ExportError.unrepresentableValue(+                throw BackupV18ExportError.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 BackupV17ExportError.unrepresentableValue(+                    throw BackupV18ExportError.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 BackupV17ExportError.unrepresentableValue(+                    throw BackupV18ExportError.unrepresentableValue(                         record: record, field: "last chapter override", value: String(describing: error))                 }             }@@ -253,6 +253,15 @@ extension LibraryRepository {             // status the reader never chose as though they had.             try require(WorkStatus(rawValue: work.workStatusRaw),                 record, "work status", work.workStatusRaw)+            do {+                if let state = try work.decodedPublicationState(),+                   state.authoredStatus.rawValue != work.workStatusRaw {+                    throw WorkPublicationState.StateError.invalidStatus+                }+            } catch {+                throw BackupV18ExportError.unrepresentableValue(+                    record: record, field: "publication state", value: String(describing: error))+            }             try require(ReadingStatus(rawValue: work.readingStatusRaw),                 record, "reading status", work.readingStatusRaw)             // `series-and-related-works` Req 13.5, on the same terms as the@@ -266,22 +275,22 @@ extension LibraryRepository {             case (nil, nil):                 break             case (let id?, nil):-                throw BackupV17ExportError.unrepresentableValue(+                throw BackupV18ExportError.unrepresentableValue(                     record: record, field: "series membership",                     value: "series \(id) with no position")             case (nil, let position?):-                throw BackupV17ExportError.unrepresentableValue(+                throw BackupV18ExportError.unrepresentableValue(                     record: record, field: "series membership",                     value: "position \(position) with no series")             case (_?, let position?):                 guard position.isFinite else {-                    throw BackupV17ExportError.unrepresentableValue(+                    throw BackupV18ExportError.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 BackupV17ExportError.unrepresentableValue(+                    throw BackupV18ExportError.unrepresentableValue(                         record: record, field: "series position", value: String(position))                 }             }@@ -289,7 +298,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 `mapV17WorkRecord`, against+            // archive exports. It is refused in `mapV18WorkRecord`, against             // exactly the bytes the record takes (Q79).             //             // `update-schedule` Req 8.3, on the statuses' terms: the accessor@@ -329,7 +338,7 @@ extension LibraryRepository {             // `formRaw` that no longer exists.             do { _ = try pattern.storedDefinition }             catch {-                throw BackupV17ExportError.unrepresentableValue(+                throw BackupV18ExportError.unrepresentableValue(                     record: record, field: "definition", value: String(describing: error))             }         }@@ -367,7 +376,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 BackupV17ExportError.unrepresentableValue(+                throw BackupV18ExportError.unrepresentableValue(                     record: "URL rule \(id)", field: "definition",                     value: "\(rule.definitionData.count) bytes that do not decode")             }@@ -418,7 +427,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 BackupV17ExportError.unrepresentableValue(+                throw BackupV18ExportError.unrepresentableValue(                     record: "Title rule \(id)", field: "definition",                     value: pattern.definitionData.map { "\($0.count) bytes that do not decode" }                         ?? "no stored definition")@@ -474,7 +483,7 @@ extension LibraryRepository {         _ value: Value?, _ record: String, _ field: String, _ raw: String     ) throws {         guard value == nil else { return }-        throw BackupV17ExportError.unrepresentableValue(record: record, field: field, value: raw)+        throw BackupV18ExportError.unrepresentableValue(record: record, field: field, value: raw)     }      /// Req 3.7's third face: a hostname whose *projected* tuple the archive@@ -499,7 +508,7 @@ extension LibraryRepository {             switch site.mode {             case .taught:                 guard activePatterns != 1 else { continue }-                throw BackupV17ExportError.referencesStillArriving(+                throw BackupV18ExportError.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 +516,7 @@ extension LibraryRepository {                     $0.rule.origin == .importedV2 && !$0.isCurrent                 }                 guard !site.patterns.isEmpty || currentRules > 0 || !historyOnly else { continue }-                throw BackupV17ExportError.referencesStillArriving(+                throw BackupV18ExportError.referencesStillArriving(                     detail: "site \(site.hostname) is untaught while still holding rules, "                         + "so the teaching that owns them has not arrived")             }@@ -528,10 +537,10 @@ extension LibraryRepository {     /// problem surfacing as a broken file, which is exactly what this gate     /// exists to say first.     internal static func requireCitationsResolve(-        entries: [BackupV17Entry],-        memberships: [BackupV17Membership],-        titlePatterns: [BackupV17TitlePattern],-        urlRules: [BackupV17URLRule]+        entries: [BackupV18Entry],+        memberships: [BackupV18Membership],+        titlePatterns: [BackupV18TitlePattern],+        urlRules: [BackupV18URLRule]     ) throws {         let rulesByID = Dictionary(urlRules.map { ($0.id, $0) }, uniquingKeysWith: { lhs, _ in lhs })         let patternHostnames = Dictionary(@@ -571,14 +580,14 @@ extension LibraryRepository {      private static func crossSiteCitation(         _ record: String, _ field: String, taughtFor hostname: String-    ) -> BackupV17ExportError {+    ) -> BackupV18ExportError {         .referencesStillArriving(             detail: "\(record) names \(field), which is taught for \(hostname)")     }      private static func missingCitation(         _ record: String, _ field: String-    ) -> BackupV17ExportError {+    ) -> BackupV18ExportError {         .referencesStillArriving(             detail: "\(record) names \(field), which the library does not hold")     }@@ -625,9 +634,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 mapV17EntryRecord(+    internal static func mapV18EntryRecord(         _ group: EntryGroup, citations cache: EntryCitationsCache-    ) throws -> BackupV17Entry {+    ) throws -> BackupV18Entry {         let snap = try snapshot(group)         let entry = group.representative         let carrier = group.carrier@@ -637,7 +646,7 @@ extension LibraryRepository {             citations.chapterTitle = carried.chapterTitle             citations.workAssignment = carried.workAssignment         }-        return BackupV17Entry(+        return BackupV18Entry(             id: snap.id,             captureTitle: snap.captureTitle,             captureTitleSource: snap.captureTitleSource,@@ -717,32 +726,32 @@ extension LibraryRepository {         guard let raw = group.carrier.thumbnailShapeRaw else { return nil }         let titled = "Work “\(group.carrier.displayTitle)”"         guard let shape = ThumbnailShape(rawValue: raw) else {-            throw BackupV17ExportError.unrepresentableValue(-                record: titled, field: BackupV17ExportError.thumbnailField, value: raw)+            throw BackupV18ExportError.unrepresentableValue(+                record: titled, field: BackupV18ExportError.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 BackupV17ExportError.unrepresentableValue(-                record: titled, field: BackupV17ExportError.thumbnailField,+            throw BackupV18ExportError.unrepresentableValue(+                record: titled, field: BackupV18ExportError.thumbnailField,                 value: "\(bytes.count) bytes that are not a \(raw) cover")         }         return bytes     } -    internal static func mapV17WorkRecord(+    internal static func mapV18WorkRecord(         _ group: WorkGroup,         canonicalWorkIDs: [UUID: UUID],         types: WorkTypeDirectory-    ) throws -> BackupV17Work {+    ) throws -> BackupV18Work {         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 `BackupV17Work` carries is a read+            // exported work to fill a field no `BackupV18Work` carries is a read             // this path skips.             credits: .empty,             // This mapper reads only Work-owned columns. The archive projects@@ -759,7 +768,7 @@ extension LibraryRepository {         case .configured(let id):             (workTypeID, typeName) = (id, types.resolve(id)?.name)         }-        return BackupV17Work(+        return BackupV18Work(             id: snap.id,             displayTitle: snap.displayTitle,             lastParsedTitle: snap.lastParsedTitle,@@ -768,7 +777,7 @@ extension LibraryRepository {             titleProvenance: snap.titleProvenance,             // Req 8.1: the carrier's three, as `snapshot` already resolved them             // for a split group (Req 7.2).-            workStatus: snap.workStatus,+            workStatus: snap.authoredWorkStatus,             readingStatus: snap.readingStatus,             verdict: snap.verdict,             // `update-schedule` Req 8.1, off the snapshot for the statuses'@@ -825,7 +834,8 @@ extension LibraryRepository {             }(),             lastChapterOverrideAt: snap.catchUp.override.map {                 MillisecondInstant.date(fromMilliseconds: $0.atMilliseconds)-            }+            },+            publicationState: snap.publicationState         )     } @@ -843,7 +853,7 @@ extension LibraryRepository {     /// there.     private static func mapMembershipRecords(         _ rows: [WorkSiteMembership]-    ) -> [BackupV17Membership] {+    ) -> [BackupV18Membership] {         var byKey: [MembershipReconciler.Key: [WorkSiteMembership]] = [:]         var unattributed: [WorkSiteMembership] = []         for row in rows {@@ -854,8 +864,8 @@ extension LibraryRepository {             byKey[MembershipReconciler.Key(workID: workID, hostname: row.hostname), default: []]                 .append(row)         }-        func record(_ row: WorkSiteMembership, workURLString: String?) -> BackupV17Membership {-            BackupV17Membership(+        func record(_ row: WorkSiteMembership, workURLString: String?) -> BackupV18Membership {+            BackupV18Membership(                 id: row.id, workID: row.resolvedWorkID, hostname: row.hostname,                 createdAt: row.createdAt, urlIdentity: row.urlIdentity,                 urlIdentityState: row.urlIdentityState,@@ -870,7 +880,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: [BackupV17Membership] = []+        var records: [BackupV18Membership] = []         for rows in byKey.values {             let ordered = MembershipReconciler.survivorFirst(rows)             guard let keeper = ordered.first else { continue }@@ -908,7 +918,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 -> [BackupV17Series] {+    internal static func projectSeries(context: ModelContext) throws -> [BackupV18Series] {         var byID: [UUID: Series] = [:]         for row in try context.fetch(FetchDescriptor<Series>()) {             guard let held = byID[row.id] else {@@ -919,7 +929,7 @@ extension LibraryRepository {         }         return byID.values             .map {-                BackupV17Series(+                BackupV18Series(                     id: $0.id, name: $0.name, notes: $0.notes,                     createdAt: $0.createdAt, modifiedAt: $0.modifiedAt)             }@@ -941,7 +951,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 -> [BackupV17Link] {+    internal static func projectLinks(context: ModelContext) throws -> [BackupV18Link] {         var byKey: [WorkPairKey: [WorkLink]] = [:]         for row in try context.fetch(FetchDescriptor<WorkLink>())         where row.lowerWorkID != row.higherWorkID {@@ -951,7 +961,7 @@ extension LibraryRepository {             guard let survivor = MembershipReconciler.survivorFirstLinks(rows).first else {                 return nil             }-            return BackupV17Link(+            return BackupV18Link(                 id: survivor.id, lowerWorkID: key.lower, higherWorkID: key.higher,                 linkType: survivor.linkType, createdAt: survivor.createdAt,                 modifiedAt: survivor.modifiedAt)@@ -983,7 +993,7 @@ extension LibraryRepository {     /// the same number the next local pass would.     internal static func projectCredits(         context: ModelContext, creators: CreatorDirectory-    ) throws -> [BackupV17Credit] {+    ) throws -> [BackupV18Credit] {         var byKey: [CreditReconciler.Key: [WorkCredit]] = [:]         for row in try context.fetch(FetchDescriptor<WorkCredit>()) {             let key = CreditReconciler.Key(@@ -993,7 +1003,7 @@ extension LibraryRepository {         return byKey.compactMap { _, rows in             let ordered = WorkCreditSupport.survivorFirstCredits(rows)             guard let head = ordered.first else { return nil }-            return BackupV17Credit(+            return BackupV18Credit(                 id: head.id, workID: head.workID, creatorID: head.creatorID,                 roleIDs: WorkCreditSupport.roleIDs(ordered.flatMap(\.roleIDs)),                 createdAt: head.createdAt,@@ -1004,7 +1014,7 @@ extension LibraryRepository {      internal static func projectDistinctPairs(         context: ModelContext-    ) throws -> [BackupV17DistinctPair] {+    ) throws -> [BackupV18DistinctPair] {         var byKey: [WorkPairKey: [WorkDistinctPair]] = [:]         for row in try context.fetch(FetchDescriptor<WorkDistinctPair>())         where row.lowerWorkID != row.higherWorkID {@@ -1016,7 +1026,7 @@ extension LibraryRepository {             guard let survivor = MembershipReconciler.survivorFirstPairs(rows).first else {                 return nil             }-            return BackupV17DistinctPair(+            return BackupV18DistinctPair(                 id: survivor.id, lowerWorkID: key.lower, higherWorkID: key.higher,                 recordedAt: survivor.recordedAt)         }@@ -1026,20 +1036,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 mapV17SiteRecord(+    internal static func mapV18SiteRecord(         _ projected: SiteUnionProjection.ProjectedSite-    ) -> BackupV17Site {-        BackupV17Site(+    ) -> BackupV18Site {+        BackupV18Site(             hostname: projected.hostname,             displayName: projected.displayName,             mode: projected.mode         )     } -    internal static func mapV17TitlePatternRecord(+    internal static func mapV18TitlePatternRecord(         _ projected: SiteUnionProjection.ProjectedTitlePattern, hostname: String-    ) throws -> BackupV17TitlePattern {-        BackupV17TitlePattern(+    ) throws -> BackupV18TitlePattern {+        BackupV18TitlePattern(             id: projected.pattern.id,             siteHostname: hostname,             // The version stored on the row the per-UUID reduction kept, without@@ -1054,17 +1064,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 mapV17URLRuleRecord(+    internal static func mapV18URLRuleRecord(         _ projected: SiteUnionProjection.ProjectedURLRule, hostname: String-    ) throws -> BackupV17URLRule {+    ) throws -> BackupV18URLRule {         let definition: URLRuleDefinition         do { definition = try projected.rule.definition }         catch {-            throw BackupV17ExportError.unrepresentableValue(+            throw BackupV18ExportError.unrepresentableValue(                 record: "URL rule \(projected.rule.id)", field: "definition",                 value: "\(projected.rule.definitionData.count) bytes that do not decode")         }-        return BackupV17URLRule(+        return BackupV18URLRule(             id: projected.rule.id,             version: projected.rule.version,             isCurrent: projected.isCurrent,
Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swiftindex 501f8d9e..501da659 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: [BackupV17Entry],-        works: [BackupV17Work],-        memberships: [BackupV17Membership],-        distinctPairs: [BackupV17DistinctPair],-        sites: [BackupV17Site],-        titlePatterns: [BackupV17TitlePattern],-        urlRules: [BackupV17URLRule],-        series: [BackupV17Series],-        links: [BackupV17Link],-        creators: [BackupV17Creator],-        creatorRoles: [BackupV17CreatorRole],-        credits: [BackupV17Credit],+        entries: [BackupV18Entry],+        works: [BackupV18Work],+        memberships: [BackupV18Membership],+        distinctPairs: [BackupV18DistinctPair],+        sites: [BackupV18Site],+        titlePatterns: [BackupV18TitlePattern],+        urlRules: [BackupV18URLRule],+        series: [BackupV18Series],+        links: [BackupV18Link],+        creators: [BackupV18Creator],+        creatorRoles: [BackupV18CreatorRole],+        credits: [BackupV18Credit],         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: BackupV17Site,-        patterns: [BackupV17TitlePattern],-        rules: [BackupV17URLRule]+        _ site: BackupV18Site,+        patterns: [BackupV18TitlePattern],+        rules: [BackupV18URLRule]     ) 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: BackupV17Membership,+        _ membership: BackupV18Membership,         siteHostnames: Set<String>,-        rulesByID: [UUID: BackupV17URLRule]+        rulesByID: [UUID: BackupV18URLRule]     ) 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: BackupV17Entry,+        _ entry: BackupV18Entry,         siteHostnames: Set<String>,         workIDs: Set<UUID>,         hostnamesByWork: [UUID: Set<String>],-        patternsByID: [UUID: BackupV17TitlePattern],-        rulesByID: [UUID: BackupV17URLRule]+        patternsByID: [UUID: BackupV18TitlePattern],+        rulesByID: [UUID: BackupV18URLRule]     ) 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: BackupV17Entry, rulesByID: [UUID: BackupV17URLRule]+        _ cited: CitedRule, entry: BackupV18Entry, rulesByID: [UUID: BackupV18URLRule]     ) -> Bool {         rulesByID[cited.id]?.siteHostname == entry.hostname     }      private static func requireSameSiteRule(         _ cited: CitedRule,-        entry: BackupV17Entry,-        rulesByID: [UUID: BackupV17URLRule]+        entry: BackupV18Entry,+        rulesByID: [UUID: BackupV18URLRule]     ) throws {         guard resolvesSameSite(cited, entry: entry, rulesByID: rulesByID) else {             throw invalid(@@ -512,10 +512,10 @@ internal enum BackupArchiveReferenceChecks {     }      private static func validateEntryRuleReference(-        _ entry: BackupV17Entry,+        _ entry: BackupV18Entry,         field: String,         cited: CitedRule?,-        rulesByID: [UUID: BackupV17URLRule]+        rulesByID: [UUID: BackupV18URLRule]     ) throws {         guard let cited else { return }         guard resolvesSameSite(cited, entry: entry, rulesByID: rulesByID) else {
Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupExporter.swiftindex 3ae5ee21..3642f3b6 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. `BackupV17Exporter` is the only producer.+/// cleaned up afterwards. `BackupV18Exporter` is the only producer. public struct BackupExportResult: Sendable {     public let fileURL: URL 
Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swiftindex 7ab18182..a4144612 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: `BackupV17ExportError.tornGroups` when the store holds a torn+    /// - Throws: `BackupV18ExportError.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 BackupV17ExportError.tornGroups(+            throw BackupV18ExportError.tornGroups(                 tornGroupsPayload(                     tornEntries: tornEntries, tornWorks: tornWorks,                     tornRecordCount: tornCharacters.count + tornPlaces.count,
Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportCreators.swiftindex 2bd272d4..f488f256 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: [BackupV17Creator],-        creatorRoles: [BackupV17CreatorRole],+        creators: [BackupV18Creator],+        creatorRoles: [BackupV18CreatorRole],         importedAt: Date,         context: ModelContext,         saveStrategy: any RepositorySaveStrategy@@ -72,7 +72,7 @@ extension LibraryRepository {      /// - Returns: whether anything was written.     private static func mergeImportedCreators(-        _ records: [BackupV17Creator], context: ModelContext+        _ records: [BackupV18Creator], 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: BackupV17Creator]+        _ survivor: UUID, local: CreatorDirectory, archive: [UUID: BackupV18Creator]     ) -> 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: [BackupV17CreatorRole], importedAt: Date, context: ModelContext+        _ records: [BackupV18CreatorRole], 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: BackupV17CreatorRole]+        _ survivor: UUID, local: CreatorRoleDirectory, archive: [UUID: BackupV18CreatorRole]     ) -> Bool {         if let record = archive[survivor],             ToleratedEnum.read(record.stateRaw, default: CreatorRoleState.active) != .merged
Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swiftindex fc725158..672f0c81 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 BackupV17Character: ArchivedRecord {+extension BackupV18Character: ArchivedRecord {     var recordID: UUID { id }     var archivedWorkID: UUID? { workID } } -extension BackupV17Place: ArchivedRecord {+extension BackupV18Place: ArchivedRecord {     var recordID: UUID { id }     var archivedWorkID: UUID? { workID } } -extension BackupV17Suppression: ArchivedSuppression {+extension BackupV18Suppression: ArchivedSuppression {     var recordID: UUID { id }     var archivedWorkID: UUID? { workID } } -extension BackupV17PlaceSuppression: ArchivedSuppression {+extension BackupV18PlaceSuppression: ArchivedSuppression {     var recordID: UUID { id }     var archivedWorkID: UUID? { workID } }
Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportWorkTypes.swiftindex 933a8d59..3ae0ffc8 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: [BackupV17WorkType],-        works: [BackupV17Work],+        workTypes: [BackupV18WorkType],+        works: [BackupV18Work],         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: [BackupV17WorkType]+        _ records: [BackupV18WorkType]     ) -> [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: [BackupV17Work], in local: WorkTypeDirectory+        _ works: [BackupV18Work], in local: WorkTypeDirectory     ) -> [ArchivedTypeCitation] {         var seen: Set<UUID> = []         var citations: [ArchivedTypeCitation] = []
Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swiftindex 845c78ad..e2f4fe37 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift@@ -11,49 +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 `BackupV17Payload`'s content rather than the type itself: the wire+/// This is `BackupV18Payload`'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: [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 let entries: [BackupV18Entry]+    public let works: [BackupV18Work]+    public let sites: [BackupV18Site]+    public let titlePatterns: [BackupV18TitlePattern]+    public let urlRules: [BackupV18URLRule]+    public let workTypes: [BackupV18WorkType]+    public let memberships: [BackupV18Membership]+    public let distinctPairs: [BackupV18DistinctPair]+    public let characters: [BackupV18Character]+    public let suppressions: [BackupV18Suppression]+    public let places: [BackupV18Place]+    public let placeSuppressions: [BackupV18PlaceSuppression]+    public let series: [BackupV18Series]+    public let links: [BackupV18Link]+    public let creators: [BackupV18Creator]+    public let creatorRoles: [BackupV18CreatorRole]+    public let credits: [BackupV18Credit]+    public let noEpisodeActions: [BackupV18NoEpisodeAction]      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] = []+        entries: [BackupV18Entry],+        works: [BackupV18Work],+        sites: [BackupV18Site],+        titlePatterns: [BackupV18TitlePattern],+        urlRules: [BackupV18URLRule],+        workTypes: [BackupV18WorkType] = [],+        memberships: [BackupV18Membership] = [],+        distinctPairs: [BackupV18DistinctPair] = [],+        characters: [BackupV18Character] = [],+        suppressions: [BackupV18Suppression] = [],+        places: [BackupV18Place] = [],+        placeSuppressions: [BackupV18PlaceSuppression] = [],+        series: [BackupV18Series] = [],+        links: [BackupV18Link] = [],+        creators: [BackupV18Creator] = [],+        creatorRoles: [BackupV18CreatorRole] = [],+        credits: [BackupV18Credit] = [],+        noEpisodeActions: [BackupV18NoEpisodeAction] = []     ) {         self.entries = entries         self.works = works@@ -86,7 +86,7 @@ public struct BackupImportPayload: Sendable, Equatable {         self.noEpisodeActions = noEpisodeActions     } -    public init(_ payload: BackupV17Payload) {+    public init(_ payload: BackupV18Payload) {         self.init(             entries: payload.entries, works: payload.works, sites: payload.sites,             titlePatterns: payload.titlePatterns, urlRules: payload.urlRules,@@ -138,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: BackupV17Payload,+        metadata: BackupImportMetadata, payload: BackupV18Payload,         counts: LibraryRecordCounts     ) {         self.init(@@ -256,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: BackupV17Document.formatVersion, schema: BackupV17Document.schemaVersion+        format: BackupV18Document.formatVersion, schema: BackupV18Document.schemaVersion     )      // MARK: - Plan Dispatch (Req 5.1, 5.2, Decision 2)@@ -287,9 +287,9 @@ public enum BackupImporter {     }      private static func planFromArchive(_ data: Data) throws -> BackupImportPlan {-        let document: BackupV17Document+        let document: BackupV18Document         do {-            document = try BackupV17Codec.decode(data)+            document = try BackupV18Codec.decode(data)         } catch {             throw BackupImportError.decodingFailed(reason: String(describing: error))         }
Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupJSONCodecSupport.swiftindex fd19ed23..456e1bcf 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 `BackupV17Codec`: the+// paths were removed. Both helpers are used by the live `BackupV18Codec`: 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. `BackupV17ArchiveTests` covers both properties by editing+/// no-trailing-bytes. `BackupV18ArchiveTests` covers both properties by editing /// encoded bytes directly. /// /// **The root keys come from here because this walk is already paying for
Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swiftnew file mode 100644index 00000000..ef9b06cd--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swift@@ -0,0 +1,308 @@+import Foundation++/// The strict 18/19 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 18/19 backup declares. 18/19 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 BackupV18Codec {+    /// Pinned literally. 18/19 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 = "V18"++    // 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 `BackupV18Document.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: BackupV18Payload,+        metadata: BackupV18Metadata+    ) 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: BackupV18Document.formatVersion,+            capabilityGate: Self.gate,+            checksum: checksum,+            databaseSchemaVersion: BackupV18Document.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 -> BackupV18Document {+        do {+            let rootKeys = try DuplicateJSONKeyValidator.validate(data)+            try BackupArchiveShapeValidator.validate(rootKeys: rootKeys)++            let document = try BackupCanonicalJSON.decoder()+                .decode(BackupV18Document.self, from: data)++            guard document.backupFormatVersion == BackupV18Document.formatVersion else {+                throw BackupCodecError.invalidFormatVersion(document.backupFormatVersion)+            }+            guard document.databaseSchemaVersion == BackupV18Document.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 BackupV18ReferenceValidator.validate(payload: document.payload)++            return document+        } catch let error as BackupCodecError { throw error }+        catch {+            throw BackupCodecError.decodingFailed(reason: String(describing: error))+        }+    }+}++// MARK: - V18 Metadata++public struct BackupV18Metadata: 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: - V18 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 BackupV18ReferenceValidator {+    static func validate(payload: BackupV18Payload) throws {+        for work in payload.works {+            guard work.publicationState.map({ $0.authoredStatus == work.workStatus }) ?? true else {+                throw BackupCodecError.invalidStateTuple(+                    type: "Work", id: work.id.uuidString,+                    reason: "publication state disagrees with work status")+            }+        }+        do { _ = try NoEpisodeHistory(payload.noEpisodeActions.map { try $0.action() }) }+        catch {+            throw BackupCodecError.invalidStateTuple(+                type: "NoEpisodeAction", id: BackupV18Codec.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: BackupV18Codec.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: BackupV18Codec.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: BackupV18Codec.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: BackupV18Codec.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: BackupV18Codec.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: BackupV18Codec.label,+                    reason: "duplicate PlaceSuppression ID")+            }+        }+    }+}
Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swiftnew file mode 100644index 00000000..d8b10808--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.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 BackupV18SnapshotProviding: Sendable {+    func backupV18Snapshot() async throws -> BackupV18Payload+}++// 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 BackupV18ExportError: 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: BackupV18SnapshotProviding {+    /// 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 backupV18Snapshot() async throws -> BackupV18Payload {+        let outcome: Result<BackupV18Payload, BackupV18ExportError> =+            try await withLockedBackupContext { context in+                do { return .success(try Self.projectV18Payload(context: context)) }+                catch let error as BackupV18ExportError { 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 projectV18Payload(context: ModelContext) throws -> BackupV18Payload {+        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 {+            BackupV18WorkType(+                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 mapV18WorkRecord(+                $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(mapV18CharacterRecord)++        let suppressions = try context.fetch(FetchDescriptor<CharacterSuppression>())+            .map(mapV18SuppressionRecord)+            .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(mapV18PlaceRecord)++        let placeSuppressions = try context.fetch(FetchDescriptor<PlaceSuppression>())+            .map(mapV18PlaceSuppressionRecord)+            .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 BackupV18Payload(+            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: mapV18CreatorRecords(creators),+            creatorRoles: mapV18CreatorRoleRecords(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(+                BackupV18NoEpisodeAction.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 mapV18CreatorRecords(+        _ directory: CreatorDirectory+    ) -> [BackupV18Creator] {+        directory.identities.map { identity in+            BackupV18Creator(+                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 mapV18CreatorRoleRecords(+        _ directory: CreatorRoleDirectory+    ) -> [BackupV18CreatorRole] {+        directory.identities.map { identity in+            BackupV18CreatorRole(+                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 mapV18CharacterRecord(_ group: CharacterGroup) -> BackupV18Character {+        let content = group.presentedContent+        return BackupV18Character(+            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 mapV18SuppressionRecord(+        _ row: CharacterSuppression+    ) -> BackupV18Suppression {+        BackupV18Suppression(+            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)+    }++    /// `mapV18CharacterRecord` 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: `BackupV18Place.workID` is a+    /// `UUID` and `BackupV18Character.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 mapV18PlaceRecord(_ group: RecordGroup<Place>) -> BackupV18Place {+        let content = group.presentedContent+        return BackupV18Place(+            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 `mapV18SuppressionRecord`'s reason.+    private static func mapV18PlaceSuppressionRecord(+        _ row: PlaceSuppression+    ) -> BackupV18PlaceSuppression {+        BackupV18PlaceSuppression(+            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 BackupV18Exporter: Sendable {+    private let repository: any BackupV18SnapshotProviding+    private let stagingDirectory: URL++    public init(+        repository: any BackupV18SnapshotProviding,+        stagingDirectory: URL+    ) {+        self.repository = repository+        self.stagingDirectory = stagingDirectory+    }++    public func export(metadata: BackupV18Metadata) async throws -> BackupExportResult {+        let payload: BackupV18Payload+        do {+            payload = try await repository.backupV18Snapshot()+        } catch let error as BackupV18ExportError {+            throw error+        } catch {+            throw BackupV18ExportError.snapshotFailed(reason: String(describing: error))+        }++        let encoded: Data+        do {+            encoded = try BackupV18Codec.encode(payload: payload, metadata: metadata)+        } catch {+            throw BackupV18ExportError.encodingFailed(reason: String(describing: error))+        }++        do {+            let decoded = try BackupV18Codec.decode(encoded)+            guard decoded.payload == payload else {+                throw BackupV18ExportError.encodingFailed(reason: "decode-validation payload mismatch")+            }+        } catch let error as BackupV18ExportError {+            throw error+        } catch {+            throw BackupV18ExportError.encodingFailed(reason: "decode-validation failed: \(error)")+        }++        do {+            try FileManager.default.createDirectory(+                at: stagingDirectory, withIntermediateDirectories: true)+            let fileURL = stagingDirectory.appending(+                path: ExportStaging.backupFilename(+                    version: "v\(BackupV18Document.formatVersion)",+                    exportedAt: metadata.exportedAt))+            do {+                try ExportStaging.write(encoded, to: fileURL)+            } catch {+                throw BackupV18ExportError.stagingFailed(reason: String(describing: error))+            }+            return BackupExportResult(fileURL: fileURL)+        } catch let error as BackupV18ExportError {+            throw error+        } catch {+            throw BackupV18ExportError.stagingFailed(+                reason: "preparing staging directory failed: \(error)")+        }+    }++    public func cleanup(_ result: BackupExportResult) {+        try? FileManager.default.removeItem(at: result.fileURL)+    }++    /// Removes abandoned backup files older than 24 hours from the staging area,+    /// which still covers the files a previous build staged at an earlier+    /// generation.+    public func scavengeStaleFiles() {+        ExportStaging.scavengeBackups(in: stagingDirectory)+    }+}
Packages/AsterismCore/Sources/AsterismCore/BackupV18Types.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV18Types.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Types.swiftnew file mode 100644index 00000000..eb9210ab--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Types.swift@@ -0,0 +1,1080 @@+import Foundation++// MARK: - Backup V18 Document++/// The 18/19 backup envelope: format version 18 over live schema version 19.+/// The schema number names the store schema the archive was taken from.+///+/// It replaces the 17/18 importer outright. This generation carries authored+/// publication state; older envelopes are refused before a library write.+///+/// The schema number is **pinned to the live schema by a test**+/// (`BackupV18ArchiveTests.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 BackupV18Document: Codable, Equatable, Sendable {+    public static let formatVersion = 18+    public static let schemaVersion = 19++    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: BackupV18Payload++    public init(+        appBuild: String,+        exportedAt: Date,+        capabilityGate: String,+        entryCount: Int,+        workCount: Int,+        checksum: String,+        payload: BackupV18Payload+    ) {+        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: - V18 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 BackupV18Payload: Codable, Equatable, Sendable {+    public let entries: [BackupV18Entry]+    public let works: [BackupV18Work]+    public let sites: [BackupV18Site]+    public let titlePatterns: [BackupV18TitlePattern]+    public let urlRules: [BackupV18URLRule]+    public let workTypes: [BackupV18WorkType]+    /// One row per Work and hostname (Req 9.1). The Work's site presence lives+    /// here and nowhere else.+    public let memberships: [BackupV18Membership]+    /// The reader's "not the same work" over an unordered pair (Req 5.5).+    public let distinctPairs: [BackupV18DistinctPair]+    public let characters: [BackupV18Character]+    public let suppressions: [BackupV18Suppression]+    /// 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: [BackupV18Place]+    /// 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: [BackupV18PlaceSuppression]+    /// 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: [BackupV18Series]+    /// 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: [BackupV18Link]+    /// The reader's creators, one record per folded identity+    /// (`work-creators` Req 9.1).+    public let creators: [BackupV18Creator]+    /// The reader's role list, one record per folded identity, carrying the+    /// list order every credit is read in.+    public let creatorRoles: [BackupV18CreatorRole]+    /// 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: [BackupV18Credit]+    /// Full remove-wins history, including clears and dangling work references.+    public let noEpisodeActions: [BackupV18NoEpisodeAction]++    public init(+        entries: [BackupV18Entry],+        works: [BackupV18Work],+        sites: [BackupV18Site],+        titlePatterns: [BackupV18TitlePattern],+        urlRules: [BackupV18URLRule],+        workTypes: [BackupV18WorkType] = [],+        memberships: [BackupV18Membership] = [],+        distinctPairs: [BackupV18DistinctPair] = [],+        characters: [BackupV18Character] = [],+        suppressions: [BackupV18Suppression] = [],+        places: [BackupV18Place] = [],+        placeSuppressions: [BackupV18PlaceSuppression] = [],+        series: [BackupV18Series] = [],+        links: [BackupV18Link] = [],+        creators: [BackupV18Creator] = [],+        creatorRoles: [BackupV18CreatorRole] = [],+        credits: [BackupV18Credit] = [],+        noEpisodeActions: [BackupV18NoEpisodeAction] = []+    ) {+        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 BackupV18NoEpisodeAction: 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: - V18 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 BackupV18Site: 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 BackupV18TitlePattern: 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 BackupV18URLRule: 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 BackupV18WorkType: 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 BackupV18Work: 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+    /// Whole authored publication value, including elapsed pause evidence.+    /// Missing on the wire means legacy status without recorded intervals.+    public let publicationState: WorkPublicationState?+    /// 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 `BackupV18WorkType`, 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,+        publicationState: WorkPublicationState? = 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.publicationState = publicationState+        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 BackupV18Series: 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).+///+/// `BackupV18DistinctPair`'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 BackupV18Link: 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 — `BackupV18DistinctPair.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: BackupV18Link {+        let ids = WorkDistinctPair.sortedIDs(lowerWorkID, higherWorkID)+        guard ids.lower != lowerWorkID || ids.higher != higherWorkID else { return self }+        return BackupV18Link(+            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**, `BackupV18WorkType`'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 BackupV18Creator: 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).+///+/// `BackupV18Creator`'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 BackupV18CreatorRole: 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).+///+/// `BackupV18Link`'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 BackupV18Credit: 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.+    ///+    /// `BackupV18Link.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: BackupV18Credit {+        let roles = WorkCreditSupport.roleIDs(roleIDs)+        guard roles != roleIDs else { return self }+        return BackupV18Credit(+            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 BackupV18Membership: 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 BackupV18DistinctPair: 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: BackupV18DistinctPair {+        let ids = WorkDistinctPair.sortedIDs(lowerWorkID, higherWorkID)+        guard ids.lower != lowerWorkID || ids.higher != higherWorkID else { return self }+        return BackupV18DistinctPair(+            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 BackupV18Entry: 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 BackupV18Character: 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 `BackupV18WorkType`'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 BackupV18Suppression: 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).+///+/// `BackupV18Character`'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 BackupV18Place: 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.+///+/// `BackupV18Suppression`'s shape with `BackupV18Place`'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 BackupV18PlaceSuppression: 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)+    }+}
Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift b/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swiftindex 08c9fd11..0bf2b870 100644--- a/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift@@ -47,6 +47,7 @@ public struct CatchUpProgress: Equatable, Sendable {     public static func build(         record: CatchUpRecord, notes: [NumberedNote], releaseDays: [ReleaseDay],         noEpisodeDays: Set<CivilDay> = [], workStatus: WorkStatus,+        publicationState: WorkPublicationState? = nil,         day: CivilDay, calendar: Calendar     ) -> CatchUpProgress {         let override: (number: Int, at: Date)?@@ -79,7 +80,13 @@ public struct CatchUpProgress: Equatable, Sendable {         }          func releases(after start: CivilDay?) -> Int {-            guard record.countsUp, workStatus == .ongoing, let start, start < day else { return 0 }+            guard record.countsUp, let start, start < day else { return 0 }+            if let publicationState {+                guard publicationState.authoredStatus != .finished else { return 0 }+                return publicationState.excludingPauses(after: start, through: day,+                    releaseDays: releaseDays, noEpisodeDays: noEpisodeDays, calendar: calendar) ?? 0+            }+            guard workStatus == .ongoing else { return 0 }             return TodayDayPlan.releaseCount(                 of: releaseDays, after: start, through: day,                 noEpisodeDays: noEpisodeDays, calendar: calendar) ?? 0@@ -119,20 +126,21 @@ public struct CatchUpProgress: Equatable, Sendable {             record: work.catchUp, notes: NumberedNote.from(work.entries),             releaseDays: work.releaseDays,             noEpisodeDays: work.noEpisodeHistory.activeDays(for: work.id).subtracting(notedDays),-            workStatus: work.workStatus,+            workStatus: work.authoredWorkStatus, publicationState: work.publicationState,             day: day, calendar: calendar)     }      public static func rebased(         record: CatchUpRecord, notes: [NumberedNote], releaseDays: [ReleaseDay],         noEpisodeDays: Set<CivilDay> = [], workStatus: WorkStatus,+        publicationState: WorkPublicationState? = nil,         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,-            noEpisodeDays: noEpisodeDays, workStatus: workStatus,+            noEpisodeDays: noEpisodeDays, workStatus: workStatus, publicationState: publicationState,             day: day, calendar: calendar)         guard let effectiveLatest = progress.effectiveLatest else { return nil }         return CatchUpRecord(
Packages/AsterismCore/Sources/AsterismCore/CivilDateCodec.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CivilDateCodec.swift b/Packages/AsterismCore/Sources/AsterismCore/CivilDateCodec.swiftnew file mode 100644index 00000000..616dfff1--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/CivilDateCodec.swift@@ -0,0 +1,23 @@+import Foundation++/// The existing no-episode civil-date grammar, shared by publication evidence.+public enum CivilDateCodec {+    public static func parse(_ 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)+    }++    public static func spelling(_ day: CivilDay) -> String {+        String(format: "%04d-%02d-%02d", day.year, day.month, day.day)+    }+}
Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swiftindex e1410217..f15373e4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift@@ -555,6 +555,8 @@ enum DuplicateReconciler {         // does not touch cost nothing to leave in the store.         let rowsByID = try workRows(             ids: Array(Set(resolvable.flatMap(\.key.memberIDs))), context: context)+        // Reject unreadable authored values before the first fan-out or deletion.+        for row in rowsByID.values.flatMap({ $0 }) { _ = try row.decodedPublicationState() }         var pending = Chunk(batchSize: batchSize)          for set in resolvable {@@ -1752,6 +1754,7 @@ enum DuplicateReconciler {         // tolerant read over a raw column, and the per-row guards below would         // otherwise parse the carrier's raw twice per row.         let carriedWorkStatus = carrier.workStatus+        let carriedPublicationStateData = carrier.publicationStateData         let carriedReadingStatus = carrier.readingStatus         let carriedVerdict = carrier.verdict         // V11, read once for the same reason: a half-set carrier row reads as@@ -1820,7 +1823,16 @@ enum DuplicateReconciler {             // There is no `propagates` gate here: that one exists because a type             // may be `.removed`, a state with no counterpart in a closed             // three-value vocabulary.-            if carriedWorkStatus != .ongoing, row.workStatus != carriedWorkStatus {+            if let stateData = carriedPublicationStateData {+                if row.publicationStateData != stateData {+                    row.publicationStateData = stateData+                    changed = true+                }+                if row.workStatusRaw != carrier.workStatusRaw {+                    row.workStatusRaw = carrier.workStatusRaw+                    changed = true+                }+            } else if carriedWorkStatus != .ongoing, row.workStatus != carriedWorkStatus {                 row.workStatus = carriedWorkStatus                 changed = true             }
Packages/AsterismCore/Sources/AsterismCore/DuplicateResolution.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateResolution.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateResolution.swiftindex bcffcf6b..b79832ec 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateResolution.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateResolution.swift@@ -29,6 +29,7 @@ public enum DuplicateResolutionField: String, Sendable, Equatable, CaseIterable     /// they typed are authored, so two copies disagreeing on one are a decision     /// the sheet has to name.     case workStatus+    case publicationState     case readingStatus     case verdict     /// V11 (Req 11.3): a series membership is authored, so two copies@@ -98,6 +99,7 @@ public struct WorkVariantChoice: Sendable, Equatable, Identifiable {     /// the reader to choose between labels, and an identity is not a label.     public let typeDisplay: WorkTypeDisplay     /// V10: what the copy says about the work and about the reader (Req 7.2).+    public let publicationState: WorkPublicationState?     public let workStatus: WorkStatus     public let readingStatus: ReadingStatus     /// Shown whatever the reading status — the one place Q7's hidden verdict is@@ -131,8 +133,10 @@ public struct WorkVariantChoice: Sendable, Equatable, Identifiable {         firstCapturedAt: Date,         membership: SeriesMembership? = nil, series: SeriesDisplay? = nil,         thumbnail: ThumbnailIdentity? = nil, thumbnailBytes: Data? = nil,-        releaseDays: [ReleaseDay] = []+        releaseDays: [ReleaseDay] = [],+        publicationState: WorkPublicationState? = nil     ) {+        self.publicationState = publicationState         self.releaseDays = ReleaseDay.canonical(releaseDays)         self.thumbnail = thumbnail         self.thumbnailBytes = thumbnailBytes@@ -145,7 +149,7 @@ public struct WorkVariantChoice: Sendable, Equatable, Identifiable {         self.workURLString = workURLString         self.genreTags = genreTags         self.typeDisplay = typeDisplay-        self.workStatus = workStatus+        self.workStatus = publicationState?.authoredStatus ?? workStatus         self.readingStatus = readingStatus         self.verdict = verdict         self.firstCapturedAt = firstCapturedAt
Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift b/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swiftindex fc42be1b..2d9bced4 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-    /// `BackupV17Entry`, hand-enumerated nowhere else. With the citations folded+    /// `BackupV18Entry`, 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
Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swiftindex fd1834ff..32330c83 100644--- a/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift@@ -241,6 +241,9 @@ public struct WorkAuthoredContent: AuthoredContent {     /// as a non-`.none` type is. A collapse can never drop it silently; the cost     /// is an occasional review card.     public var workStatus: WorkStatus+    /// The complete canonical envelope; malformed bytes remain distinct until a+    /// throwing read or validation refuses them. They must never become nil.+    public var publicationStateData: Data?     public var readingStatus: ReadingStatus     /// Non-empty is authored — including under a `reading` status, where Q7     /// hides the text but Q14 still counts it (Q21).@@ -281,7 +284,8 @@ public struct WorkAuthoredContent: AuthoredContent {         verdict: String = "",         membership: SeriesMembership? = nil,         thumbnail: ThumbnailIdentity? = nil,-        releaseDays: [ReleaseDay] = []+        releaseDays: [ReleaseDay] = [],+        publicationStateData: Data? = nil     ) {         self.releaseDays = ReleaseDay.canonical(releaseDays)         self.thumbnail = thumbnail@@ -291,7 +295,9 @@ public struct WorkAuthoredContent: AuthoredContent {         self.workURLString = workURLString         self.genreTags = genreTags.sorted()         self.typeAssignment = typeAssignment-        self.workStatus = workStatus+        let state = publicationStateData.flatMap { try? WorkPublicationState.decode($0) }+        self.publicationStateData = state.map { try! $0.canonicalData() } ?? publicationStateData+        self.workStatus = state?.authoredStatus ?? workStatus         self.readingStatus = readingStatus         self.verdict = verdict     }@@ -312,7 +318,7 @@ public struct WorkAuthoredContent: AuthoredContent {             // has none. An **empty** set contributes nothing, which is what             // makes a non-empty set fold over an empty sibling without asking             // (`update-schedule` Decision 1, Req 7.2).-            && releaseDays.isEmpty+            && releaseDays.isEmpty && publicationStateData == nil     }      public var orderComponents: [OrderComponent] {@@ -353,6 +359,7 @@ public struct WorkAuthoredContent: AuthoredContent {             // that every existing Work `VariantID` moves once as a result, as             // V10 and V14 did.             .strings(releaseDays.map(\.rawValue)),+            .absentableString(publicationStateData?.base64EncodedString()),         ]     } }@@ -707,7 +714,8 @@ public enum GroupOrdering {             // V15, through the tolerant accessor like the statuses above: an             // unknown stored spelling is a library mid-rollout, not damage, and             // must not tear a group on its own (`update-schedule` Req 1.6).-            releaseDays: work.releaseDays)+            releaseDays: work.releaseDays,+            publicationStateData: work.publicationStateData)     }      /// A row's series pair, or nil.
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swiftindex c310c892..ffadf5c5 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift@@ -85,7 +85,7 @@ extension LibraryRepository {          var worksByID: [UUID: Work] = [:]         for record in payload.works {-            let work = ArchiveRecordBuilders.makeWork(record)+            let work = try ArchiveRecordBuilders.makeWork(record)             context.insert(work)             worksByID[record.id] = work         }
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swiftindex 58825f80..92399502 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             schema: schema,             isStoredInMemoryOnly: true,
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swiftindex 6defb547..03a04e72 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 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+/// Opens the live V19 library after classifying the fixed-path store.+/// The app accepts markers `"16"`, `"17"`, `"18"`, and `"19"`; the extension accepts only `"19"`.+/// V16, V17 and V18 stores migrate through lightweight stages. The app validates+/// before publishing `"19"`, 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@@ -14,7 +14,7 @@ public extension LibraryRepository {         case ready(LibraryRecordCounts)     } -    /// Extension-only readiness result. The extension opens only a `"17"` marker.+    /// Extension-only readiness result. The extension opens only a `"19"` marker.     enum ExtensionResult: Equatable, Sendable {         case ready(LibraryRecordCounts)     }@@ -150,7 +150,7 @@ public extension LibraryRepository {                     + "version this build opens; restore from a backup archive")          case .ready:-            // open (nothing to convert at `"16"`) → validate → clear residual+            // open (nothing to convert at `"19"`) → validate → clear residual             // evidence → counts. The marker already records the current             // generation, so nothing is published: this is the only certification             // sequence left, and it writes no marker at all.@@ -163,22 +163,13 @@ public extension LibraryRepository {             return Certification(result: .ready(counts), diagnostics: diagnostics)          case .markerLagging(let generation):-            // open (which drops the junk-suffix column) → validate →-            // publish `"17"`.-            //-            // The V16 → V17 lightweight stage adds two optional Work blobs.-            // It needs no data pass: a converted row reads nil in both columns.-            // Validation certifies the converted store before readiness moves;-            // a failed validation leaves `"16"` for the next app open.-            //-            // The residual evidence goes **last**, after the publish rather than-            // with the validation: a publish that fails on a full disk leaves-            // the library at `"16"` with its historical marker and sidecar still-            // beside it, which is the state the next open wants to find.+            // Convert the supported V16–V18 schemas, validate, then publish 19.+            // V19 adds only an optional Work blob, so existing rows retain nil.+            // A failure leaves the previous marker and residual evidence intact.             let container = try openCertificationContainer(configuration, hooks: hooks)             let context = ModelContext(container)             bootstrapLogger.debug(-                "Marker generation \(generation, privacy: .public) is lagging; certifying the V18 conversion")+                "Marker generation \(generation, privacy: .public) is lagging; certifying the V19 conversion")             let diagnostics = try validateStore(context: context)             try publishReadiness(at: configuration.readinessMarkerURL)             clearResidualEvidence(configuration)@@ -197,7 +188,7 @@ public extension LibraryRepository {                 reason: kind.orphanedReason)          case .unmarkedStore:-            // open → counts → refuse if nonempty → publish `"16"`.+            // open → counts → refuse if nonempty → publish `"19"`.             //             // An *empty* unmarked store is the state a crash between store             // creation and the marker leaves, or a `publishReadiness` that@@ -224,10 +215,10 @@ public extension LibraryRepository {             return Certification(result: .ready(counts), diagnostics: .empty)          case .pristine:-            // open (which creates) → save → counts → publish `"16"`.+            // open (which creates) → save → counts → publish `"19"`.             //-            // Certified at `"16"`, the current generation: a store created by-            // these classes is already V16-shaped, so it is born in the state a+            // Certified at `"19"`, the current generation: a store created by+            // these classes is already V19-shaped, so it is born in the state a             // certified library is in (Q26) rather than at the lagging digit             // with a conversion ahead of it.             let container = try openCertificationContainer(configuration, hooks: hooks)@@ -380,15 +371,16 @@ extension LibraryRepository {         var quarantined: [String: LibraryValidationError] { diagnostics.quarantineMap() }     } -    /// Opens the fixed-path store under V17 and the `[V16, V17]` migration-    /// plan. The single lightweight stage adds two optional Work blob columns;-    /// existing rows read nil in both, with no data pass.+    /// Opens the fixed-path store under V19 and the `[V16, V17, V18, V19]` migration+    /// plan. Its retained lightweight stages add catch-up blobs, no-episode+    /// actions and the optional publication blob. Existing rows receive nil+    /// publication state without a data pass.     /// The classifier refuses older markers before this constructs a container.     public static func openContainer(         at storeURL: URL,         mirroring cloudKitDatabase: ModelConfiguration.CloudKitDatabase = .none     ) throws -> ModelContainer {-        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let storeConfiguration = ModelConfiguration(             // **Frozen persisted state (Req 3.5).** This names the store             // configuration *inside* the container, not the file — `url:` below is@@ -402,7 +394,7 @@ extension LibraryRepository {         )         return try ModelContainer(             for: schema,-            migrationPlan: AsterismV18MigrationPlan.self,+            migrationPlan: AsterismV19MigrationPlan.self,             configurations: [storeConfiguration]         )     }@@ -507,6 +499,10 @@ extension LibraryRepository {     @discardableResult     static func validateStore(context: ModelContext) throws -> LibraryDiagnostics {         do {+            // Corrupt authored envelopes must refuse readiness, never read as legacy.+            try context.enumerate(FetchDescriptor<Work>()) { work in+                _ = try work.decodedPublicationState()+            }             return try LibraryValidator.validate(context: context)         } catch {             throw LibraryRepositoryError.libraryUnavailable(@@ -514,7 +510,7 @@ extension LibraryRepository {         }     } -    /// Marker generations the app opens: the current one and its predecessor.+    /// Marker generations the app opens: every retained schema generation.     ///     /// **This is the live acceptance test**, not a description of one: the     /// classifier's ready row tests `extensionOpenableMarkerVersion` and its@@ -551,7 +547,7 @@ extension LibraryRepository {     /// convert its store anyway; the recovery is the backup archive, as for any     /// unrecognised marker.     static let appOpenableMarkerVersions: Set<String> = [-        laggingOpenableMarkerVersion, "17", extensionOpenableMarkerVersion,+        laggingOpenableMarkerVersion, "17", "18", extensionOpenableMarkerVersion,     ]      /// The one lagging generation the app still opens: a library certified by a@@ -564,7 +560,7 @@ extension LibraryRepository {     /// installed library (Req 3.5). Both generations the app opens are now     /// spelled with two characters, which is why nothing anywhere may assume a     /// marker is one character long.-    static let extensionOpenableMarkerVersion = "18"+    static let extensionOpenableMarkerVersion = "19"      // The app-side counterpart of `validateMarkerContentForExtension` stood     // here. It restated the acceptance test the classifier performs, and
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swiftindex 38dad679..7aa680c3 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. `BackupV17Membership`'s+/// The one field the off-host pre-pass rewrites. `BackupV18Membership`'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 BackupV17Membership {-    fileprivate func withWorkURLString(_ value: String?) -> BackupV17Membership {-        BackupV17Membership(+extension BackupV18Membership {+    fileprivate func withWorkURLString(_ value: String?) -> BackupV18Membership {+        BackupV18Membership(             id: id, workID: workID, hostname: hostname, createdAt: createdAt,             urlIdentity: urlIdentity, urlIdentityState: urlIdentityState,             urlIdentityRuleID: urlIdentityRuleID, workURLString: value)@@ -206,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: [BackupV17Site] = []+        var matchedRecords: [BackupV18Site] = []         for record in payload.sites {             if sitesByHostname[record.hostname] != nil {                 matchedRecords.append(record)@@ -507,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: BackupV17Site,+        _ record: BackupV18Site,         to site: Site,         patterns: [TitlePattern],         urlRules: [URLRulePattern]@@ -554,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: [BackupV17Work],+        _ records: [BackupV18Work],         into workRows: inout [UUID: [Work]],         types: WorkTypeDirectory,         context: ModelContext,@@ -602,12 +602,12 @@ extension LibraryRepository {                     guard record.modifiedAt >= group.modifiedAt else { continue }                     thumbnail = ArchiveThumbnail.of(record)                     for existing in group.rows {-                        apply(record, to: existing, thumbnail: thumbnail)+                        try apply(record, to: existing, thumbnail: thumbnail)                     }                     applied.insert(record.id)                 } else {                     thumbnail = ArchiveThumbnail.of(record)-                    let work = ArchiveRecordBuilders.makeWork(record, thumbnail: thumbnail)+                    let work = try ArchiveRecordBuilders.makeWork(record, thumbnail: thumbnail)                     context.insert(work)                     workRows[record.id] = [work]                     applied.insert(record.id)@@ -654,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: [BackupV17Membership],+        _ records: [BackupV18Membership],         workRows: [UUID: [Work]],         workTargets: [UUID: Work],         appliedWorkIDs: Set<UUID>,@@ -769,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: [BackupV17Membership],+        _ records: [BackupV18Membership],         existingMembershipIDs: Set<UUID>,         appliedWorkIDs: Set<UUID>-    ) -> [BackupV17Membership] {+    ) -> [BackupV18Membership] {         var indicesByWork: [UUID: [Int]] = [:]         for (index, record) in records.enumerated() {             guard let workID = record.workID else { continue }@@ -835,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: BackupV17Membership,+        _ record: BackupV18Membership,         existingMembershipIDs: Set<UUID>,         appliedWorkIDs: Set<UUID>     ) -> Bool {@@ -859,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: [BackupV17Series],+        _ records: [BackupV18Series],         context: ModelContext,         batchSize: Int,         saveStrategy: any RepositorySaveStrategy@@ -900,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: [BackupV17Link],+        _ records: [BackupV18Link],         context: ModelContext,         batchSize: Int,         saveStrategy: any RepositorySaveStrategy@@ -955,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: [BackupV17Credit],+        _ records: [BackupV18Credit],         context: ModelContext,         batchSize: Int,         saveStrategy: any RepositorySaveStrategy@@ -1002,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: [BackupV17DistinctPair],+        _ records: [BackupV18DistinctPair],         context: ModelContext,         batchSize: Int,         saveStrategy: any RepositorySaveStrategy@@ -1042,8 +1042,9 @@ 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: BackupV17Work, to work: Work, thumbnail: ArchiveThumbnail-    ) {+        _ record: BackupV18Work, to work: Work, thumbnail: ArchiveThumbnail+    ) throws {+        let publicationStateData = try record.publicationState?.canonicalData()         // Every scalar below is value-guarded (T-2334): re-importing an archive         // the library already matches must write nothing, so a re-export mirrors         // no unchanged row through CloudKit. The recency gate in the caller@@ -1065,6 +1066,9 @@ extension LibraryRepository {         if work.workStatusRaw != record.workStatus.rawValue {             work.workStatusRaw = record.workStatus.rawValue         }+        if work.publicationStateData != publicationStateData {+            work.publicationStateData = publicationStateData+        }         if work.readingStatusRaw != record.readingStatus.rawValue {             work.readingStatusRaw = record.readingStatus.rawValue         }@@ -1149,7 +1153,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: BackupV17Membership, to membership: WorkSiteMembership) {+    internal static func apply(_ record: BackupV18Membership, 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 }@@ -1170,7 +1174,7 @@ extension LibraryRepository {         if membership.workID != workID { membership.workID = workID }     } -    internal static func apply(_ record: BackupV17Entry, to entry: Entry) {+    internal static func apply(_ record: BackupV18Entry, 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 }
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swiftindex d8d6549b..8c99b1e7 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift@@ -282,8 +282,8 @@ extension LibraryRepository {                 return .found(                     .work(                         setKey: set.key,-                        variants: set.variants.map {-                            Self.choice(+                        variants: try set.variants.map {+                            try Self.choice(                                 $0, rows: rows, orderedRows: orderedRows, types: types,                                 series: series)                         },@@ -383,7 +383,7 @@ extension LibraryRepository {     private static func choice(         _ variant: AuthoredVariant<WorkAuthoredContent>, rows: [Work], orderedRows: [Work],         types: WorkTypeDirectory, series: SeriesDirectory-    ) -> WorkVariantChoice {+    ) throws -> WorkVariantChoice {         let carrier = rows.first {             GroupOrdering.authoredContent(of: $0, types: types) == variant.content         }@@ -426,7 +426,8 @@ extension LibraryRepository {             // content is what the reader is choosing between, and the variant             // already holds it canonical with every unknown spelling dropped             // (`update-schedule` Req 7.2).-            releaseDays: variant.content.releaseDays)+            releaseDays: variant.content.releaseDays,+            publicationState: try variant.content.publicationStateData.map(WorkPublicationState.decode))     }      /// The bytes of a variant's cover, from the first row of the set whose blob@@ -520,6 +521,7 @@ extension LibraryRepository {         // V10 (Req 7.2). No sentinel: the values are non-optional, so the set of         // what the variants hold is the whole comparison.         if Set(contents.map(\.workStatus)).count > 1 { fields.append(.workStatus) }+        if Set(contents.map(\.publicationStateData)).count > 1 { fields.append(.publicationState) }         if Set(contents.map(\.readingStatus)).count > 1 { fields.append(.readingStatus) }         if Set(contents.map(\.verdict)).count > 1 { fields.append(.verdict) }         // V11 (Req 11.3): the pair is one decision. The canonical text keys it,@@ -794,7 +796,7 @@ extension LibraryRepository {         // adopts a URL the chosen variant lacks, and records a discarded manual         // title — all of it through the helper Merge uses, so the two routes         // cannot give one field opposite outcomes (Q51).-        let others = set.variants.filter { $0.id != chosen }.map { variant -> WorkVariantSide in+        let others = try set.variants.filter { $0.id != chosen }.map { variant -> WorkVariantSide in             let row = GroupOrdering.sortedWorkRows(allRows).first {                 GroupOrdering.authoredContent(of: $0, types: types) == variant.content             }@@ -811,7 +813,8 @@ extension LibraryRepository {                 readingStatus: row?.readingStatus ?? variant.content.readingStatus,                 verdict: row?.verdict ?? variant.content.verdict,                 membership: variant.content.membership,-                releaseDays: variant.content.releaseDays)+                releaseDays: variant.content.releaseDays,+                publicationState: try variant.content.publicationStateData.map(WorkPublicationState.decode))         }         let chosenSide = WorkVariantSide(             displayTitle: carrier.displayTitle, titleProvenance: carrier.titleProvenance,@@ -823,7 +826,8 @@ extension LibraryRepository {             readingStatus: carrier.readingStatus,             verdict: carrier.verdict,             membership: GroupOrdering.membership(of: carrier),-            releaseDays: carrier.releaseDays)+            releaseDays: carrier.releaseDays,+            publicationState: try carrier.decodedPublicationState())         let union = WorkVariantUnion.fold(into: chosenSide, others: others)          // V14 (Req 1.6): carrier-wins, like the title and the statuses, and the@@ -835,6 +839,8 @@ extension LibraryRepository {             ofVariant: chosenVariant.content,             inSorted: GroupOrdering.sortedWorkRows(allRows)) +        let publicationStateData = try chosenSide.publicationState?.canonicalData()+        let authoredStatusRaw = carrier.workStatusRaw         let timestamp = MillisecondInstant.quantize(clock.now())         for row in survivorRows {             // Q34: the title is the chosen variant's, provenance and all, so a@@ -846,7 +852,8 @@ extension LibraryRepository {             // Req 7.2: the chosen variant's statuses and verdict, carrier-wins             // like the title and the type. The fold never moves them; a losing             // verdict travels in the notes it just wrote (Q41).-            row.workStatus = carrier.workStatus+            row.publicationStateData = publicationStateData+            row.workStatusRaw = authoredStatusRaw             row.readingStatus = carrier.readingStatus             row.verdict = carrier.verdict             // V11, carrier-wins like the three above, and as a pair so a
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swiftindex 01b9fc87..efcc5a29 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift@@ -194,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 `mapV17WorkRecord`'s+                // An **empty** series directory, for `mapV18WorkRecord`'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
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swiftindex 39be56dc..c16b7942 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift@@ -406,7 +406,8 @@ extension LibraryRepository {         types: WorkTypeDirectory, series: SeriesDirectory, credits: CreditIndex,         history: NoEpisodeHistory     ) throws -> WorkSnapshot {-        let base = snapshot(+        for row in group.rows { _ = try row.decodedPublicationState() }+        let base = try snapshot(             group.representative, entries: [], types: types, series: series, credits: credits,             history: history)         let entries = try entryGroups(entryRows, canonicalWorkIDs: canonicalWorkIDs)@@ -422,18 +423,18 @@ extension LibraryRepository {                 genreTags: base.genreTags,                 titleProvenance: base.titleProvenance, createdAt: base.createdAt,                 modifiedAt: base.modifiedAt, entries: entries, groupState: group.state,-                workStatus: base.workStatus, readingStatus: base.readingStatus,+                authoredWorkStatus: base.authoredWorkStatus, readingStatus: base.readingStatus,                 verdict: base.verdict,                 membership: base.membership, series: base.series,                 credits: base.credits,                 thumbnail: base.thumbnail,                 releaseDays: base.releaseDays, releaseDaysRaw: base.releaseDaysRaw,-                catchUp: catchUp, noEpisodeHistory: history)+                catchUp: catchUp, noEpisodeHistory: history, publicationState: base.publicationState)         }         // 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(+        let carried = try snapshot(             group.carrier, entries: [], types: types, series: series, credits: credits,             history: history)         return WorkSnapshot(@@ -462,7 +463,7 @@ extension LibraryRepository {             // The carrier's, like every other authored field of a split group             // (Req 7.2): the row holding the content the group presents is the             // row whose statuses and verdict it presents.-            workStatus: carried.workStatus,+            authoredWorkStatus: carried.authoredWorkStatus,             readingStatus: carried.readingStatus,             verdict: carried.verdict,             // Req 9.7: the membership is presented from the same row every other@@ -485,6 +486,6 @@ extension LibraryRepository {             // section, presenting the days of the row whose content it presents.             releaseDays: carried.releaseDays,             releaseDaysRaw: carried.releaseDaysRaw,-            catchUp: catchUp, noEpisodeHistory: history)+            catchUp: catchUp, noEpisodeHistory: history, publicationState: carried.publicationState)     } }
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swiftindex ad03bb23..6e6600db 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift@@ -54,7 +54,8 @@ extension LibraryRepository {         let hostname = try Self.pageHostname(rawURL)         return try await withLockedContext(mode: .shared, operation: "matching a page") {             context in-            try Self.pageMatch(rawURL: rawURL, hostname: hostname, context: context)+            let day = CivilDay(clock.now(), calendar: .current)+            return try Self.pageMatch(rawURL: rawURL, hostname: hostname, context: context, on: day)         }     } @@ -76,7 +77,8 @@ extension LibraryRepository {         ) { context in             if let workURL, let pageHostname,                let match = try Self.pageMatch(-                   rawURL: workURL, hostname: pageHostname, context: context)+                   rawURL: workURL, hostname: pageHostname, context: context,+                   on: CivilDay(clock.now(), calendar: .current))             {                 return .present(match)             }@@ -112,7 +114,7 @@ extension LibraryRepository {     /// the work (Q31). Among works the first in title order is named; among     /// unattached entries, the least by UUID, so the answer is deterministic.     static func pageMatch(-        rawURL: String, hostname: String, context: ModelContext+        rawURL: String, hostname: String, context: ModelContext, on day: CivilDay     ) throws -> PageMatch? {         let pageKey = try EntryIdentityNormalizer.key(forRawURL: rawURL)         var workIDs: Set<UUID> = []@@ -150,7 +152,7 @@ extension LibraryRepository {          if !workIDs.isEmpty {             let rows = try fetchWorks(ids: Array(workIDs), context: context)-            if let first = try workSummaries(rows, context: context).values+            if let first = try workSummaries(rows, context: context, on: day).values                 .min(by: WorkSummary.titleOrder)             {                 return .work(first)@@ -172,7 +174,8 @@ extension LibraryRepository {         let byID = try await withLockedContext(             mode: .shared, operation: "reading work summaries"         ) { context -> [UUID: WorkSummary] in-            try Self.workSummaries(Self.fetchWorks(ids: wanted, context: context), context: context)+            let day = CivilDay(clock.now(), calendar: .current)+            return try Self.workSummaries(Self.fetchWorks(ids: wanted, context: context), context: context, on: day)         }         var seen: Set<UUID> = []         return ids.compactMap { id in@@ -224,7 +227,8 @@ extension LibraryRepository {         operation: String, _ isIncluded: @escaping @Sendable (WorkSummary) -> Bool     ) async throws -> [WorkSummary] {         try await withLockedContext(mode: .shared, operation: operation) { context in-            try Self.workSummaries(context.fetch(FetchDescriptor<Work>()), context: context)+            let day = CivilDay(clock.now(), calendar: .current)+            return try Self.workSummaries(context.fetch(FetchDescriptor<Work>()), context: context, on: day)                 .values                 .filter(isIncluded)                 .sorted(by: WorkSummary.titleOrder)@@ -244,29 +248,30 @@ extension LibraryRepository {     /// more than one row is grouped, and the type directory is fetched only     /// when there is one.     static func workSummaries(-        _ rows: [Work], context: ModelContext+        _ rows: [Work], context: ModelContext, on day: CivilDay     ) throws -> [UUID: WorkSummary] {         let buckets = Dictionary(grouping: rows, by: \.id)         var types: WorkTypeDirectory?         var summaries: [UUID: WorkSummary] = [:]         for (id, rows) in buckets {+            for row in rows { _ = try row.decodedPublicationState() }             guard rows.count > 1 else {-                summaries[id] = summary(rows[0])+                summaries[id] = try summary(rows[0], on: day)                 continue             }             if types == nil { types = try workTypeDirectory(context: context) }             guard let types, let group = workGroup(id: id, rows: rows, types: types) else {                 continue             }-            summaries[id] = summary(group.carrier)+            summaries[id] = try summary(group.carrier, on: day)         }         return summaries     } -    private static func summary(_ presented: Work) -> WorkSummary {+    private static func summary(_ presented: Work, on day: CivilDay) throws -> WorkSummary {         WorkSummary(             id: presented.id, displayTitle: presented.displayTitle,-            readingStatus: presented.readingStatus, workStatus: presented.workStatus)+            readingStatus: presented.readingStatus, workStatus: try presented.effectiveWorkStatus(on: day))     }  }
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swiftindex 06a96b0e..7e1c3f5f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift@@ -58,8 +58,10 @@ extension LibraryRepository {             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 {+            guard TodaySchedule.isReleaseEligible(+                readingStatus: work.readingStatus, workStatus: work.workStatus,+                releaseDays: work.releaseDays, publicationState: try work.decodedPublicationState(),+                on: day, calendar: calendar) else {                 return .conflict(.recordChanged(recordID: workID))             }             let entries = try context.fetch(FetchDescriptor<Entry>(
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swiftindex 551b72c1..0c62e48b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift@@ -336,6 +336,7 @@ extension WorkEditBasis {             && content.genreTags == genreTags.sorted()             && content.typeAssignment == types.canonicalized(typeAssignment)             && content.workStatus == workStatus+            && content.publicationStateData == publicationStateData             && content.readingStatus == readingStatus             && content.verdict == verdict             // Req 2.4: `updateWork` writes both series columns to every row, so
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swiftindex 36682e3a..6070c11c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift@@ -314,11 +314,11 @@ extension LibraryRepository {         workGroups: [UUID: WorkGroup], entryRows: [Entry], canonicalWorkIDs: [UUID: UUID],         types: WorkTypeDirectory, calendar: Calendar, noEpisode: NoEpisodeIndex     ) throws -> TodaySchedule {-        let admitted = workGroups.values.filter { group in+        let admitted = try workGroups.values.filter { group in             let carrier = group.carrier             return TodaySchedule.admits(                 readingStatus: carrier.readingStatus, workStatus: carrier.workStatus,-                releaseDays: carrier.releaseDays) != nil+                releaseDays: carrier.releaseDays, publicationState: try carrier.decodedPublicationState()) != nil         }         guard !admitted.isEmpty else {             return TodaySchedule.build(works: [], calendar: calendar)
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swiftindex 05dd7e24..0d6c7e27 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift@@ -554,7 +554,10 @@ extension LibraryRepository {                     forDigest: identity.digest, in: sourceGroup.rows)             } +            let publicationStateData = try outcome.publicationState?.canonicalData()             for row in targetGroup.rows {+                row.publicationStateData = publicationStateData+                row.workStatusRaw = currentBasis.target.workStatusRaw                 row.genericNotes = outcome.genericNotes                 row.genreTags = outcome.genreTags                 // Req 1.11's guard: only a row whose digest differs is written,@@ -718,6 +721,9 @@ extension LibraryRepository {         if row.readingStatusRaw != overrides.readingStatusRaw {             row.readingStatusRaw = overrides.readingStatusRaw         }+        if row.publicationStateData != overrides.publicationStateData {+            row.publicationStateData = overrides.publicationStateData+        }         if row.workStatusRaw != overrides.workStatusRaw {             row.workStatusRaw = overrides.workStatusRaw         }
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex a27b2ce1..eab06b51 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -1492,9 +1492,17 @@ public actor LibraryRepository {             // schedule change, and a work with no latest has nothing to rebase.             let stored = group.carrier             let storedRecord = CatchUpFold.elect(group.rows.map(\.catchUpRecord))-            let crossesOngoing = (stored.workStatus == .ongoing) != (draft.workStatus == .ongoing)+            let today = CivilDay(timestamp, calendar: calendar)+            let oldPublication = try stored.decodedPublicationState()+            let publication = try WorkPublicationWriter.prepare(+                state: oldPublication, legacyStatus: stored.workStatus,+                edit: draft.publicationEdit, today: today)+            let publicationData = publication.didEdit+                ? try publication.state?.canonicalData() : stored.publicationStateData+            let authoredStatusRaw = publication.didEdit+                ? publication.authoredStatus.rawValue : stored.workStatusRaw             let changesDays = stored.releaseDays != ReleaseDay.canonical(draft.releaseDays)-            if storedRecord.latest != nil && (crossesOngoing || changesDays) {+            if storedRecord.latest != nil && (publication.rebasesStatus || changesDays) {                 let workID = group.id                 let entryRows = try context.fetch(FetchDescriptor<Entry>(                     predicate: #Predicate<Entry> { $0.work?.id == workID }))@@ -1507,12 +1515,24 @@ public actor LibraryRepository {                 let notedDays = Set(entrySnapshots.map {                     CivilDay($0.lastSharedAt, calendar: calendar)                 })+                // A schedule edit uses the resulting pauses under the old weekdays.+                // Finished time never accrues; a status-only finish measures the+                // old paused state before its interval is closed.+                let wasFinished = (oldPublication?.status(on: today) ?? stored.workStatus) == .finished+                var rebaseState = oldPublication+                if changesDays && !wasFinished {+                    rebaseState = publication.state+                    if rebaseState?.authoredStatus == .finished, let state = rebaseState {+                        rebaseState = try WorkPublicationState(status: .ongoing, closedPauses: state.closedPauses)+                    }+                }                 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)+                    workStatus: stored.workStatus, publicationState: rebaseState,+                    now: timestamp, calendar: calendar)                 {                     CatchUpWriter.apply(rebased, to: group.rows)                 }@@ -1532,7 +1552,8 @@ public actor LibraryRepository {                 // is written, so an unknown stored spelling is replaced rather                 // than preserved — the draft has no representation for a value                 // the picker cannot name.-                work.workStatus = draft.workStatus+                work.publicationStateData = publicationData+                work.workStatusRaw = authoredStatusRaw                 work.readingStatus = draft.readingStatus                 work.verdict = normalizedVerdict                 // Req 2.8: the pair lands on every row of the group beside the@@ -1874,7 +1895,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 `BackupV17Entry`+    // own `map*Record` family in `BackupArchiveProjection`, over `BackupV18Entry`     // and friends, and never used these.      internal func withLockedContext<Value: Sendable>(@@ -2144,7 +2165,7 @@ public actor LibraryRepository {         _ work: Work, types: WorkTypeDirectory, series: SeriesDirectory, credits: CreditIndex,         history: NoEpisodeHistory     ) throws -> WorkSnapshot {-        snapshot(+        try snapshot(             work, entries: try work.entryValues.map(snapshot).sorted(by: entryActivityOrder),             types: types, series: series, credits: credits, history: history)     }@@ -2161,7 +2182,7 @@ public actor LibraryRepository {     internal static func snapshot(         _ work: Work, entries: [EntrySnapshot], types: WorkTypeDirectory,         series: SeriesDirectory, credits: CreditIndex, history: NoEpisodeHistory-    ) -> WorkSnapshot {+    ) throws -> WorkSnapshot {         let membership = GroupOrdering.membership(of: work)         return WorkSnapshot(             id: work.id,@@ -2177,7 +2198,7 @@ public actor LibraryRepository {             entries: entries,             // The tolerant accessors, like `titleProvenance` above (Q2): an             // unknown raw value is a library mid-rollout, not corruption.-            workStatus: work.workStatus,+            authoredWorkStatus: work.workStatus,             readingStatus: work.readingStatus,             verdict: work.verdict,             // Both halves or neither, and the series resolved through the@@ -2201,7 +2222,8 @@ public actor LibraryRepository {             releaseDays: work.releaseDays,             releaseDaysRaw: work.releaseDaysRaw,             catchUp: work.catchUpRecord,-            noEpisodeHistory: history+            noEpisodeHistory: history,+            publicationState: try work.decodedPublicationState()         )     } 
Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swiftindex bddf385c..353e0b5a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift@@ -252,6 +252,7 @@ public struct WorkEditBasis: Sendable, Equatable {     /// verdict changed elsewhere between the read and the write is an edit     /// conflict exactly as a changed title is — `matches` compares all three.     public let workStatus: WorkStatus+    public let publicationStateData: Data?     public let readingStatus: ReadingStatus     public let verdict: String     /// V11 (Req 2.4): the membership the edit started from. A pair changed@@ -285,7 +286,8 @@ public struct WorkEditBasis: Sendable, Equatable {         verdict: String = "",         membership: SeriesMembership? = nil,         thumbnail: ThumbnailIdentity? = nil,-        releaseDays: [ReleaseDay] = []+        releaseDays: [ReleaseDay] = [],+        publicationStateData: Data? = nil     ) {         self.releaseDays = ReleaseDay.canonical(releaseDays)         self.thumbnail = thumbnail@@ -297,7 +299,9 @@ public struct WorkEditBasis: Sendable, Equatable {         self.memberships = memberships         self.lastParsedTitle = lastParsedTitle         self.titleProvenance = titleProvenance-        self.workStatus = workStatus+        let state = publicationStateData.flatMap { try? WorkPublicationState.decode($0) }+        self.publicationStateData = state.map { try! $0.canonicalData() } ?? publicationStateData+        self.workStatus = state?.authoredStatus ?? workStatus         self.readingStatus = readingStatus         self.verdict = verdict     }@@ -312,7 +316,7 @@ public struct WorkEditBasis: Sendable, Equatable {             },             lastParsedTitle: work.lastParsedTitle,             titleProvenance: work.titleProvenance,-            workStatus: work.workStatus,+            workStatus: work.authoredWorkStatus,             readingStatus: work.readingStatus,             verdict: work.verdict,             membership: work.membership,@@ -321,7 +325,8 @@ public struct WorkEditBasis: Sendable, Equatable {             // against what `authoredContent` reads off the survivor, which is             // tolerant too, so an unknown spelling on either side is not a             // divergence on its own (`update-schedule` Req 1.6).-            releaseDays: work.releaseDays)+            releaseDays: work.releaseDays,+            publicationStateData: work.publicationStateData)     }      /// The basis's first membership hostname, or the empty string — the same
Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/MembershipReconciler.swiftindex 6a74f11c..a73e330b 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 `BackupV17Exporter`'s decode-validation refuses the file it just wrote.+    /// and `BackupV18Exporter`'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
Packages/AsterismCore/Sources/AsterismCore/Models.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Models.swift b/Packages/AsterismCore/Sources/AsterismCore/Models.swiftindex bc1cca6a..2e6d0907 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Models.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Models.swift@@ -1,7 +1,7 @@ import Foundation import SwiftData -// The live model classes are V18's, nested inside `AsterismSchemaV18`+// The live model classes are V19's, nested inside `AsterismSchemaV19` // (Decision 6, Q20). Top-level typealiases keep every call site (`Entry`, // `Site`, …) unchanged. //@@ -11,57 +11,57 @@ import SwiftData // *top-level* `@Model` per entity name — and there are none, because every // top-level name here is a typealias. Two top-level `@Model`s sharing an entity // name crash `ModelContext` (`docs/agent-notes/schema-migration.md`).-public typealias Entry = 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+public typealias Entry = AsterismSchemaV19.Entry+public typealias Work = AsterismSchemaV19.Work+public typealias Site = AsterismSchemaV19.Site+public typealias TitlePattern = AsterismSchemaV19.TitlePattern+public typealias URLRulePattern = AsterismSchemaV19.URLRulePattern+public typealias WorkTypeEntity = AsterismSchemaV19.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 = AsterismSchemaV18.WorkSiteMembership+public typealias WorkSiteMembership = AsterismSchemaV19.WorkSiteMembership /// V8: a reader's "not the same work" over an unordered pair of Works (Q20).-public typealias WorkDistinctPair = AsterismSchemaV18.WorkDistinctPair+public typealias WorkDistinctPair = AsterismSchemaV19.WorkDistinctPair /// V11: a reader-named, ordered collection a Work belongs to at most once /// (`series-and-related-works` Decision 1).-public typealias Series = AsterismSchemaV18.Series+public typealias Series = AsterismSchemaV19.Series /// V11: an undirected, typed connection between two distinct Works /// (`series-and-related-works` Decision 5).-public typealias WorkLink = AsterismSchemaV18.WorkLink+public typealias WorkLink = AsterismSchemaV19.WorkLink /// V12: a person a work is credited to, a reader-managed directory record /// (`work-creators` Decision 2).-public typealias Creator = AsterismSchemaV18.Creator+public typealias Creator = AsterismSchemaV19.Creator /// V12: one entry in the ordered role list credits reference by identity /// (`work-creators` Decision 1).-public typealias CreatorRole = AsterismSchemaV18.CreatorRole+public typealias CreatorRole = AsterismSchemaV19.CreatorRole /// V12: one work-and-creator pairing, carrying the roles that creator holds on /// that work (`work-creators` Decision 6).-public typealias WorkCredit = AsterismSchemaV18.WorkCredit+public typealias WorkCredit = AsterismSchemaV19.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 = AsterismSchemaV18.Character-public typealias CharacterSuppression = AsterismSchemaV18.CharacterSuppression+public typealias CharacterRecord = AsterismSchemaV19.Character+public typealias CharacterSuppression = AsterismSchemaV19.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 = AsterismSchemaV18.Place+public typealias Place = AsterismSchemaV19.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 = AsterismSchemaV18.PlaceSuppression-public typealias NoEpisodeAction = AsterismSchemaV18.NoEpisodeAction+public typealias PlaceSuppression = AsterismSchemaV19.PlaceSuppression+public typealias NoEpisodeAction = AsterismSchemaV19.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`, `BackupV17Types`, `BackupArchiveProjection` — each+/// `ArchiveRecordBuilders`, `BackupV18Types`, `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. ///@@ -136,7 +136,7 @@ enum JSONBlob {     } } -extension AsterismSchemaV18 {+extension AsterismSchemaV19 {  @Model public final class Entry {@@ -424,6 +424,8 @@ public final class Work {     /// V17: independently elected catch-up progress values. Optional blobs migrate as nil.     public var catchUpConfirmationData: Data? = nil     public var lastChapterOverrideData: Data? = nil+    /// V19: one authored publication state; nil retains legacy status behaviour.+    public var publicationStateData: Data? = nil     /// V14: the reader's cover for this work, as JPEG bytes     /// (`work-thumbnails` Decision 2, Req 1.1).     ///@@ -702,9 +704,8 @@ public final class 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 `AsterismSchemaV18` snapshot, which is frozen by-    // reference to it (Q8).+    // `JunkSuffixRule` remains in `ValueObjects.swift` for historical contract+    // tests; the live schema has no consumer.      public init(hostname: String, displayName: String? = nil) {         self.hostname = hostname@@ -1764,7 +1765,7 @@ public final class PlaceSuppression {     } } -} // extension AsterismSchemaV18+} // extension AsterismSchemaV19  /// 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).
Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swiftindex 626730f3..a06ccc08 100644--- a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift@@ -27,7 +27,7 @@ public struct NoEpisodeHistory: Equatable, Sendable {             guard Self.validKey(key, kind: kind, day: day) else {                 throw HistoryError.invalidKey(key)             }-            guard Self.civilDay(day) != nil else { throw HistoryError.invalidDay(day) }+            guard CivilDateCodec.parse(day) != nil else { throw HistoryError.invalidDay(day) }             guard kind == .mark || observedClearKeys.isEmpty else {                 throw HistoryError.invalidPayload             }@@ -89,23 +89,10 @@ public struct NoEpisodeHistory: Equatable, Sendable {          public var civilDay: CivilDay {             // Constructor and decoder validate this spelling.-            Self.civilDay(day)!+            CivilDateCodec.parse(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
Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift b/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swiftindex 249d201e..201e40e9 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift@@ -548,6 +548,7 @@ public struct WorkMergeWorkBasis: Equatable, Sendable {     /// can be done through a tolerated enum: an unknown raw status reads as the     /// default. Part of the basis, so a raw-only change behind the preview     /// refreshes it.+    public let publicationStateData: Data?     public let workStatusRaw: String     public let readingStatusRaw: String     public let titleProvenanceRaw: String@@ -571,10 +572,11 @@ public struct WorkMergeWorkBasis: Equatable, Sendable {         titleProvenanceRaw: String? = nil,         releaseDaysRaw: [String]? = nil     ) {+        self.publicationStateData = snapshot.publicationStateData         self.snapshot = snapshot         self.identitiesByHostname = identitiesByHostname         self.entries = entries ?? snapshot.entries.map { WorkMergeEntryBasis(snapshot: $0) }-        self.workStatusRaw = workStatusRaw ?? snapshot.workStatus.rawValue+        self.workStatusRaw = workStatusRaw ?? snapshot.authoredWorkStatus.rawValue         self.readingStatusRaw = readingStatusRaw ?? snapshot.readingStatus.rawValue         self.titleProvenanceRaw = titleProvenanceRaw ?? snapshot.titleProvenance.rawValue         self.releaseDaysRaw = releaseDaysRaw ?? snapshot.releaseDaysRaw@@ -750,6 +752,7 @@ public struct WorkMergeRawOverrides: Equatable, Sendable {     public let lastParsedTitle: String?     public let titleProvenanceRaw: String     public let readingStatusRaw: String+    public let publicationStateData: Data?     public let workStatusRaw: String     public let verdict: String     public let releaseDaysRaw: [String]@@ -761,8 +764,10 @@ public struct WorkMergeRawOverrides: Equatable, Sendable {         readingStatusRaw: String,         workStatusRaw: String,         verdict: String,-        releaseDaysRaw: [String]+        releaseDaysRaw: [String],+        publicationStateData: Data? = nil     ) {+        self.publicationStateData = publicationStateData         self.displayTitle = displayTitle         self.lastParsedTitle = lastParsedTitle         self.titleProvenanceRaw = titleProvenanceRaw@@ -792,9 +797,11 @@ public enum WorkMergeField: String, Equatable, Hashable, Sendable, CaseIterable     // V10 (Req 7.3): the merged Work keeps the target's three, and the source's     // are reported.     case targetWorkStatus+    case targetPublicationState     case targetReadingStatus     case targetVerdict     case sourceWorkStatus+    case sourcePublicationState     case sourceReadingStatus     case sourceVerdict     // V11 (`series-and-related-works` Reqs 9.1, 9.2): the merged Work carries@@ -837,6 +844,7 @@ public enum WorkMergeField: String, Equatable, Hashable, Sendable, CaseIterable         // text, and a picture is not text — so the preview saying so is the         // whole of what the reader gets (Req 1.5).         case .sourceGenreTags, .sourceWorkStatus, .sourceReadingStatus,+             .targetPublicationState, .sourcePublicationState,              .targetDisplayTitle, .sourceDisplayTitle, .targetType, .targetWorkURL, .targetNotes,              .targetGenreTags, .targetWorkStatus, .targetReadingStatus, .targetVerdict,              .targetSeries, .sourceSeries,@@ -930,6 +938,7 @@ public struct WorkMergeOutcome: Equatable, Sendable {     /// V10: the target's three, kept whole like `typeDisplay` — the fold never     /// moves them, so the preview names what the merged Work will carry     /// (Req 7.3, Q13).+    public let publicationState: WorkPublicationState?     public let workStatus: WorkStatus     public let readingStatus: ReadingStatus     public let verdict: String@@ -1021,6 +1030,7 @@ public struct WorkMergeOutcome: Equatable, Sendable {         // preview, and a caller that omits them is describing a Work on the         // defaults rather than moving anybody's status.         workStatus: WorkStatus = .ongoing,+        publicationState: WorkPublicationState? = nil,         readingStatus: ReadingStatus = .reading,         verdict: String = "",         // Defaulted for the reason above: an outcome built by hand is describing@@ -1051,6 +1061,7 @@ public struct WorkMergeOutcome: Equatable, Sendable {         self.seriesName = seriesName         self.discardedMembership = discardedMembership         self.discardedLinks = discardedLinks+        self.publicationState = publicationState         self.workStatus = workStatus         self.readingStatus = readingStatus         self.verdict = verdict
Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swiftindex 08ba0ae5..433a5ec3 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: BackupV17Character) -> CharacterRecord {+    public static func make(imported record: BackupV18Character) -> CharacterRecord {         ArchiveRecordBuilders.makeCharacter(record)     } @@ -238,7 +238,7 @@ extension CharacterSuppression: SuppressionRow {             evidence: evidence, status: status, actionAt: actionAt)     } -    public static func make(imported record: BackupV17Suppression) -> CharacterSuppression {+    public static func make(imported record: BackupV18Suppression) -> CharacterSuppression {         ArchiveRecordBuilders.makeSuppression(record)     } @@ -296,7 +296,7 @@ extension Place: RecordRow {             timestamp: timestamp, workID: work?.id ?? UUID())     } -    public static func make(imported record: BackupV17Place) -> Place {+    public static func make(imported record: BackupV18Place) -> Place {         ArchiveRecordBuilders.makePlace(record)     } @@ -349,7 +349,7 @@ extension PlaceSuppression: SuppressionRow {             evidence: evidence, status: status, actionAt: actionAt)     } -    public static func make(imported record: BackupV17PlaceSuppression) -> PlaceSuppression {+    public static func make(imported record: BackupV18PlaceSuppression) -> PlaceSuppression {         ArchiveRecordBuilders.makePlaceSuppression(record)     } 
Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift b/Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swiftindex 725d05ce..b7bbe751 100644--- a/Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift@@ -67,11 +67,9 @@ public struct WorkMetadataDraft: Equatable, Sendable {     public let typeAssignment: WorkTypeAssignment     public let genreTags: [String]     public let genericNotes: String-    /// V10, and **not** defaulted (Q40): `updateWork` writes all three to every-    /// row of the group, so a draft built without them would silently reset a-    /// reader's statuses with no compiler error. Every caller states what the-    /// editor showed.-    public let workStatus: WorkStatus+    /// Required: metadata-only saves explicitly retain publication evidence;+    /// status/date edits deliberately replace it through the publication writer.+    public let publicationEdit: WorkPublicationEdit     public let readingStatus: ReadingStatus     /// Trimmed on write, in `updateWork` and nowhere else (Q33).     public let verdict: String@@ -108,7 +106,7 @@ public struct WorkMetadataDraft: Equatable, Sendable {     public init(         displayTitle: String, typeAssignment: WorkTypeAssignment, genreTags: [String],         genericNotes: String,-        workStatus: WorkStatus, readingStatus: ReadingStatus, verdict: String,+        publicationEdit: WorkPublicationEdit, readingStatus: ReadingStatus, verdict: String,         releaseDays: [ReleaseDay],         membership: SeriesMembership?,         credits: CreditsDraft? = nil,@@ -122,7 +120,7 @@ public struct WorkMetadataDraft: Equatable, Sendable {         self.typeAssignment = typeAssignment         self.genreTags = genreTags         self.genericNotes = genericNotes-        self.workStatus = workStatus+        self.publicationEdit = publicationEdit         self.readingStatus = readingStatus         self.verdict = verdict     }
Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swiftindex d040ab03..538ea5ae 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift@@ -121,7 +121,17 @@ public struct WorkSnapshot: Equatable, Sendable {     /// V10: where the *work* stands (Req 2.1), read through the tolerant     /// accessor, so an unknown stored spelling presents as the default rather     /// than refusing the read (Req 1.3, 2.7).-    public let workStatus: WorkStatus+    /// Authored compatibility spelling; presentation resolves an explicit day.+    public let authoredWorkStatus: WorkStatus+    public let publicationState: WorkPublicationState?++    public var publicationStateData: Data? {+        publicationState.map { try! $0.canonicalData() }+    }++    public func effectiveWorkStatus(on day: CivilDay) -> WorkStatus {+        publicationState?.status(on: day) ?? authoredWorkStatus+    }     /// V10: where the *reader* stands with it (Req 2.1).     public let readingStatus: ReadingStatus     /// V10: the reader's closing thought, stored trimmed (Req 2.4). Kept when a@@ -258,7 +268,7 @@ public struct WorkSnapshot: Equatable, Sendable {         // Defaulted, unlike `WorkMetadataDraft`'s (Q40): a snapshot only ever         // reads, so a fixture that omits them describes a work on the defaults         // rather than silently resetting a reader's statuses.-        workStatus: WorkStatus = .ongoing,+        authoredWorkStatus: WorkStatus = .ongoing,         readingStatus: ReadingStatus = .reading,         verdict: String = "",         // Defaulted for the same reason the three above are: a snapshot only@@ -274,7 +284,8 @@ public struct WorkSnapshot: Equatable, Sendable {         releaseDays: [ReleaseDay] = [],         releaseDaysRaw: [String]? = nil,         catchUp: CatchUpRecord = .pristine,-        noEpisodeHistory: NoEpisodeHistory = .empty+        noEpisodeHistory: NoEpisodeHistory = .empty,+        publicationState: WorkPublicationState? = nil     ) {         // 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@@ -285,7 +296,8 @@ public struct WorkSnapshot: Equatable, Sendable {         self.noEpisodeHistory = noEpisodeHistory         self.thumbnail = thumbnail         self.credits = credits-        self.workStatus = workStatus+        self.publicationState = publicationState+        self.authoredWorkStatus = publicationState?.authoredStatus ?? authoredWorkStatus         self.readingStatus = readingStatus         self.verdict = verdict         self.membership = membership
Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swiftindex 12d8371a..a063da80 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Thumbnails/CoveredWorkFixture.swift@@ -67,7 +67,7 @@ extension LibraryRepository {                 typeAssignment: reloaded.typeDisplay.assignment,                 genreTags: reloaded.genreTags,                 genericNotes: reloaded.genericNotes,-                workStatus: reloaded.workStatus,+                publicationEdit: .unchanged,                 readingStatus: reloaded.readingStatus,                 verdict: reloaded.verdict,                 releaseDays: reloaded.releaseDays,
Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift b/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swiftindex 17640691..bcf075aa 100644--- a/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift@@ -235,15 +235,32 @@ public struct TodaySchedule: Equatable, Sendable {     /// thing a later change to Req 6.1 relaxes, and a catch-up work with release     /// days must never be swallowed by the scheduled bucket when it does.     public static func admits(-        readingStatus: ReadingStatus, workStatus: WorkStatus, releaseDays: [ReleaseDay]+        readingStatus: ReadingStatus, workStatus: WorkStatus, releaseDays: [ReleaseDay],+        publicationState: WorkPublicationState? = nil     ) -> Bucket? {         if readingStatus == .catchingUp { return .catchingUp }-        if workStatus == .ongoing && readingStatus == .reading && !releaseDays.isEmpty {+        let authoredStatus = publicationState?.authoredStatus ?? workStatus+        let pause = publicationState?.currentPause+        let hasEligibleDays = authoredStatus == .hiatus && (pause?.start != nil || pause?.returnDate != nil)+        if (authoredStatus == .ongoing || hasEligibleDays) && readingStatus == .reading && !releaseDays.isEmpty {             return .scheduled         }         return nil     } +    /// Candidate membership is broader than one day's release eligibility.+    /// This is also the command rule for recording a no-episode mark.+    public static func isReleaseEligible(+        readingStatus: ReadingStatus, workStatus: WorkStatus, releaseDays: [ReleaseDay],+        publicationState: WorkPublicationState? = nil, on day: CivilDay, calendar: Calendar+    ) -> Bool {+        admits(readingStatus: readingStatus, workStatus: workStatus, releaseDays: releaseDays,+            publicationState: publicationState) == .scheduled+            && (publicationState?.status(on: day) ?? workStatus) == .ongoing+            && !(publicationState?.isPaused(on: day) ?? false)+            && releaseDays.contains(day.weekday(calendar: calendar))+    }+     /// The schedule the library's works amount to under `calendar`.     ///     /// O(works + entries), and the calendar is consulted only to bucket each@@ -254,8 +271,8 @@ public struct TodaySchedule: Equatable, Sendable {         var catchingUpSnapshots: [WorkSnapshot] = []         for work in works {             switch admits(-                readingStatus: work.readingStatus, workStatus: work.workStatus,-                releaseDays: work.releaseDays)+                readingStatus: work.readingStatus, workStatus: work.authoredWorkStatus,+                releaseDays: work.releaseDays, publicationState: work.publicationState)             {             case .catchingUp: catchingUpSnapshots.append(work)             case .scheduled: scheduledSnapshots.append(work)@@ -308,6 +325,7 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable {     public let catchUp: CatchUpRecord     public let numberedNotes: [NumberedNote]     public let workStatus: WorkStatus+    public let publicationState: WorkPublicationState?     /// 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]@@ -321,7 +339,8 @@ 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, noEpisodeDays: Set<CivilDay> = []+        primaryURL: URL? = nil, noEpisodeDays: Set<CivilDay> = [],+        publicationState: WorkPublicationState? = nil     ) {         self.id = id         self.title = title@@ -333,7 +352,8 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable {         self.noEpisodeDays = noEpisodeDays.subtracting(notedDays.map(\.day))         self.catchUp = catchUp         self.numberedNotes = numberedNotes-        self.workStatus = workStatus+        self.publicationState = publicationState+        self.workStatus = publicationState?.authoredStatus ?? workStatus         self.primaryURL = primaryURL     } @@ -349,9 +369,10 @@ public struct ScheduledWork: Equatable, Sendable, Identifiable {             notedDays: Self.notedDays(of: snapshot.entries, calendar: calendar),             catchUp: snapshot.catchUp,             numberedNotes: NumberedNote.from(snapshot.entries),-            workStatus: snapshot.workStatus,+            workStatus: snapshot.authoredWorkStatus,             primaryURL: snapshot.primaryURL,-            noEpisodeDays: snapshot.noEpisodeHistory.activeDays(for: snapshot.id))+            noEpisodeDays: snapshot.noEpisodeHistory.activeDays(for: snapshot.id),+            publicationState: snapshot.publicationState)     }      /// One `NotedDay` per civil day, newest first, each naming the day's most@@ -455,9 +476,12 @@ public struct TodayDayPlan: Equatable, Sendable {         day: CivilDay, currentDay: CivilDay, schedule: TodaySchedule,         presentation: TodayPresentation, calendar: Calendar     ) -> TodayDayPlan {-        let weekday = day.weekday(calendar: calendar)         let releases = schedule.works-            .filter { $0.releaseDays.contains(weekday) }+            .filter {+                TodaySchedule.isReleaseEligible(readingStatus: .reading, workStatus: $0.workStatus,+                    releaseDays: $0.releaseDays, publicationState: $0.publicationState,+                    on: day, calendar: calendar)+            }             .map { work in                 row(for: work, on: day, calendar: calendar, countsReleases: false)             }@@ -497,7 +521,8 @@ public struct TodayDayPlan: Equatable, Sendable {         let progress = CatchUpProgress.build(             record: work.catchUp, notes: work.numberedNotes,             releaseDays: work.releaseDays, noEpisodeDays: work.noEpisodeDays,-            workStatus: work.workStatus, day: day, calendar: calendar)+            workStatus: work.workStatus, publicationState: work.publicationState,+            day: day, calendar: calendar)         let unknownReadDay = countsReleases && progress.state == .unknown             ? progress.readDay : nil         let unknownLine: ReleaseRow.Line? =@@ -514,13 +539,16 @@ public struct TodayDayPlan: Equatable, Sendable {             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,+            progress: progress, workStatus: work.publicationState?.status(on: day) ?? work.workStatus,             lastChapter: progress.lastRead,             lastNotedDay: unknownReadDay ?? latest?.day,             releasesSince: countsReleases-                ? (unknownReadDay ?? latest?.day).flatMap {-                    releaseCount(-                        of: work.releaseDays, after: $0, through: day,+                ? (unknownReadDay ?? latest?.day).flatMap { start in+                    work.publicationState.map { state in+                        state.excludingPauses(after: start, through: day,+                            releaseDays: work.releaseDays, noEpisodeDays: work.noEpisodeDays, calendar: calendar)+                    } ?? releaseCount(+                        of: work.releaseDays, after: start, through: day,                         noEpisodeDays: work.noEpisodeDays, calendar: calendar)                 } : nil,             primaryURL: work.primaryURL)
Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift b/Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swiftindex e54908fa..f9ad0104 100644--- a/Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift@@ -295,7 +295,8 @@ public enum WorkMergePlanner {             // Req 7.3: the target's, as its type and its title are. The commit's             // target loop writes none of them, so the preview and the row agree.             // A `.toReadMatch` overlay replaces them, and its commit writes them.-            workStatus: overlay?.workStatus ?? target.workStatus,+            workStatus: overlay?.workStatus ?? target.authoredWorkStatus,+            publicationState: overlay.map(\.publicationState) ?? target.publicationState,             readingStatus: overlay?.readingStatus ?? target.readingStatus,             verdict: overlay?.overrides.verdict ?? target.verdict,             // V11: the fold decided the pair; the label is this planner's,@@ -327,6 +328,7 @@ public enum WorkMergePlanner {         let titleProvenance: TitleProvenance         let readingStatus: ReadingStatus         let workStatus: WorkStatus+        let publicationState: WorkPublicationState?         let releaseDays: [ReleaseDay]         let retained: [WorkMergeField]         let discarded: [WorkMergeField]@@ -340,6 +342,7 @@ public enum WorkMergePlanner {         .targetDisplayTitle, .sourceManualTitle,         .targetReadingStatus, .sourceReadingStatus,         .targetWorkStatus, .sourceWorkStatus,+        .targetPublicationState, .sourcePublicationState,         .targetVerdict, .sourceVerdict,         .targetReleaseDays, .sourceReleaseDays,     ]@@ -363,6 +366,7 @@ public enum WorkMergePlanner {         let targetWork = target.snapshot          let takesWorkStatus = target.workStatusRaw == WorkStatus.ongoing.rawValue+            && target.publicationStateData == nil         let takesVerdict = M2Unicode.isBlank(targetWork.verdict)         let takesReleaseDays = target.releaseDaysRaw.isEmpty @@ -383,6 +387,13 @@ public enum WorkMergePlanner {             source.workStatusRaw != target.workStatusRaw {             dropped.append(.sourceWorkStatus)         }+        if (takesWorkStatus ? source.publicationStateData : target.publicationStateData) != nil {+            kept.append(takesWorkStatus ? .sourcePublicationState : .targetPublicationState)+        }+        if !takesWorkStatus, source.publicationStateData != nil,+           source.publicationStateData != target.publicationStateData {+            dropped.append(.sourcePublicationState)+        }         let verdictLost = !takesVerdict && !M2Unicode.isBlank(sourceWork.verdict)             && ExactScalarString(sourceWork.verdict) != ExactScalarString(targetWork.verdict)         kept.append(takesVerdict ? .sourceVerdict : .targetVerdict)@@ -413,10 +424,12 @@ public enum WorkMergePlanner {                 readingStatusRaw: source.readingStatusRaw,                 workStatusRaw: takesWorkStatus ? source.workStatusRaw : target.workStatusRaw,                 verdict: takesVerdict ? sourceWork.verdict : targetWork.verdict,-                releaseDaysRaw: takesReleaseDays ? source.releaseDaysRaw : target.releaseDaysRaw),+                releaseDaysRaw: takesReleaseDays ? source.releaseDaysRaw : target.releaseDaysRaw,+                publicationStateData: takesWorkStatus ? source.publicationStateData : target.publicationStateData),             titleProvenance: sourceWork.titleProvenance,             readingStatus: sourceWork.readingStatus,-            workStatus: takesWorkStatus ? sourceWork.workStatus : targetWork.workStatus,+            workStatus: takesWorkStatus ? sourceWork.authoredWorkStatus : targetWork.authoredWorkStatus,+            publicationState: takesWorkStatus ? sourceWork.publicationState : targetWork.publicationState,             releaseDays: takesReleaseDays ? sourceWork.releaseDays : targetWork.releaseDays,             retained: kept,             discarded: dropped,
Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift b/Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swiftnew file mode 100644index 00000000..e0f5ff7f--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift@@ -0,0 +1,170 @@+import Foundation++/// One authored publication value. Passing time resolves it without rewriting it.+public struct WorkPublicationState: Equatable, Sendable, Codable {+    public enum StateError: Error, Equatable {+        case unsupportedVersion(Int)+        case invalidDate(String)+        case invalidPause+        case invalidStatus+        case noncanonicalIntervals+    }++    public struct ClosedPause: Equatable, Sendable {+        public let start: CivilDay?+        public let end: CivilDay+        public init(start: CivilDay?, end: CivilDay) { self.start = start; self.end = end }+    }++    public struct CurrentPause: Equatable, Sendable {+        public let start: CivilDay?+        public let returnDate: CivilDay?+        public init(start: CivilDay?, returnDate: CivilDay? = nil) {+            self.start = start+            self.returnDate = returnDate+        }+    }++    public let authoredStatus: WorkStatus+    public let closedPauses: [ClosedPause]+    public let currentPause: CurrentPause?++    /// Writers canonicalize once; decoders additionally require canonical input.+    public init(status: WorkStatus, closedPauses: [ClosedPause] = [], currentPause: CurrentPause? = nil) throws {+        guard (status == .hiatus) == (currentPause != nil) else { throw StateError.invalidStatus }+        if let pause = currentPause, let start = pause.start, let end = pause.returnDate, end < start {+            throw StateError.invalidPause+        }+        let closed = try Self.normalized(closedPauses)+        if let currentPause, let last = closed.last {+            guard let start = currentPause.start, start >= last.end else { throw StateError.invalidPause }+        }+        if let pause = currentPause, let start = pause.start, start == pause.returnDate {+            self.authoredStatus = .ongoing+            self.currentPause = nil+        } else {+            self.authoredStatus = status+            self.currentPause = currentPause+        }+        self.closedPauses = closed+    }++    public func status(on day: CivilDay) -> WorkStatus {+        guard authoredStatus != .finished else { return .finished }+        return isPaused(on: day) ? .hiatus : .ongoing+    }++    public func pendingReturn(on day: CivilDay) -> CivilDay? {+        status(on: day) == .hiatus ? currentPause?.returnDate : nil+    }++    public func isPaused(on day: CivilDay) -> Bool {+        if let pause = currentPause,+           pause.start.map({ day >= $0 }) ?? true,+           pause.returnDate.map({ day < $0 }) ?? true { return true }+        // Sorted, disjoint intervals let callers test a mark without scanning history.+        var lower = 0+        var upper = closedPauses.count+        while lower < upper {+            let middle = (lower + upper) / 2+            if closedPauses[middle].end <= day { lower = middle + 1 } else { upper = middle }+        }+        guard lower < closedPauses.count else { return false }+        return closedPauses[lower].start.map { day >= $0 } ?? true+    }++    /// Count normal weekdays in (start, end], excluding pause evidence and marks.+    /// Day spans use whole-week arithmetic; no calendar-day enumeration is needed.+    public func excludingPauses(+        after start: CivilDay, through end: CivilDay, releaseDays: [ReleaseDay],+        noEpisodeDays: Set<CivilDay> = [], calendar: Calendar+    ) -> Int? {+        guard var count = TodayDayPlan.releaseCount(of: releaseDays, after: start, through: end, calendar: calendar)+        else { return nil }+        guard end > start else { return 0 }+        func pausedCount(from pauseStart: CivilDay?, until pauseEnd: CivilDay?) -> Int {+            let lower = max(start.adding(days: 1, calendar: calendar), pauseStart ?? start)+            let upper = min(end, pauseEnd?.adding(days: -1, calendar: calendar) ?? end)+            guard lower <= upper else { return 0 }+            return TodayDayPlan.releaseCount(of: releaseDays,+                after: lower.adding(days: -1, calendar: calendar), through: upper, calendar: calendar) ?? 0+        }+        for pause in closedPauses { count -= pausedCount(from: pause.start, until: pause.end) }+        if let pause = currentPause { count -= pausedCount(from: pause.start, until: pause.returnDate) }+        let due = Set(releaseDays)+        count -= noEpisodeDays.filter {+            start < $0 && $0 <= end && due.contains($0.weekday(calendar: calendar)) && !isPaused(on: $0)+        }.count+        return count+    }++    private static func normalized(_ input: [ClosedPause]) throws -> [ClosedPause] {+        for pause in input where pause.start.map({ $0 > pause.end }) ?? false { throw StateError.invalidPause }+        let sorted = input.filter { $0.start != $0.end }.sorted {+            switch ($0.start, $1.start) {+            case (nil, nil): return $0.end < $1.end+            case (nil, _): return true+            case (_, nil): return false+            case let (left?, right?): return left == right ? $0.end < $1.end : left < right+            }+        }+        var result: [ClosedPause] = []+        for pause in sorted {+            if let last = result.last, pause.start.map({ $0 <= last.end }) ?? true {+                result[result.count - 1] = ClosedPause(start: last.start, end: max(last.end, pause.end))+            } else { result.append(pause) }+        }+        return result+    }++    private struct ClosedWire: Codable { let start: String?; let end: String }+    private struct CurrentWire: Codable { let start: String?; let returnDate: String? }+    private struct Wire: Codable {+        let version: Int+        let status: WorkStatus+        let closedPauses: [ClosedWire]+        let currentPause: CurrentWire?+    }++    public init(from decoder: any Decoder) throws {+        let wire = try Wire(from: decoder)+        guard wire.version == 1 else { throw StateError.unsupportedVersion(wire.version) }+        func day(_ value: String) throws -> CivilDay {+            guard let result = CivilDateCodec.parse(value), CivilDateCodec.spelling(result) == value else { throw StateError.invalidDate(value) }+            return result+        }+        let closed = try wire.closedPauses.map { try ClosedPause(start: $0.start.map(day), end: day($0.end)) }+        let current = try wire.currentPause.map { try CurrentPause(start: $0.start.map(day), returnDate: $0.returnDate.map(day)) }+        let value = try Self(status: wire.status, closedPauses: closed, currentPause: current)+        guard value.closedPauses == closed, value.currentPause == current, value.authoredStatus == wire.status else {+            throw StateError.noncanonicalIntervals+        }+        self = value+    }++    public func encode(to encoder: any Encoder) throws {+        try Wire(version: 1, status: authoredStatus,+            closedPauses: closedPauses.map { ClosedWire(start: $0.start.map(CivilDateCodec.spelling), end: CivilDateCodec.spelling($0.end)) },+            currentPause: currentPause.map { CurrentWire(start: $0.start.map(CivilDateCodec.spelling), returnDate: $0.returnDate.map(CivilDateCodec.spelling)) })+            .encode(to: encoder)+    }++    public func canonicalData() throws -> Data {+        let encoder = JSONEncoder()+        encoder.outputFormatting = .canonical+        return try encoder.encode(self)+    }++    public static func decode(_ data: Data) throws -> Self { try JSONDecoder().decode(Self.self, from: data) }+}++extension Work {+    /// Nil alone is legacy. A present envelope that cannot decode is a data error.+    public func decodedPublicationState() throws -> WorkPublicationState? {+        try publicationStateData.map(WorkPublicationState.decode)+    }++    public func effectiveWorkStatus(on day: CivilDay) throws -> WorkStatus {+        try decodedPublicationState()?.status(on: day) ?? workStatus+    }+}
Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swift b/Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swiftnew file mode 100644index 00000000..93b4f247--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swift@@ -0,0 +1,57 @@+import Foundation++/// An explicit authored edit; unrelated metadata saves retain the stored value.+public enum WorkPublicationEdit: Equatable, Sendable {+    case unchanged+    case set(status: WorkStatus, returnDate: CivilDay?)+}++/// Prepares publication changes. The repository stages and saves them with metadata.+internal enum WorkPublicationWriter {+    struct Change {+        let state: WorkPublicationState?+        let authoredStatus: WorkStatus+        let didEdit: Bool+        let rebasesStatus: Bool+    }++    static func prepare(state: WorkPublicationState?, legacyStatus: WorkStatus,+                        edit: WorkPublicationEdit, today: CivilDay) throws -> Change {+        let oldStatus = state?.status(on: today) ?? legacyStatus+        guard case .set(let status, let returnDate) = edit else {+            return Change(state: state, authoredStatus: state?.authoredStatus ?? legacyStatus,+                          didEdit: false, rebasesStatus: false)+        }+        if let returnDate {+            guard status == .hiatus, returnDate >= today else {+                throw LibraryRepositoryError.invalidInput(+                    operation: "updating Work", reason: "Choose today or a later hiatus return date")+            }+        }+        var closed = state?.closedPauses ?? []+        var pause = state?.currentPause+        if state == nil, legacyStatus == .hiatus {+            pause = .init(start: nil)+        }+        func close(_ pause: WorkPublicationState.CurrentPause, at end: CivilDay) {+            if pause.start == nil || pause.start! < end {+                closed.append(.init(start: pause.start, end: end))+            }+        }+        // Materialize an elapsed return at its announced boundary, never at launch.+        if let current = pause, let end = current.returnDate, end <= today {+            close(current, at: end)+            pause = nil+        }+        if status == .hiatus {+            let start = oldStatus == .hiatus ? pause?.start : today+            pause = .init(start: start, returnDate: returnDate)+        } else {+            if let current = pause { close(current, at: today) }+            pause = nil+        }+        let updated = try WorkPublicationState(status: status, closedPauses: closed, currentPause: pause)+        return Change(state: updated, authoredStatus: updated.authoredStatus, didEdit: true,+                      rebasesStatus: (oldStatus == .finished) != (updated.authoredStatus == .finished))+    }+}
Packages/AsterismCore/Sources/AsterismCore/WorkVariantUnion.swift Modified
diff --git a/Packages/AsterismCore/Sources/AsterismCore/WorkVariantUnion.swift b/Packages/AsterismCore/Sources/AsterismCore/WorkVariantUnion.swiftindex 6c81309c..3c1c09f5 100644--- a/Packages/AsterismCore/Sources/AsterismCore/WorkVariantUnion.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/WorkVariantUnion.swift@@ -28,6 +28,7 @@ public struct WorkVariantSide: Sendable, Equatable {     public let typeDisplay: WorkTypeDisplay     /// V10: carried like the type — the fold keeps the chosen side's statuses     /// and reports what the others held (Q13, Req 7.3).+    public let publicationState: WorkPublicationState?     public let workStatus: WorkStatus     public let readingStatus: ReadingStatus     /// Reader text, so unlike the statuses a losing one is *recorded* rather@@ -65,8 +66,10 @@ public struct WorkVariantSide: Sendable, Equatable {         // **Required** for the membership's reason: an omitted set is a         // schedule dropped from the preview, so the reader approves a merge         // without being told a source's days are going (Req 7.3).-        releaseDays: [ReleaseDay]+        releaseDays: [ReleaseDay],+        publicationState: WorkPublicationState? = nil     ) {+        self.publicationState = publicationState         self.releaseDays = ReleaseDay.canonical(releaseDays)         self.membership = membership         self.displayTitle = displayTitle@@ -75,7 +78,7 @@ public struct WorkVariantSide: Sendable, Equatable {         self.genericNotes = genericNotes         self.genreTags = genreTags         self.typeDisplay = typeDisplay-        self.workStatus = workStatus+        self.workStatus = publicationState?.authoredStatus ?? workStatus         self.readingStatus = readingStatus         self.verdict = verdict     }@@ -95,14 +98,15 @@ public struct WorkVariantSide: Sendable, Equatable {         readingStatus: ReadingStatus,         verdict: String,         membership: SeriesMembership?,-        releaseDays: [ReleaseDay]+        releaseDays: [ReleaseDay],+        publicationState: WorkPublicationState? = nil     ) {         self.init(             displayTitle: displayTitle, titleProvenance: titleProvenance,             workURLsByHostname: workURLString.map { [hostname: $0] } ?? [:],             genericNotes: genericNotes, genreTags: genreTags, typeDisplay: typeDisplay,             workStatus: workStatus, readingStatus: readingStatus, verdict: verdict,-            membership: membership, releaseDays: releaseDays)+            membership: membership, releaseDays: releaseDays, publicationState: publicationState)     }      public init(snapshot: WorkSnapshot) {@@ -115,9 +119,9 @@ public struct WorkVariantSide: Sendable, Equatable {             displayTitle: snapshot.displayTitle, titleProvenance: snapshot.titleProvenance,             workURLsByHostname: urls, genericNotes: snapshot.genericNotes,             genreTags: snapshot.genreTags, typeDisplay: snapshot.typeDisplay,-            workStatus: snapshot.workStatus, readingStatus: snapshot.readingStatus,+            workStatus: snapshot.authoredWorkStatus, readingStatus: snapshot.readingStatus,             verdict: snapshot.verdict, membership: snapshot.membership,-            releaseDays: snapshot.releaseDays)+            releaseDays: snapshot.releaseDays, publicationState: snapshot.publicationState)     } } @@ -194,6 +198,7 @@ public enum WorkVariantUnion {             .targetWorkStatus, .targetReadingStatus, .targetVerdict,             .targetReleaseDays,         ]+        if chosen.publicationState != nil { retained.append(.targetPublicationState) }         var discarded: [WorkMergeField] = []         var workURLs = chosen.workURLsByHostname         var droppedURLs: [String: String] = [:]@@ -271,6 +276,9 @@ public enum WorkVariantUnion {             if titleDiscarded { discarded.append(.sourceManualTitle) }             if notesRetained { discarded.append(.sourceNotes) }             if workStatusDiscarded { discarded.append(.sourceWorkStatus) }+            if other.publicationState != nil, other.publicationState != chosen.publicationState {+                discarded.append(.sourcePublicationState)+            }             if readingStatusDiscarded { discarded.append(.sourceReadingStatus) }             if verdictRecorded { discarded.append(.sourceVerdict) }             if releaseDaysDiscarded { discarded.append(.sourceReleaseDays) }
Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swiftindex 317b100d..ec097826 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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)         let result = try await exporter.export(-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date()))+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: Date())) -        let decoded = try BackupV17Codec.decode(try Data(contentsOf: result.fileURL))+        let decoded = try BackupV18Codec.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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)          let error = try await expectRefusal {             _ = try await exporter.export(-                metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date()))+                metadata: BackupV18Metadata(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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)          let error = try await expectRefusal {             _ = try await exporter.export(-                metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date()))+                metadata: BackupV18Metadata(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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)          let error = try await expectRefusal {             _ = try await exporter.export(-                metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date()))+                metadata: BackupV18Metadata(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: BackupV17ExportError.self,+                throws: BackupV18ExportError.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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)         let error = try await expectRefusal {             _ = try await exporter.export(-                metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date()))+                metadata: BackupV18Metadata(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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)          let error = try await expectRefusal {             _ = try await exporter.export(-                metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date()))+                metadata: BackupV18Metadata(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.backupV17Snapshot() }+        let error = try await expectRefusal { _ = try await repository.backupV18Snapshot() }          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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)          let error = try await expectRefusal {             _ = try await exporter.export(-                metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date()))+                metadata: BackupV18Metadata(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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()         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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()         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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)         let result = try await exporter.export(-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: Date()))+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: Date())) -        let decoded = try BackupV17Codec.decode(try Data(contentsOf: result.fileURL))-        #expect(decoded.backupFormatVersion == 17)-        #expect(decoded.databaseSchemaVersion == 18)+        let decoded = try BackupV18Codec.decode(try Data(contentsOf: result.fileURL))+        #expect(decoded.backupFormatVersion == 18)+        #expect(decoded.databaseSchemaVersion == 19)         #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 -> BackupV17ExportError {+    ) async throws -> BackupV18ExportError {         do {             try await body()             Issue.record("expected a named refusal, but the export proceeded")             return .snapshotFailed(reason: "no refusal")-        } catch let error as BackupV17ExportError {+        } catch let error as BackupV18ExportError {             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: BackupV17Payload) throws -> ModelContext {-        let encoded = try BackupV17Codec.encode(+    private static func importIntoEmptyStore(_ payload: BackupV18Payload) throws -> ModelContext {+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch))-        let decoded = try BackupV17Codec.decode(encoded)+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch))+        let decoded = try BackupV18Codec.decode(encoded) -        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)         let container = try ModelContainer(for: schema, configurations: [configuration])
Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swiftindex a260ea8a..f1ea143e 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGoldenExportTests.swift@@ -4,7 +4,7 @@ import Testing  @testable import AsterismCore -/// The byte-for-byte pin on the deterministic 17/18 payload.+/// The byte-for-byte pin on the deterministic 18/19 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@@ -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 17/18 golden export", .serialized)+@Suite("Backup 18/19 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-17-18-golden.json")+            .appending(path: "Fixtures/backup-18-19-golden.json")     } -    /// Every array the 17/18 payload declares is non-empty, so the golden below is+    /// Every array the 18/19 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")@@ -97,6 +97,8 @@ struct BackupGoldenExportTests {         // that tells a 16/17 record apart from a pre-feature one (Q22).         #expect(payload.works.contains { $0.releaseDays == [.monday, .thursday] })         #expect(payload.works.contains { $0.releaseDays.isEmpty })+        #expect(payload.works.contains { $0.publicationState?.currentPause?.returnDate != nil })+        #expect(payload.works.contains { $0.publicationState == nil })         #expect(payload.works.contains {             $0.latestReleasedChapter == 52 && $0.latestConfirmedAt != nil                 && !$0.countsUpOnReleaseDays && $0.latestIsEstimate@@ -191,13 +193,13 @@ struct BackupGoldenExportTests {                 == 1)     } -    @Test("The literal 17/18 payload is byte-identical to the recorded archive")+    @Test("The literal 18/19 payload is byte-identical to the recorded archive")     func exportIsByteIdenticalToTheRecordedArchive() async throws {         // 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(+        let encoded = try BackupV18Codec.encode(             payload: payload, metadata: BackupGoldenLibrary.metadata)          // Q22: every generation bump used to re-record the golden by hand from@@ -219,7 +221,7 @@ struct BackupGoldenExportTests {         #expect(             encoded == golden,             """-            the 17/18 literal payload no longer produces the recorded \+            the 18/19 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) \@@ -234,8 +236,8 @@ struct BackupGoldenExportTests {         let golden = try Data(contentsOf: Self.goldenURL)         let plan = try BackupImporter.plan(from: golden) -        #expect(plan.metadata.formatVersion == 17)-        #expect(plan.metadata.schemaVersion == 18)+        #expect(plan.metadata.formatVersion == 18)+        #expect(plan.metadata.schemaVersion == 19)         #expect(plan.counts.entries == plan.metadata.entryCount)         #expect(plan.counts.works == plan.metadata.workCount)     }@@ -261,14 +263,14 @@ struct BackupGoldenExportTests {     @Test("An export restored into an empty library retains every record and adds note clears")     func exportImportExportIsByteIdentical() async throws {         let source = try await Self.exportedPayload()-        let first = try BackupV17Codec.encode(+        let first = try BackupV18Codec.encode(             payload: source, metadata: BackupGoldenLibrary.metadata)          let target = try await M5Fixture()         try await target.repository.confirmImport(plan: try BackupImporter.plan(from: first))-        let restored = try await target.repository.backupV17Snapshot()+        let restored = try await target.repository.backupV18Snapshot() -        try BackupV17RestoreAssertions.expectExactRecordsAndFreshNoteClears(+        try BackupV18RestoreAssertions.expectExactRecordsAndFreshNoteClears(             before: source, after: restored)         #expect(try await target.repository.strictDiagnoses().isEmpty)     }@@ -278,7 +280,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 BackupV17Codec.encode(+        let archive = try BackupV18Codec.encode(             payload: try await Self.exportedPayload(), metadata: BackupGoldenLibrary.metadata)          let target = try await M5Fixture()@@ -295,17 +297,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 -> BackupV17Payload {+    private static func exportedPayload() async throws -> BackupV18Payload {         let fixture = try await M5Fixture()         let plan = try BackupImporter.plan(-            from: try BackupV17Codec.encode(+            from: try BackupV18Codec.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.backupV17Snapshot()+        return try await fixture.repository.backupV18Snapshot()     } } @@ -444,14 +446,14 @@ enum BackupGoldenLibrary {     static let secondSiteWorkURL = "https://plain.example/works/actual-title"     static let trimmedTitleSuffix = " - Trimmed Example" -    static var metadata: BackupV17Metadata {-        BackupV17Metadata(appBuild: "golden", exportedAt: created)+    static var metadata: BackupV18Metadata {+        BackupV18Metadata(appBuild: "golden", exportedAt: created)     }      // MARK: The archive -    static var payload: BackupV17Payload {-        BackupV17Payload(+    static var payload: BackupV18Payload {+        BackupV18Payload(             entries: [notedEntry, plainEntry, trimmedEntry],             works: [typedWork, foldedWork, legacyWork],             sites: [taughtSite, plainSite, trimmedSite],@@ -479,7 +481,7 @@ enum BackupGoldenLibrary {             noEpisodeActions: noEpisodeActions)     } -    static var noEpisodeActions: [BackupV17NoEpisodeAction] {+    static var noEpisodeActions: [BackupV18NoEpisodeAction] {         let clearKey = "clear/10000000-0000-4000-8000-000000000001"         let mark = try! NoEpisodeHistory.Action(             workID: typedWork.id,@@ -493,7 +495,7 @@ enum BackupGoldenLibrary {             workID: absentWorkID,             key: "mark/10000000-0000-4000-8000-000000000003",             day: "2026-09-30", kind: .mark, observedClearKeys: [])-        return [mark, clear, orphan].map { try! BackupV17NoEpisodeAction($0) }+        return [mark, clear, orphan].map { try! BackupV18NoEpisodeAction($0) }     }      // MARK: The creators, roles and credits@@ -501,7 +503,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: [BackupV17Creator] {+    private static var creators: [BackupV18Creator] {         [             creator(id: creatorID, name: "Mori Ayane", notes: "Also draws."),             creator(id: studioID, name: "Studio Lantern"),@@ -515,7 +517,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: [BackupV17CreatorRole] {+    private static var creatorRoles: [BackupV18CreatorRole] {         CreatorRoleSeeding.seeds.map {             role(                 id: $0.id, name: $0.name, position: $0.position,@@ -530,7 +532,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: [BackupV17Credit] {+    private static var credits: [BackupV18Credit] {         [             credit(                 id: authorCreditID, workID: typedWorkID, creatorID: creatorID,@@ -547,8 +549,8 @@ enum BackupGoldenLibrary {     private static func creator(         id: UUID, name: String, notes: String = "", state: CreatorState = .active,         canonicalID: UUID? = nil-    ) -> BackupV17Creator {-        BackupV17Creator(+    ) -> BackupV18Creator {+        BackupV18Creator(             id: id, name: name, nameModifiedAt: created, notes: notes,             notesModifiedAt: created, stateRaw: state.rawValue, stateModifiedAt: created,             canonicalID: canonicalID, createdAt: created, modifiedAt: created)@@ -557,8 +559,8 @@ enum BackupGoldenLibrary {     private static func role(         id: UUID, name: String, position: Int, state: CreatorRoleState = .active,         stamp: Date = created-    ) -> BackupV17CreatorRole {-        BackupV17CreatorRole(+    ) -> BackupV18CreatorRole {+        BackupV18CreatorRole(             id: id, name: name, nameModifiedAt: stamp, position: position,             positionModifiedAt: stamp, stateRaw: state.rawValue, stateModifiedAt: stamp,             canonicalID: nil, createdAt: stamp, modifiedAt: stamp)@@ -566,40 +568,40 @@ enum BackupGoldenLibrary {      private static func credit(         id: UUID, workID: UUID, creatorID: UUID, roleIDs: [UUID]-    ) -> BackupV17Credit {-        BackupV17Credit(+    ) -> BackupV18Credit {+        BackupV18Credit(             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: BackupV17Series {-        BackupV17Series(+    private static var series: BackupV18Series {+        BackupV18Series(             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: BackupV17Link {+    private static var resolvedLink: BackupV18Link {         let ids = WorkDistinctPair.sortedIDs(typedWorkID, legacyWorkID)-        return BackupV17Link(+        return BackupV18Link(             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: BackupV17Link {+    private static var unresolvedLink: BackupV18Link {         let ids = WorkDistinctPair.sortedIDs(foldedWorkID, absentWorkID)-        return BackupV17Link(+        return BackupV18Link(             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: BackupV17TitlePattern {-        BackupV17TitlePattern(+    private static var pattern: BackupV18TitlePattern {+        BackupV18TitlePattern(             id: patternID, siteHostname: taughtHost, version: 1, isActive: true,             createdAt: created,             definition: StoredPatternDefinition(@@ -607,8 +609,8 @@ enum BackupGoldenLibrary {     }      /// The second taught site's active rule, and the fixture's only `trimSuffix`.-    private static var trimmedPattern: BackupV17TitlePattern {-        BackupV17TitlePattern(+    private static var trimmedPattern: BackupV18TitlePattern {+        BackupV18TitlePattern(             id: trimmedPatternID, siteHostname: trimmedHost, version: 1, isActive: true,             createdAt: created,             definition: StoredPatternDefinition(@@ -616,35 +618,35 @@ enum BackupGoldenLibrary {     }      /// A sequence-only query rule extracts "94" from the raw URL.-    private static var rule: BackupV17URLRule {-        BackupV17URLRule(+    private static var rule: BackupV18URLRule {+        BackupV18URLRule(             id: ruleID, version: 1, isCurrent: true, createdAt: created,             origin: .readerTaught,             definition: .sequence(locator: .query(name: ExactScalarString("chapter"))),             siteHostname: taughtHost)     } -    private static var taughtSite: BackupV17Site {-        BackupV17Site(+    private static var taughtSite: BackupV18Site {+        BackupV18Site(             hostname: taughtHost, displayName: "Golden", mode: .taught)     } -    private static var plainSite: BackupV17Site {-        BackupV17Site(+    private static var plainSite: BackupV18Site {+        BackupV18Site(             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: BackupV17Site {-        BackupV17Site(+    private static var trimmedSite: BackupV18Site {+        BackupV18Site(             hostname: trimmedHost, displayName: "Trimmed", mode: .taught)     }      private static func workType(         id: UUID, name: String, state: WorkTypeState = .active, canonicalID: UUID? = nil-    ) -> BackupV17WorkType {-        BackupV17WorkType(+    ) -> BackupV18WorkType {+        BackupV18WorkType(             id: id, name: name, stateRaw: state.rawValue, canonicalID: canonicalID,             createdAt: created, modifiedAt: created)     }@@ -653,8 +655,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: BackupV17Membership {-        BackupV17Membership(+    private static var taughtMembership: BackupV18Membership {+        BackupV18Membership(             id: taughtMembershipID, workID: typedWorkID, hostname: taughtHost,             createdAt: created, urlIdentity: workIdentity, urlIdentityState: .rule,             urlIdentityRuleID: ruleID, workURLString: workURL)@@ -663,22 +665,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: BackupV17Membership {-        BackupV17Membership(+    private static var secondSiteMembership: BackupV18Membership {+        BackupV18Membership(             id: secondSiteMembershipID, workID: typedWorkID, hostname: plainHost,             createdAt: created.addingTimeInterval(1), urlIdentity: nil,             urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: secondSiteWorkURL)     } -    private static var plainMembership: BackupV17Membership {-        BackupV17Membership(+    private static var plainMembership: BackupV18Membership {+        BackupV18Membership(             id: plainMembershipID, workID: foldedWorkID, hostname: plainHost,             createdAt: created, urlIdentity: nil, urlIdentityState: .none,             urlIdentityRuleID: nil, workURLString: nil)     } -    private static var trimmedMembership: BackupV17Membership {-        BackupV17Membership(+    private static var trimmedMembership: BackupV18Membership {+        BackupV18Membership(             id: trimmedMembershipID, workID: legacyWorkID, hostname: trimmedHost,             createdAt: created, urlIdentity: nil, urlIdentityState: .none,             urlIdentityRuleID: nil, workURLString: nil)@@ -686,17 +688,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: BackupV17Membership {-        BackupV17Membership(+    private static var orphanMembership: BackupV18Membership {+        BackupV18Membership(             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: BackupV17DistinctPair {+    private static var distinctPair: BackupV18DistinctPair {         let ids = WorkDistinctPair.sortedIDs(typedWorkID, foldedWorkID)-        return BackupV17DistinctPair(+        return BackupV18DistinctPair(             id: distinctPairID, lowerWorkID: ids.lower, higherWorkID: ids.higher,             recordedAt: created)     }@@ -709,8 +711,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: BackupV17Work {-        BackupV17Work(+    private static var typedWork: BackupV18Work {+        BackupV18Work(             id: typedWorkID, displayTitle: workName, lastParsedTitle: workName,             genericNotes: genericNotes, genreTags: ["fantasy"], titleProvenance: .parsed,             workStatus: .hiatus, readingStatus: .abandoned,@@ -733,13 +735,18 @@ enum BackupGoldenLibrary {             latestConfirmedAt: created.addingTimeInterval(12),             countsUpOnReleaseDays: false,             latestIsEstimate: true,-            lastChapterOverrideAt: created.addingTimeInterval(14))+            lastChapterOverrideAt: created.addingTimeInterval(14),+            publicationState: try! WorkPublicationState(+                status: .hiatus,+                closedPauses: [.init(start: nil, end: CivilDateCodec.parse("2026-08-10")!)],+                currentPause: .init(start: CivilDateCodec.parse("2026-09-01")!,+                                    returnDate: CivilDateCodec.parse("2026-09-10")!)))     }      /// 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: BackupV17Work {-        BackupV17Work(+    private static var foldedWork: BackupV18Work {+        BackupV18Work(             id: foldedWorkID, displayTitle: "Plain Work", lastParsedTitle: nil,             genericNotes: "", genreTags: [], titleProvenance: .manual,             workStatus: .finished, readingStatus: .finished, verdict: "",@@ -752,8 +759,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: BackupV17Work {-        BackupV17Work(+    private static var legacyWork: BackupV18Work {+        BackupV18Work(             id: legacyWorkID, displayTitle: "A Standalone", lastParsedTitle: nil,             genericNotes: "", genreTags: [], titleProvenance: .manual,             workStatus: .ongoing, readingStatus: .reading, verdict: "",@@ -769,14 +776,14 @@ enum BackupGoldenLibrary {     // MARK: The entries      /// The v3 key embeds host + resolved Work name + sequence.-    private static var notedEntry: BackupV17Entry {+    private static var notedEntry: BackupV18Entry {         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 BackupV17Entry(+        return BackupV18Entry(             id: notedEntryID, captureTitle: titlePrefix + workName, captureTitleSource: .host,             rawURL: rawURL, canonicalURL: nil, hostname: taughtHost,             entryIdentityKey: key, conservativeIdentityKey: rawURL,@@ -795,9 +802,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: BackupV17Entry {+    private static var plainEntry: BackupV18Entry {         let rawURL = "https://\(plainHost)/read/7"-        return BackupV17Entry(+        return BackupV18Entry(             id: plainEntryID, captureTitle: "Plain Work", captureTitleSource: .manual,             rawURL: rawURL, canonicalURL: nil, hostname: plainHost,             entryIdentityKey: rawURL, conservativeIdentityKey: rawURL,@@ -812,9 +819,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: BackupV17Entry {+    private static var trimmedEntry: BackupV18Entry {         let rawURL = "https://\(trimmedHost)/posts/hello?utm_source=share"-        return BackupV17Entry(+        return BackupV18Entry(             id: trimmedEntryID, captureTitle: "A Standalone" + trimmedTitleSuffix,             captureTitleSource: .host,             rawURL: rawURL, canonicalURL: "https://\(trimmedHost)/posts/hello",@@ -829,8 +836,8 @@ enum BackupGoldenLibrary {      // MARK: The characters -    private static var guide: BackupV17Character {-        BackupV17Character(+    private static var guide: BackupV18Character {+        BackupV18Character(             id: guideID, workID: typedWorkID, name: "Grover", nameKey: "grover",             aliases: ["Klar"], note: "The guide.",             facts: [@@ -843,14 +850,14 @@ enum BackupGoldenLibrary {     }      /// The sync orphan: a character whose work has not arrived.-    private static var orphan: BackupV17Character {-        BackupV17Character(+    private static var orphan: BackupV18Character {+        BackupV18Character(             id: orphanID, workID: nil, name: "The Stranger", nameKey: "the stranger",             aliases: [], note: "", facts: [], createdAt: created, modifiedAt: created)     } -    private static var candidateSuppression: BackupV17Suppression {-        BackupV17Suppression(+    private static var candidateSuppression: BackupV18Suppression {+        BackupV18Suppression(             id: candidateSuppressionID, workID: typedWorkID,             kindRaw: CharacterSuppressionKind.candidate.rawValue, nameKey: "the crowned one",             sourceKindRaw: nil, sourceEntryID: nil, evidence: nil,@@ -858,8 +865,8 @@ enum BackupGoldenLibrary {     }      /// A fact suppression, which is the shape that carries a source and evidence.-    private static var factSuppression: BackupV17Suppression {-        BackupV17Suppression(+    private static var factSuppression: BackupV18Suppression {+        BackupV18Suppression(             id: factSuppressionID, workID: typedWorkID,             kindRaw: CharacterSuppressionKind.fact.rawValue, nameKey: "grover",             sourceKindRaw: SourceRef.entry(notedEntryID).kindRaw, sourceEntryID: notedEntryID,@@ -871,8 +878,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: BackupV17Place {-        BackupV17Place(+    private static var keep: BackupV18Place {+        BackupV18Place(             id: keepID, workID: typedWorkID, name: "The High Keep",             nameKey: "high keep", aliases: ["The Keep"],             note: "The fortress above the pass.",@@ -887,15 +894,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: BackupV17Place {-        BackupV17Place(+    private static var orphanPlace: BackupV18Place {+        BackupV18Place(             id: orphanPlaceID, workID: absentWorkID, name: "The Drowned Road",             nameKey: "drowned road", aliases: [], note: "", facts: [],             createdAt: created, modifiedAt: created)     } -    private static var placeCandidateSuppression: BackupV17PlaceSuppression {-        BackupV17PlaceSuppression(+    private static var placeCandidateSuppression: BackupV18PlaceSuppression {+        BackupV18PlaceSuppression(             id: placeCandidateSuppressionID, workID: typedWorkID,             kindRaw: CharacterSuppressionKind.candidate.rawValue, nameKey: "low road",             sourceKindRaw: nil, sourceEntryID: nil, evidence: nil,@@ -904,8 +911,8 @@ enum BackupGoldenLibrary {      /// The place fact suppression, which is the shape that carries a source and     /// evidence.-    private static var placeFactSuppression: BackupV17PlaceSuppression {-        BackupV17PlaceSuppression(+    private static var placeFactSuppression: BackupV18PlaceSuppression {+        BackupV18PlaceSuppression(             id: placeFactSuppressionID, workID: typedWorkID,             kindRaw: CharacterSuppressionKind.fact.rawValue, nameKey: "high keep",             sourceKindRaw: SourceRef.entry(notedEntryID).kindRaw, sourceEntryID: notedEntryID,
Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupProjectionTests.swiftindex 2313d8dd..229c1875 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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }-        let encoded = try BackupV17Codec.encode(+        let payload = try store.read { try LibraryRepository.projectV18Payload(context: $0) }+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+            metadata: BackupV18Metadata(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 BackupV17Codec.decode(encoded)+        let decoded = try BackupV18Codec.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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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 BackupV17Codec.encode(+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))-        _ = try BackupV17Codec.decode(encoded)+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+        _ = try BackupV18Codec.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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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 BackupV17Codec.encode(+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))-        _ = try BackupV17Codec.decode(encoded)+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+        _ = try BackupV18Codec.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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }+            _ = try store.read { try LibraryRepository.projectV18Payload(context: $0) }         }          #expect(payload.count == 1)@@ -268,7 +268,7 @@ struct BackupGroupProjectionTests {         try store.commit()          let payload = try expectTornRefusal {-            _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) }+            _ = try store.read { try LibraryRepository.projectV18Payload(context: $0) }         }          #expect(payload.count == 2)@@ -288,7 +288,7 @@ struct BackupGroupProjectionTests {         try store.commit()          let payload = try expectTornRefusal {-            _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) }+            _ = try store.read { try LibraryRepository.projectV18Payload(context: $0) }         }          #expect(payload.count == 1)@@ -321,7 +321,7 @@ struct BackupGroupProjectionTests {         try store.commit()          let payload = try expectTornRefusal {-            _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) }+            _ = try store.read { try LibraryRepository.projectV18Payload(context: $0) }         }          #expect(payload.count == 1)@@ -357,7 +357,7 @@ struct BackupGroupProjectionTests {         try store.commit()          let payload = try expectTornRefusal {-            _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) }+            _ = try store.read { try LibraryRepository.projectV18Payload(context: $0) }         }          #expect(payload.count == 2)@@ -393,7 +393,7 @@ struct BackupGroupProjectionTests {         try store.commit()          let payload = try expectTornRefusal {-            _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) }+            _ = try store.read { try LibraryRepository.projectV18Payload(context: $0) }         }          #expect(payload.count == 2)@@ -414,7 +414,7 @@ struct BackupGroupProjectionTests {         try store.commit()          _ = try expectTornRefusal {-            _ = try store.read { try LibraryRepository.projectV17Payload(context: $0) }+            _ = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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 BackupV17Codec.encode(+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))-        _ = try BackupV17Codec.decode(encoded)+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+        _ = try BackupV18Codec.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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(context: $0) }          #expect(payload.titlePatterns.count == 1)         #expect(payload.titlePatterns.first?.isActive == true)-        let encoded = try BackupV17Codec.encode(+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))-        _ = try BackupV17Codec.decode(encoded)+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: DuplicateStore.epoch))+        _ = try BackupV18Codec.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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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.projectV17Payload(context: $0) }+        let payload = try store.read { try LibraryRepository.projectV18Payload(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 BackupV17ExportError {+        } catch let error as BackupV18ExportError {             guard case .tornGroups(let payload) = error else {                 Issue.record("expected .tornGroups, got \(error)")                 return TornGroupsPayload(count: 0, blockingWorkSet: nil)
Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupGroupRoundTripTests.swiftindex d055b316..bfc7a991 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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()         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.backupV17Snapshot()+        let payload = try await sourceRepository.backupV18Snapshot()          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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()         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.backupV17Snapshot()+        let payload = try await sourceRepository.backupV18Snapshot()          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.backupV17Snapshot()+        let exported = try await sourceRepository.backupV18Snapshot()          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: BackupV17Fixtures.entryID)+        let citations = try await targetRepository.citations(entryID: BackupV18Fixtures.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.     ///-    /// `BackupV17ArchiveTests` stops at a decode, which only proves the reference+    /// `BackupV18ArchiveTests` 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 = BackupV17Fixtures.duplicateVersionsPayload()+        let payload = BackupV18Fixtures.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: BackupV17Payload) -> [RuleRowFacts] {+    private static func expectedPatternRows(_ payload: BackupV18Payload) -> [RuleRowFacts] {         payload.titlePatterns             .map {                 RuleRowFacts(@@ -221,7 +221,7 @@ struct BackupGroupRoundTripTests {             .sorted { $0.id.uuidString < $1.id.uuidString }     } -    private static func expectedURLRuleRows(_ payload: BackupV17Payload) -> [RuleRowFacts] {+    private static func expectedURLRuleRows(_ payload: BackupV18Payload) -> [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() -> BackupV17Payload {-        let base = BackupV17Fixtures.composedPayload()+    private static func versionSpreadPayload() -> BackupV18Payload {+        let base = BackupV18Fixtures.composedPayload()         let host = "example.com"-        let retired = BackupV17Fixtures.created.addingTimeInterval(-60)+        let retired = BackupV18Fixtures.created.addingTimeInterval(-60) -        let retiredPattern = BackupV17TitlePattern(+        let retiredPattern = BackupV18TitlePattern(             id: UUID(uuidString: "cccccccc-cccc-cccc-cccc-ccccccccccc9")!,             siteHostname: host, version: 9, isActive: false, createdAt: retired,             definition: StoredPatternDefinition(definition: .wholeTitle))-        let retiredRule = BackupV17URLRule(+        let retiredRule = BackupV18URLRule(             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 BackupV17Payload(+        return BackupV18Payload(             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: BackupV17Payload) -> BackupImportPlan {+    static func plan(_ payload: BackupV18Payload) -> BackupImportPlan {         BackupImportPlan(             metadata: BackupImportMetadata(                 formatVersion: 8, schemaVersion: 9, appBuild: "test-1.0",
Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swiftindex 4fc4d916..2616055a 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: AsterismSchemaV18.self)+    let schema = Schema(versionedSchema: AsterismSchemaV19.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: AsterismV18MigrationPlan.self,+        migrationPlan: AsterismV19MigrationPlan.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: AsterismSchemaV18.self)+    let schema = Schema(versionedSchema: AsterismSchemaV19.self)     let storeConfig = ModelConfiguration(         "AsterismV3",         schema: schema,@@ -715,7 +715,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration)     )     let container = try ModelContainer(         for: schema,-        migrationPlan: AsterismV18MigrationPlan.self,+        migrationPlan: AsterismV19MigrationPlan.self,         configurations: [storeConfig]     )     let context = ModelContext(container)@@ -758,7 +758,7 @@ private func createReadySiteStore(         at: configuration.storeURL.deletingLastPathComponent(),         withIntermediateDirectories: true     )-    let schema = Schema(versionedSchema: AsterismSchemaV18.self)+    let schema = Schema(versionedSchema: AsterismSchemaV19.self)     let storeConfig = ModelConfiguration(         "AsterismV3",         schema: schema,@@ -767,7 +767,7 @@ private func createReadySiteStore(     )     let container = try ModelContainer(         for: schema,-        migrationPlan: AsterismV18MigrationPlan.self,+        migrationPlan: AsterismV19MigrationPlan.self,         configurations: [storeConfig]     )     let context = ModelContext(container)@@ -802,7 +802,7 @@ private func createReadyDuplicateSiteStore(         at: configuration.storeURL.deletingLastPathComponent(),         withIntermediateDirectories: true     )-    let schema = Schema(versionedSchema: AsterismSchemaV18.self)+    let schema = Schema(versionedSchema: AsterismSchemaV19.self)     let storeConfig = ModelConfiguration(         "AsterismV3",         schema: schema,@@ -811,7 +811,7 @@ private func createReadyDuplicateSiteStore(     )     let container = try ModelContainer(         for: schema,-        migrationPlan: AsterismV18MigrationPlan.self,+        migrationPlan: AsterismV19MigrationPlan.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 = BackupV17Site(+    let site = BackupV18Site(         hostname: hostname, displayName: displayName ?? hostname,         mode: mode)-    let patterns: [BackupV17TitlePattern] = activePattern+    let patterns: [BackupV18TitlePattern] = activePattern         ? [-            BackupV17TitlePattern(+            BackupV18TitlePattern(                 // 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 = BackupV17Site(+    let site = BackupV18Site(         hostname: hostname, displayName: hostname, mode: .untaught)-    let entries = (0..<entryCount).map { index -> BackupV17Entry in+    let entries = (0..<entryCount).map { index -> BackupV18Entry in         let rawURL = "https://\(hostname)/read?chapter=\(index)"-        return BackupV17Entry(+        return BackupV18Entry(             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 = BackupV17Entry(+    let entry = BackupV18Entry(         id: entryID,         captureTitle: "Imported Chapter",         captureTitleSource: .networkFetch,@@ -960,7 +960,7 @@ private func makeMinimalImportPlan(             workAssignment: .pattern(CitedRule(id: patternID)))     ) -    let work = BackupV17Work(+    let work = BackupV18Work(         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 = BackupV17Membership(+    let membership = BackupV18Membership(         // 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 = BackupV17TitlePattern(+    let pattern = BackupV18TitlePattern(         id: patternID,         siteHostname: siteHostname,         version: 1,@@ -1005,8 +1005,8 @@ private func makeMinimalImportPlan(                 ignored: []))     ) -    let urlRules: [BackupV17URLRule] = includeURLRule ? [-        BackupV17URLRule(+    let urlRules: [BackupV18URLRule] = includeURLRule ? [+        BackupV18URLRule(             id: urlRuleID,             version: 1,             isCurrent: true,@@ -1022,7 +1022,7 @@ private func makeMinimalImportPlan(         )     ] : [] -    let site = BackupV17Site(+    let site = BackupV18Site(         hostname: siteHostname,         displayName: siteHostname,         mode: .taught
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swiftnew file mode 100644index 00000000..971a07d5--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.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 BackupV18CodecTests {++    @Test("V16 encode/decode round-trips 16/17, the multi-site gate, and the seventeen arrays")+    func roundTrip() throws {+        let payload = BackupV18Fixtures.payload()++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))++        #expect(decoded.backupFormatVersion == 18)+        #expect(decoded.databaseSchemaVersion == 19)+        #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+                == BackupV18Fixtures.noteFingerprint)+        #expect(+            decoded.payload.works.first?.genericNotesExtractionFingerprint+                == BackupV18Fixtures.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 = BackupV18Fixtures.composedPayload()++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))++        let record = try #require(+            decoded.payload.works.first { $0.id == BackupV18Fixtures.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 = [+            BackupV18Fixtures.fact(),+            BackupV18Fixtures.fact(+                statement: "Knows the way through the pass.",+                quote: "knows the way", source: .genericNotes),+        ]+        let payload = BackupV18Fixtures.payload(+            characters: [+                BackupV18Fixtures.character(aliases: ["Klar", "The Guide"], facts: facts)+            ])++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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(BackupV18Fixtures.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 = [+            BackupV18Fixtures.suppression(),+            BackupV18Fixtures.suppression(+                id: BackupV18Fixtures.factSuppressionID, kind: .fact, nameKey: "grover",+                source: .entry(BackupV18Fixtures.entryID), evidence: "promised to guide",+                status: .cleared),+        ]+        let payload = BackupV18Fixtures.payload(suppressions: rows)++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.payload(+            characters: [BackupV18Fixtures.character(id: BackupV18Fixtures.orphanID, workID: nil)])++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.payload(+            characters: [+                BackupV18Fixtures.character(facts: [BackupV18Fixtures.fact(source: .entry(absent))])+            ],+            suppressions: [+                BackupV18Fixtures.suppression(+                    id: BackupV18Fixtures.factSuppressionID, kind: .fact, nameKey: "grover",+                    source: .entry(absent), evidence: "gone")+            ])++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.payload(+            characters: [BackupV18Fixtures.character(workID: absent)])++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.payload(+            suppressions: [BackupV18Fixtures.suppression(workID: absent)])++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))+        }+    }++    // MARK: Payloads that contradict themselves++    @Test("Two records for one character identity refuse")+    func duplicateCharacterIDRefuses() throws {+        let payload = BackupV18Fixtures.payload(+            characters: [BackupV18Fixtures.character(), BackupV18Fixtures.character()])++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))+        }+    }++    @Test("Two records for one suppression identity refuse")+    func duplicateSuppressionIDRefuses() throws {+        let payload = BackupV18Fixtures.payload(+            suppressions: [BackupV18Fixtures.suppression(), BackupV18Fixtures.suppression()])++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = [+            BackupV18Fixtures.fact(+                statement: "Sits above the pass.", quote: "above the pass",+                nameKey: "high keep"),+            BackupV18Fixtures.fact(+                statement: "Was abandoned after the siege.", quote: "abandoned after the siege",+                nameKey: "high keep", source: .genericNotes),+        ]+        let payload = BackupV18Fixtures.payload(+            places: [BackupV18Fixtures.place(aliases: ["The Keep"], facts: facts)])++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))++        let place = try #require(decoded.payload.places.first)+        #expect(place.workID == BackupV18Fixtures.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(BackupV18Fixtures.entryID) })+    }++    @Test("Both place-suppression kinds round-trip with their status and action time")+    func placeSuppressionKindsRoundTrip() throws {+        let rows = [+            BackupV18Fixtures.placeSuppression(),+            BackupV18Fixtures.placeSuppression(+                id: BackupV18Fixtures.placeFactSuppressionID, kind: .fact,+                nameKey: "high keep", source: .entry(BackupV18Fixtures.entryID),+                evidence: "above the pass", status: .cleared),+        ]+        let payload = BackupV18Fixtures.payload(placeSuppressions: rows)++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.payload(+            places: [BackupV18Fixtures.place(id: BackupV18Fixtures.orphanPlaceID, workID: absent)],+            placeSuppressions: [BackupV18Fixtures.placeSuppression(workID: absent)])++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.payload(+            places: [BackupV18Fixtures.place(), BackupV18Fixtures.place()])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(+                    payload: duplicatePlaces, metadata: BackupV18Fixtures.metadata()))+        }++        let duplicateSuppressions = BackupV18Fixtures.payload(+            placeSuppressions: [+                BackupV18Fixtures.placeSuppression(), BackupV18Fixtures.placeSuppression(),+            ])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(+                    payload: duplicateSuppressions, metadata: BackupV18Fixtures.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(+            BackupV18Document.schemaVersion == AsterismSchemaV19.versionIdentifier.major,+            """+            the archive declares schema \(BackupV18Document.schemaVersion) but the store \+            is at V\(AsterismSchemaV19.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(+            BackupV18Document.formatVersion == BackupV18Document.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)++    /// `BackupV18Site.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.unknownSiteModePayloadJSON,+            entryCount: 1, workCount: 1)++        do {+            _ = try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.citationVersionFreePayloadJSON,+            entryCount: 1, workCount: 1)+        let site = try #require(try BackupV18Codec.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 = BackupV18Fixtures.composedPayload()++        // The premise: with the membership present the payload is legal.+        _ = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: base, metadata: BackupV18Fixtures.metadata()))++        let uncovered = BackupV18Payload(+            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 BackupV18Codec.decode(+                try BackupV18Codec.encode(+                    payload: uncovered, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.composedPayload()+        let twin = BackupV18Fixtures.membership(+            id: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee2")!,+            workID: BackupV18Fixtures.composedWorkID, hostname: "example.com")+        let payload = BackupV18Payload(+            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 BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.composedPayload()+        let orphan = BackupV18Fixtures.membership(+            id: UUID(uuidString: "0adbea00-0000-4000-8000-000000000001")!,+            workID: absent, hostname: "example.com")+        let ids = WorkDistinctPair.sortedIDs(absent, other)+        let payload = BackupV18Payload(+            entries: base.entries, works: base.works, sites: base.sites,+            titlePatterns: base.titlePatterns, urlRules: base.urlRules,+            workTypes: base.workTypes, memberships: base.memberships + [orphan],+            distinctPairs: [+                BackupV18DistinctPair(+                    id: UUID(uuidString: "0adbea00-0000-4000-8000-000000000002")!,+                    lowerWorkID: ids.lower, higherWorkID: ids.higher,+                    recordedAt: BackupV18Fixtures.created)+            ])++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.composedPayload()+        let illegal = BackupV18Membership(+            id: BackupV18Fixtures.composedMembershipID,+            workID: BackupV18Fixtures.composedWorkID, hostname: "example.com",+            createdAt: BackupV18Fixtures.created, urlIdentity: nil, urlIdentityState: .rule,+            urlIdentityRuleID: nil, workURLString: nil)+        let payload = BackupV18Payload(+            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 BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.composedPayload()+        let otherHost = "other.example"+        let otherRuleID = UUID(uuidString: "dddddddd-dddd-dddd-dddd-ddddddddddd2")!+        let otherSite = BackupV18Site(+            hostname: otherHost, displayName: "Other", mode: .untaught)+        let otherRule = BackupV18URLRule(+            id: otherRuleID, version: 1, isCurrent: false, createdAt: BackupV18Fixtures.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 = BackupV18Fixtures.membership(+            id: BackupV18Fixtures.composedMembershipID,+            workID: BackupV18Fixtures.composedWorkID, hostname: "example.com",+            urlIdentity: "serial-9", urlIdentityState: .rule, urlIdentityRuleID: otherRuleID)+        let payload = BackupV18Payload(+            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 BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.composedPayload()+        let absentRule = UUID(uuidString: "dddddddd-dddd-dddd-dddd-ddddddddddd3")!+        let dangling = BackupV18Fixtures.membership(+            id: BackupV18Fixtures.composedMembershipID,+            workID: BackupV18Fixtures.composedWorkID, hostname: "example.com",+            urlIdentity: "serial-9", urlIdentityState: .rule, urlIdentityRuleID: absentRule)+        let payload = BackupV18Payload(+            entries: base.entries, works: base.works, sites: base.sites,+            titlePatterns: base.titlePatterns, urlRules: base.urlRules,+            workTypes: base.workTypes, memberships: [dangling])++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.seriesPayload()++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))++        #expect(decoded.payload.series == payload.series)+        #expect(decoded.payload.links == payload.links)+        let first = try #require(+            decoded.payload.works.first { $0.id == BackupV18Fixtures.composedWorkID })+        #expect(first.seriesID == BackupV18Fixtures.seriesID)+        #expect(first.seriesPosition == 1)+        let second = try #require(+            decoded.payload.works.first { $0.id == BackupV18Fixtures.secondWorkID })+        #expect(second.seriesPosition == 2.5)+    }++    @Test("Two records for one series identity refuse")+    func duplicateSeriesIDRefuses() throws {+        let payload = BackupV18Fixtures.seriesPayload(+            series: [BackupV18Fixtures.seriesRecord(), BackupV18Fixtures.seriesRecord()])++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))+        }+    }++    @Test("Two records for one link identity refuse")+    func duplicateLinkIDRefuses() throws {+        let payload = BackupV18Fixtures.seriesPayload(+            links: [BackupV18Fixtures.linkRecord(), BackupV18Fixtures.linkRecord()])++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.seriesPayload(+            links: [+                BackupV18Fixtures.linkRecord(+                    a: BackupV18Fixtures.composedWorkID, b: BackupV18Fixtures.composedWorkID)+            ])++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.seriesPayload(+            links: [+                BackupV18Fixtures.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.+                BackupV18Fixtures.linkRecord(+                    id: second, a: BackupV18Fixtures.secondWorkID,+                    b: BackupV18Fixtures.composedWorkID, type: "sequel"),+            ])++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))+        }+    }++    @Test("A series with an empty trimmed name refuses")+    func emptySeriesNameRefuses() throws {+        for name in ["", "   ", "\n\t "] {+            let payload = BackupV18Fixtures.seriesPayload(+                series: [BackupV18Fixtures.seriesRecord(name: name)])+            #expect(throws: BackupCodecError.self) {+                try BackupV18Codec.decode(+                    try BackupV18Codec.encode(+                        payload: payload, metadata: BackupV18Fixtures.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?)] = [+            (BackupV18Fixtures.seriesID, nil),+            (nil, 2),+        ]+        for (id, position) in halves {+            let payload = BackupV18Fixtures.payloadWithMembership(+                seriesID: id, position: position)+            #expect(throws: BackupCodecError.self) {+                try BackupV18Codec.decode(+                    try BackupV18Codec.encode(+                        payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.payloadWithMembership(+                seriesID: BackupV18Fixtures.seriesID, position: position)+            #expect(throws: (any Error).self) {+                try BackupV18Codec.decode(+                    try BackupV18Codec.encode(+                        payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.seriesPayload(+            links: [+                BackupV18Fixtures.linkRecord(+                    a: BackupV18Fixtures.composedWorkID, b: absentWork, type: "spin-off")+            ],+            firstMembership: (absentSeries, 3))++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))++        #expect(+            decoded.payload.works.contains {+                $0.id == BackupV18Fixtures.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(+            BackupV18Fixtures.composedWorkID, BackupV18Fixtures.secondWorkID)+        let reversed = BackupV18Fixtures.linkRecord(a: ids.higher, b: ids.lower)+        #expect(reversed.lowerWorkID == ids.higher)++        let payload = BackupImportPayload(BackupV18Fixtures.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 = BackupV18Fixtures.creditsPayload()++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 == BackupV18Fixtures.aliasID })+        #expect(alias.stateRaw == CreatorState.merged.rawValue)+        #expect(alias.canonicalID == BackupV18Fixtures.moriID)++        let mori = try #require(+            decoded.payload.creators.first { $0.id == BackupV18Fixtures.moriID })+        #expect(mori.notes == "Also draws.")+        #expect(mori.nameModifiedAt == BackupV18Fixtures.created)+        #expect(mori.notesModifiedAt == BackupV18Fixtures.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 == BackupV18Fixtures.authorRoleID })+        #expect(author.position == 0)+        #expect(author.nameModifiedAt == BackupV18Fixtures.pristine)+        #expect(author.positionModifiedAt == BackupV18Fixtures.pristine)++        let letterer = try #require(+            decoded.payload.creatorRoles.first { $0.id == BackupV18Fixtures.lettererRoleID })+        #expect(letterer.position == 3)+        let editor = try #require(+            decoded.payload.creatorRoles.first { $0.id == BackupV18Fixtures.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 == BackupV18Fixtures.moriCreditID })+        #expect(credit.roleIDs.contains(BackupV18Fixtures.editorRoleID.uuidString))+    }++    @Test(+        "Two records for one creator, role or credit identity refuse",+        arguments: [0, 1, 2])+    func duplicateDirectoryIDsRefuse(table: Int) throws {+        let payload: BackupV18Payload+        switch table {+        case 0:+            payload = BackupV18Fixtures.creditsPayload(+                creators: BackupV18Fixtures.creatorRecords+                    + [BackupV18Fixtures.creatorRecord(+                        id: BackupV18Fixtures.moriID, name: "Mori Ayane")])+        case 1:+            payload = BackupV18Fixtures.creditsPayload(+                creatorRoles: BackupV18Fixtures.creatorRoleRecords+                    + [BackupV18Fixtures.creatorRoleRecord(+                        id: BackupV18Fixtures.lettererRoleID, name: "letterer", position: 9)])+        default:+            payload = BackupV18Fixtures.creditsPayload(+                credits: BackupV18Fixtures.creditRecords+                    + [BackupV18Fixtures.creditRecord(+                        id: BackupV18Fixtures.moriCreditID,+                        workID: BackupV18Fixtures.secondWorkID,+                        creatorID: BackupV18Fixtures.studioID)])+        }++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.creditsPayload(+            creators: BackupV18Fixtures.creatorRecords+                + [BackupV18Fixtures.creatorRecord(+                    id: BackupV18Fixtures.absentCreatorID, name: "MORI AYANE")])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(+                    payload: creators, metadata: BackupV18Fixtures.metadata()))+        }++        // Active against removed: the pair Req 2.2's restore could not choose+        // between.+        let roles = BackupV18Fixtures.creditsPayload(+            creatorRoles: BackupV18Fixtures.creatorRoleRecords+                + [BackupV18Fixtures.creatorRoleRecord(+                    id: BackupV18Fixtures.absentRoleID, name: "Editor", position: 5)])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: roles, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.creditsPayload(+            creators: [+                BackupV18Fixtures.creatorRecord(+                    id: BackupV18Fixtures.moriID, name: "Mori Ayane"),+                BackupV18Fixtures.creatorRecord(+                    id: BackupV18Fixtures.aliasID, name: "mori ayane", state: .merged,+                    canonicalID: BackupV18Fixtures.absentCreatorID),+            ])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(+                    payload: absentSurvivor, metadata: BackupV18Fixtures.metadata()))+        }++        let chain = BackupV18Fixtures.creditsPayload(+            creators: [+                BackupV18Fixtures.creatorRecord(+                    id: BackupV18Fixtures.moriID, name: "Mori Ayane"),+                BackupV18Fixtures.creatorRecord(+                    id: BackupV18Fixtures.studioID, name: "mori ayane 2", state: .merged,+                    canonicalID: BackupV18Fixtures.moriID),+                BackupV18Fixtures.creatorRecord(+                    id: BackupV18Fixtures.aliasID, name: "mori ayane", state: .merged,+                    canonicalID: BackupV18Fixtures.studioID),+            ])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(+                    payload: chain, metadata: BackupV18Fixtures.metadata()))+        }++        let roleChain = BackupV18Fixtures.creditsPayload(+            creatorRoles: BackupV18Fixtures.creatorRoleRecords+                + [BackupV18Fixtures.creatorRoleRecord(+                    id: BackupV18Fixtures.absentRoleID, name: "letters", position: 6,+                    state: .merged, canonicalID: BackupV18Fixtures.absentCreatorID)])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(+                    payload: roleChain, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.creditsPayload(+            credits: BackupV18Fixtures.creditRecords+                + [BackupV18Fixtures.creditRecord(+                    id: BackupV18Fixtures.absentRoleID,+                    workID: BackupV18Fixtures.composedWorkID,+                    creatorID: BackupV18Fixtures.moriID,+                    roleIDs: [BackupV18Fixtures.artistRoleID])])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: pair, metadata: BackupV18Fixtures.metadata()))+        }++        let repeated = BackupV18Fixtures.creditsPayload(+            credits: [+                BackupV18Credit(+                    id: BackupV18Fixtures.moriCreditID,+                    workID: BackupV18Fixtures.composedWorkID,+                    creatorID: BackupV18Fixtures.moriID,+                    roleIDs: [+                        BackupV18Fixtures.authorRoleID.uuidString,+                        BackupV18Fixtures.authorRoleID.uuidString,+                    ],+                    createdAt: BackupV18Fixtures.created,+                    modifiedAt: BackupV18Fixtures.created)+            ])+        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(+                    payload: repeated, metadata: BackupV18Fixtures.metadata()))+        }+    }++    @Test("A creator or role with an empty trimmed name refuses")+    func emptyDirectoryNamesRefuse() throws {+        for name in ["", "   ", "\n\t "] {+            let creators = BackupV18Fixtures.creditsPayload(+                creators: [BackupV18Fixtures.creatorRecord(+                    id: BackupV18Fixtures.moriID, name: name)],+                credits: [])+            #expect(throws: BackupCodecError.self) {+                try BackupV18Codec.decode(+                    try BackupV18Codec.encode(+                        payload: creators, metadata: BackupV18Fixtures.metadata()))+            }++            let roles = BackupV18Fixtures.creditsPayload(+                creatorRoles: [BackupV18Fixtures.creatorRoleRecord(+                    id: BackupV18Fixtures.lettererRoleID, name: name, position: 3)],+                credits: [])+            #expect(throws: BackupCodecError.self) {+                try BackupV18Codec.decode(+                    try BackupV18Codec.encode(+                        payload: roles, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.creditsPayload(+            credits: [+                BackupV18Fixtures.creditRecord(+                    id: BackupV18Fixtures.orphanCreditID, workID: absentWork,+                    creatorID: BackupV18Fixtures.absentCreatorID,+                    roleIDs: [BackupV18Fixtures.absentRoleID])+            ])++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))++        let credit = try #require(decoded.payload.credits.first)+        #expect(credit.workID == absentWork)+        #expect(credit.creatorID == BackupV18Fixtures.absentCreatorID)+        #expect(credit.roleIDs == [BackupV18Fixtures.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 = BackupV18Fixtures.composedPayload(dropNameContributor: true)++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 = BackupV18Fixtures.composedPayload()+        let entry = try #require(base.entries.first)+        let stripped = BackupV18Entry(+            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 = BackupV18Payload(+            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 BackupV18Codec.decode(+                try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))+        }+    }++    @Test("A mismatched version pair around 16/17 is refused by the codec itself")+    func mismatchedPairsRefuse() throws {+        let encoded = try BackupV18Codec.encode(+            payload: BackupV18Fixtures.payload(), metadata: BackupV18Fixtures.metadata())+        var object = try #require(+            try JSONSerialization.jsonObject(with: encoded) as? [String: Any])+        object["databaseSchemaVersion"] = 9++        #expect(throws: BackupCodecError.self) {+            try BackupV18Codec.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 BackupV18Codec.decode(BackupV18Fixtures.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.citationVersionPayloadJSON, entryCount: 1, workCount: 1)++        do {+            _ = try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+        let decoded = try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.statusFieldsOmittedPayloadJSON, entryCount: 1, workCount: 1)++        do {+            _ = try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+        let record = try #require(try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.placeArraysOmittedPayloadJSON, entryCount: 1, workCount: 1)++        do {+            _ = try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.citationVersionFreePayloadJSON, entryCount: 1, workCount: 1)+        let decoded = try BackupV18Codec.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 BackupV18Codec.encode(+            payload: BackupV18Fixtures.coveredPayload(),+            metadata: BackupV18Fixtures.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 BackupV18Codec.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 BackupV18Codec.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 = BackupV18Fixtures.duplicateVersionsPayload()++        let decoded = try BackupV18Codec.decode(+            try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.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 BackupV18ExportTests {+    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 = BackupV18Fixtures.payload()+        let exporter = BackupV18Exporter(+            repository: MockV15SnapshotProvider(payload: payload), stagingDirectory: tempDir)+        let result = try await exporter.export(metadata: BackupV18Fixtures.metadata())++        #expect(result.fileURL.lastPathComponent.contains("v18"))+        let decoded = try BackupV18Codec.decode(try Data(contentsOf: result.fileURL))+        #expect(decoded.backupFormatVersion == 18)+        #expect(decoded.databaseSchemaVersion == 19)+        #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 `BackupV18Work` 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: BackupV18Fixtures.coverBytes, digest: BackupV18Fixtures.coverDigest)+        try store.context.save()++        let payload = try LibraryRepository.projectV18Payload(context: store.context)++        let record = try #require(payload.works.first { $0.id == Self.workID })+        #expect(record.thumbnailShape == ThumbnailShape.portrait.rawValue)+        #expect(record.thumbnail == BackupV18Fixtures.coverBytes)++        let encoded = try BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        let text = try #require(String(data: encoded, encoding: .utf8))+        #expect(!text.contains("thumbnailDigest"))+        #expect(!text.contains(BackupV18Fixtures.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: BackupV18Fixtures.gappedCoverBytes,+            digest: BackupV18Fixtures.gappedCoverDigest)+        try store.context.save()++        let payload = try LibraryRepository.projectV18Payload(context: store.context)++        let record = try #require(payload.works.first { $0.id == Self.workID })+        #expect(record.thumbnailShape == ThumbnailShape.portrait.rawValue)+        #expect(record.thumbnail == BackupV18Fixtures.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.projectV18Payload(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: BackupV18Fixtures.coverDigest)+        store.insertSiblingRow(+            shapeRaw: ThumbnailShape.portrait.rawValue, bytes: BackupV18Fixtures.coverBytes,+            digest: BackupV18Fixtures.coverDigest)+        try store.context.save()++        let payload = try LibraryRepository.projectV18Payload(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 == BackupV18Fixtures.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: BackupV18Fixtures.coverDigest)+        store.insertSiblingRow(+            shapeRaw: ThumbnailShape.portrait.rawValue, bytes: BackupV18Fixtures.coverBytes,+            digest: BackupV18Fixtures.coverDigest)+        try store.context.save()++        let payload = try LibraryRepository.projectV18Payload(context: store.context)++        let record = try #require(payload.works.first { $0.id == Self.workID })+        #expect(record.thumbnail == BackupV18Fixtures.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: BackupV18ExportError.self) {+            _ = try LibraryRepository.projectV18Payload(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 == BackupV18ExportError.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: BackupV18Fixtures.coverBytes,+            digest: BackupV18Fixtures.coverDigest)+        try store.context.save()++        let error = #expect(throws: BackupV18ExportError.self) {+            _ = try LibraryRepository.projectV18Payload(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 == BackupV18ExportError.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: BackupV18ExportError.self) {+            _ = try LibraryRepository.projectV18Payload(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.projectV18Payload(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.projectV18Payload(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.projectV18Payload(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.projectV18Payload(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 BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.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: BackupV18ExportError.self) {+            try LibraryRepository.projectV18Payload(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.projectV18Payload(context: store.context)++        #expect(payload.characters.first?.facts.first?.source == .entry(absent))+        let encoded = try BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.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.projectV18Payload(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.projectV18Payload(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 BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.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: BackupV18ExportError.self) {+            try LibraryRepository.projectV18Payload(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.projectV18Payload(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.projectV18Payload(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: BackupV18ExportError.self) {+                try LibraryRepository.projectV18Payload(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.projectV18Payload(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 BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.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.projectV18Payload(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 BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.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.projectV18Payload(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.projectV18Payload(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 BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.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.projectV18Payload(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 BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.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: AsterismSchemaV19.self)+            container = try ModelContainer(+                for: schema,+                configurations: [+                    ModelConfiguration(+                        schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+                ])+            context = ModelContext(container)+            let site = Site(hostname: BackupV18ExportTests.host, displayName: "Characters")+            site.mode = .untaught+            context.insert(site)++            let work = Work.create(+                in: context, id: BackupV18ExportTests.workID, title: "A Work",+                hostname: BackupV18ExportTests.host, site: site,+                timestamp: BackupV18ExportTests.early)+            work.genericNotes = BackupV18ExportTests.genericNotes+            carrier = work++            let rawURL = "https://\(BackupV18ExportTests.host)/read/1"+            let entry = Entry(+                id: BackupV18ExportTests.entryID, captureTitle: "Chapter 1",+                captureTitleSource: .host, rawURLString: rawURL,+                hostname: BackupV18ExportTests.host, entryIdentityKey: rawURL,+                timestamp: BackupV18ExportTests.early, note: BackupV18ExportTests.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: BackupV18ExportTests.early)+            context.insert(character)+            if attachToWork { character.work = work }+        }++        func insertSuppression(nameKey: String) {+            let row = CharacterSuppression(+                kind: .candidate, nameKey: nameKey, actionAt: BackupV18ExportTests.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 = BackupV18ExportTests.workID+        ) {+            context.insert(+                Place(+                    id: id, name: name, nameKey: RecordNameKey.normalize(name),+                    aliases: aliases, note: note, facts: facts,+                    timestamp: BackupV18ExportTests.early, workID: workID))+        }++        func insertPlaceSuppression(+            nameKey: String, workID: UUID = BackupV18ExportTests.workID+        ) {+            context.insert(+                PlaceSuppression(+                    workID: workID, kind: .candidate, nameKey: nameKey,+                    actionAt: BackupV18ExportTests.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: BackupV18ExportTests.workID, title: carrier.displayTitle,+                hostname: BackupV18ExportTests.host, site: carrier.primaryMembership?.site,+                timestamp: BackupV18ExportTests.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(+                    BackupV18ExportTests.note)+        }++        func coverGenericNotes() {+            work?.genericNotesExtractionFingerprint = CharacterCoverageFingerprint.of(+                BackupV18ExportTests.genericNotes)+        }++        // `series-and-related-works` Req 13.++        func insertSeries(+            id: UUID, name: String, notes: String = "",+            createdAt: Date = BackupV18ExportTests.early,+            modifiedAt: Date = BackupV18ExportTests.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 = BackupV18ExportTests.early+        ) {+            let sorted = WorkDistinctPair.sortedIDs(a, b)+            context.insert(+                WorkLink(+                    id: id, lowerWorkID: sorted.lower, higherWorkID: sorted.higher,+                    linkType: type, createdAt: BackupV18ExportTests.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 = BackupV18ExportTests.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 = BackupV18ExportTests.early,+            positionModifiedAt: Date = BackupV18ExportTests.early,+            stateModifiedAt: Date = BackupV18ExportTests.early+        ) {+            let row = CreatorRole(+                id: id, name: name, position: position, stateRaw: state.rawValue,+                canonicalID: canonicalID)+            row.createdAt = BackupV18ExportTests.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 BackupV18ImportTests {++    // MARK: One accepted pair (Decision 2)++    @Test("The importer accepts 16/17")+    func acceptedGeneration() throws {+        let data = try BackupV18Codec.encode(+            payload: BackupV18Fixtures.payload(), metadata: BackupV18Fixtures.metadata())++        let plan = try BackupImporter.plan(from: data)+        #expect(plan.metadata.formatVersion == 18)+        #expect(plan.metadata.schemaVersion == 19)+        #expect(plan.payload == BackupImportPayload(BackupV18Fixtures.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 = BackupV18Fixtures.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("(\(BackupV18Document.formatVersion)/\(BackupV18Document.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: BackupV18Fixtures.plan(BackupV18Fixtures.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 == BackupV18Fixtures.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(BackupV18Fixtures.entryID))+        #expect(grover.workID == BackupV18Fixtures.workID, "the character joins its work")++        let suppressions = try await fixture.repository.m5SuppressionRows()+        let row = try #require(suppressions.first { $0.id == BackupV18Fixtures.suppressionID })+        #expect(row.nameKey == "the crowned one")+        #expect(row.kind == .candidate)+        #expect(row.status == .active)+        #expect(row.workID == BackupV18Fixtures.workID)++        #expect(+            try await fixture.repository.m5EntryCoverage(BackupV18Fixtures.entryID)+                == BackupV18Fixtures.noteFingerprint)+        #expect(+            try await fixture.repository.m5WorkCoverage(BackupV18Fixtures.workID)+                == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    characters: [+                        BackupV18Fixtures.character(id: BackupV18Fixtures.orphanID, workID: nil)+                    ])))++        let characters = try await fixture.repository.m5AllCharacters()+        let orphan = try #require(characters.first { $0.id == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(entryFingerprint: "not-this-note")))++        #expect(try await fixture.repository.m5EntryCoverage(BackupV18Fixtures.entryID) == nil)+        #expect(+            try await fixture.repository.m5WorkCoverage(BackupV18Fixtures.workID)+                == BackupV18Fixtures.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 = BackupV18Fixtures.payload()+        let stranger = UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee99")!+        let ids = WorkDistinctPair.sortedIDs(BackupV18Fixtures.workID, stranger)+        let plan = BackupV18Fixtures.plan(+            BackupV18Payload(+                entries: base.entries, works: base.works, sites: base.sites,+                titlePatterns: base.titlePatterns, urlRules: base.urlRules,+                workTypes: base.workTypes, memberships: base.memberships,+                distinctPairs: [+                    BackupV18DistinctPair(+                        id: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee98")!,+                        lowerWorkID: ids.lower, higherWorkID: ids.higher,+                        recordedAt: BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.payload()))++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    characters: [+                        BackupV18Fixtures.character(+                            name: "Renamed by an older device", note: "older",+                            modifiedAt: BackupV18Fixtures.created.addingTimeInterval(-1_000))+                    ])))++        let grover = try #require(+            try await fixture.repository.m5AllCharacters()+                .first { $0.id == BackupV18Fixtures.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 BackupV18Codec.encode(+            payload: BackupV18Fixtures.coveredPayload(),+            metadata: BackupV18Fixtures.metadata())++        try await fixture.repository.confirmImport(plan: try BackupImporter.plan(from: archive))++        #expect(+            try await fixture.repository.thumbnailColumns(of: BackupV18Fixtures.workID)+                == [ThumbnailColumns(+                    byteCount: BackupV18Fixtures.coverBytes.count,+                    shapeRaw: ThumbnailShape.portrait.rawValue,+                    digest: BackupV18Fixtures.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: BackupV18Fixtures.workID, digest: BackupV18Fixtures.coverDigest)+                == BackupV18Fixtures.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 BackupV18Codec.encode(+            payload: BackupV18Fixtures.coveredPayload(+                bytes: BackupV18Fixtures.gappedCoverBytes),+            metadata: BackupV18Fixtures.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: BackupV18Fixtures.workID,+                digest: BackupV18Fixtures.gappedCoverDigest)+                == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.coveredPayload(+                    bytes: BackupV18Fixtures.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: BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.coveredPayload()))+        #expect(+            try await fixture.repository.thumbnailColumns(of: BackupV18Fixtures.workID)+                != [ThumbnailColumns.empty])++        let result = try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.coveredPayload(+                    bytes: BackupV18Fixtures.undecodableCoverBytes,+                    modifiedAt: BackupV18Fixtures.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: BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.coveredPayload(+                    modifiedAt: BackupV18Fixtures.created.addingTimeInterval(1_000))))++        let result = try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.coveredPayload(+                    shapeRaw: ThumbnailShape.square.rawValue,+                    bytes: BackupV18Fixtures.undecodableCoverBytes,+                    modifiedAt: BackupV18Fixtures.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: BackupV18Fixtures.workID)+                == [ThumbnailColumns(+                    byteCount: BackupV18Fixtures.coverBytes.count,+                    shapeRaw: ThumbnailShape.portrait.rawValue,+                    digest: BackupV18Fixtures.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 = BackupV18Fixtures.plan(BackupV18Fixtures.coveredPayload())++        try await fixture.repository.confirmImport(plan: plan)+        let columnsAfterFirst = try await fixture.repository+            .thumbnailColumns(of: BackupV18Fixtures.workID)++        try await fixture.repository.confirmImport(plan: plan)++        #expect(+            try await fixture.repository.thumbnailColumns(of: BackupV18Fixtures.workID)+                == columnsAfterFirst)+        #expect(+            try await fixture.repository.thumbnailBytes(+                workID: BackupV18Fixtures.workID, digest: BackupV18Fixtures.coverDigest)+                == BackupV18Fixtures.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: AsterismSchemaV19.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: BackupV18Fixtures.created)+        let cover = ArchiveThumbnail.value(+            shapeRaw: ThumbnailShape.portrait.rawValue,+            bytes: BackupV18Fixtures.coverBytes,+            digest: BackupV18Fixtures.coverDigest)+        LibraryRepository.applyThumbnail(cover, to: work)+        try context.save()+        #expect(work.thumbnailDigest == BackupV18Fixtures.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 == BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.payload()))++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    characters: [+                        BackupV18Fixtures.character(+                            name: "Grover Underwood", note: "Still the guide.",+                            modifiedAt: BackupV18Fixtures.created.addingTimeInterval(1_000))+                    ])))++        let grover = try #require(+            try await fixture.repository.m5AllCharacters()+                .first { $0.id == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    suppressions: [+                        BackupV18Fixtures.suppression(+                            status: .cleared,+                            actionAt: BackupV18Fixtures.created.addingTimeInterval(1_000))+                    ])))++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(suppressions: [BackupV18Fixtures.suppression()])))++        let row = try #require(+            try await fixture.repository.m5SuppressionRows()+                .first { $0.id == BackupV18Fixtures.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 BackupV18Codec.encode(+                payload: BackupV18Fixtures.composedPayload(),+                metadata: BackupV18Fixtures.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(BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.payload()))++        let places = try await fixture.repository.m5AllPlaces()+        let keep = try #require(places.first { $0.id == BackupV18Fixtures.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 == BackupV18Fixtures.workID, "the place joins its work")++        let rows = try await fixture.repository.m5PlaceSuppressionRows()+        let row = try #require(rows.first { $0.id == BackupV18Fixtures.placeSuppressionID })+        #expect(row.nameKey == "low road")+        #expect(row.kind == .candidate)+        #expect(row.status == .active)+        #expect(row.workID == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    places: [+                        BackupV18Fixtures.place(+                            id: BackupV18Fixtures.orphanPlaceID, workID: absent)+                    ],+                    placeSuppressions: [BackupV18Fixtures.placeSuppression(workID: absent)])))++        let orphan = try #require(+            try await fixture.repository.m5AllPlaces()+                .first { $0.id == BackupV18Fixtures.orphanPlaceID })+        #expect(orphan.workID == absent)+        #expect(+            try await fixture.repository.m5PlaceSuppressionRows()+                .first { $0.id == BackupV18Fixtures.placeSuppressionID }?.workID == absent)++        let payload = try await fixture.repository.backupV18Snapshot()+        #expect(payload.places.first { $0.id == BackupV18Fixtures.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 = BackupV18Fixtures.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: BackupV18Fixtures.keepID, name: "The Keep", nameKey: "high keep",+                    workID: localWorkID, createdAt: older, modifiedAt: older)+            ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(places: [BackupV18Fixtures.place(workID: absent)])))++        let keep = try #require(+            try await fixture.repository.m5AllPlaces()+                .first { $0.id == BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(-1_000)+        let fixture = try await M5Fixture()+        try await fixture.repository.seedM5Rows(+            places: [+                M5SeedPlace(+                    id: BackupV18Fixtures.keepID, name: "The Keep", nameKey: "high keep",+                    workID: unresolvable, createdAt: older, modifiedAt: older)+            ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.payload()))++        let keep = try #require(+            try await fixture.repository.m5AllPlaces()+                .first { $0.id == BackupV18Fixtures.keepID })+        #expect(keep.workID == BackupV18Fixtures.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 = BackupV18Fixtures.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: BackupV18Fixtures.placeSuppressionID, workID: localWorkID,+                    nameKey: "old key", actionAt: older)+            ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    placeSuppressions: [BackupV18Fixtures.placeSuppression(workID: absent)])))++        let row = try #require(+            try await fixture.repository.m5PlaceSuppressionRows()+                .first { $0.id == BackupV18Fixtures.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 = BackupV18Fixtures.plan(BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.payload()))++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    places: [+                        BackupV18Fixtures.place(+                            name: "Renamed by an older device", note: "older",+                            modifiedAt: BackupV18Fixtures.created.addingTimeInterval(-1_000))+                    ])))++        var keep = try #require(+            try await fixture.repository.m5AllPlaces()+                .first { $0.id == BackupV18Fixtures.keepID })+        #expect(keep.name == "The High Keep")+        #expect(keep.note == "The fortress above the pass.")++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    places: [+                        BackupV18Fixtures.place(+                            name: "The Keep Above the Pass", note: "Still standing.",+                            modifiedAt: BackupV18Fixtures.created.addingTimeInterval(1_000))+                    ])))++        keep = try #require(+            try await fixture.repository.m5AllPlaces()+                .first { $0.id == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    placeSuppressions: [+                        BackupV18Fixtures.placeSuppression(+                            status: .cleared,+                            actionAt: BackupV18Fixtures.created.addingTimeInterval(1_000))+                    ])))++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.payload(+                    placeSuppressions: [BackupV18Fixtures.placeSuppression()])))++        let row = try #require(+            try await fixture.repository.m5PlaceSuppressionRows()+                .first { $0.id == BackupV18Fixtures.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 = BackupV18Fixtures.plan(BackupV18Fixtures.seriesPayload())++        try await fixture.repository.confirmImport(plan: plan)++        let series = try await fixture.repository.seriesRowValues()+        #expect(series.map(\.id) == [BackupV18Fixtures.seriesID])+        #expect(series.first?.name == "Ashfall Cycle")+        #expect(series.first?.notes == "Read 2.5 after 2.")+        #expect(+            try await fixture.repository.membershipColumns(of: BackupV18Fixtures.composedWorkID)+                == [SeriesColumns(seriesID: BackupV18Fixtures.seriesID, position: 1)])+        #expect(+            try await fixture.repository.membershipColumns(of: BackupV18Fixtures.secondWorkID)+                == [SeriesColumns(seriesID: BackupV18Fixtures.seriesID, position: 2.5)])+        let links = try await fixture.repository.workLinkRowValues()+        #expect(links.map(\.id) == [BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.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: BackupV18Fixtures.composedWorkID,+                b: UUID(uuidString: "eeeeeeee-eeee-eeee-eeee-eeeeeeeeee97")!, type: "prequel")+        ])+        try await fixture.repository.updateSeries(+            id: BackupV18Fixtures.seriesID, name: "Renamed here", notes: "later")+        try await fixture.repository.retypeLink(+            id: BackupV18Fixtures.linkID, type: "retyped here")++        // The same archive again: its records are now older than both rows.+        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.seriesPayload()))++        let afterOlder = try await fixture.repository.seriesRowValues()+        #expect(afterOlder.first { $0.id == BackupV18Fixtures.seriesID }?.name == "Renamed here")+        #expect(+            try await fixture.repository.workLinkRowValues()+                .first { $0.id == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.seriesPayload(+                    series: [+                        BackupV18Fixtures.seriesRecord(name: "Renamed there", modifiedAt: later)+                    ],+                    links: [BackupV18Fixtures.linkRecord(type: "retyped there", modifiedAt: later)])))++        #expect(+            try await fixture.repository.seriesRowValues()+                .first { $0.id == BackupV18Fixtures.seriesID }?.name == "Renamed there")+        #expect(+            try await fixture.repository.workLinkRowValues()+                .first { $0.id == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.seriesPayload(+                    links: [+                        BackupV18Fixtures.linkRecord(+                            a: BackupV18Fixtures.composedWorkID, b: absentWork, type: "spin-off")+                    ],+                    firstMembership: (absentSeries, 3))))++        #expect(+            try await fixture.repository.membershipColumns(of: BackupV18Fixtures.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 = BackupV18Fixtures.plan(BackupV18Fixtures.creditsPayload())++        try await fixture.repository.confirmImport(plan: plan)++        let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+        let mori = try #require(creators[BackupV18Fixtures.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 == BackupV18Fixtures.created)+        #expect(mori.notesModifiedAt == BackupV18Fixtures.created)+        let alias = try #require(creators[BackupV18Fixtures.aliasID])+        #expect(alias.state == .merged)+        #expect(alias.canonicalID == BackupV18Fixtures.moriID)+        // A credit naming the alias reads as its survivor on arrival.+        #expect(creators.canonicalID(of: BackupV18Fixtures.aliasID) == BackupV18Fixtures.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[BackupV18Fixtures.lettererRoleID]?.position == 3)+        #expect(roles[BackupV18Fixtures.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[BackupV18Fixtures.authorRoleID]?.isPristine == true)++        let credits = try await fixture.repository.creditRows()+        #expect(credits.count == 3)+        let credit = try #require(credits.first { $0.id == BackupV18Fixtures.moriCreditID })+        #expect(+            credit.roleIDs+                == [+                    BackupV18Fixtures.authorRoleID.uuidString,+                    BackupV18Fixtures.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 == BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(1_000)+        try await fixture.repository.seedCreators([+            SeedCreator(+                id: BackupV18Fixtures.moriID, name: "Renamed here",+                nameModifiedAt: later, createdAt: BackupV18Fixtures.created)+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.creditsPayload()))++        let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+        let mori = try #require(creators[BackupV18Fixtures.moriID])+        #expect(mori.name == "Renamed here")+        #expect(mori.nameModifiedAt == later)+        #expect(mori.notes == "Also draws.")+        #expect(mori.notesModifiedAt == BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(1_000)+        // A second row of the seeded identity, carrying the reader's rename.+        try await fixture.repository.seedCreatorRoles([+            SeedCreatorRole(+                id: BackupV18Fixtures.authorRoleID, name: "writer", position: 0,+                nameModifiedAt: touched)+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.creditsPayload()))++        let roles = CreatorRoleDirectory(+            rows: try await fixture.repository.creatorRoleRowValues())+        #expect(roles[BackupV18Fixtures.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 = BackupV18Fixtures.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: BackupV18Fixtures.created),+            SeedCreator(+                id: BackupV18Fixtures.moriID, name: "Mori Ayane", state: .merged,+                canonicalID: survivor,+                nameModifiedAt: BackupV18Fixtures.created,+                stateModifiedAt: BackupV18Fixtures.created),+            // Locally active, and the archive says it merged into `mori`, which+            // resolves here to `survivor`: the archive's later stamp applies.+            SeedCreator(+                id: BackupV18Fixtures.aliasID, name: "mori ayane",+                nameModifiedAt: BackupV18Fixtures.created.addingTimeInterval(2_000),+                stateModifiedAt: BackupV18Fixtures.created),+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.creditsPayload(+                    creators: [+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                            notes: "Also draws.", stateModifiedAt: later),+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.studioID, name: "Studio Lantern"),+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.aliasID, name: "mori ayane",+                            state: .merged, canonicalID: BackupV18Fixtures.moriID,+                            stateModifiedAt: later),+                    ])))++        let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+        let mori = try #require(creators[BackupV18Fixtures.moriID])+        #expect(mori.state == .merged)+        #expect(mori.canonicalID == survivor)+        let alias = try #require(creators[BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(3_000)+        try await fixture.repository.seedCreators([+            SeedCreator(+                id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                nameModifiedAt: BackupV18Fixtures.created,+                stateModifiedAt: BackupV18Fixtures.created)+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.creditsPayload(+                    creators: [+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                            state: .merged, canonicalID: nil, stateModifiedAt: later)+                    ])))++        let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+        #expect(creators[BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.creditsPayload(+                    creators: [+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                            state: .merged, canonicalID: nil)+                    ])))++        let rows = try await fixture.repository.creatorRowValues()+        let row = try #require(rows.first { $0.id == BackupV18Fixtures.moriID })+        #expect(row.stateRaw == CreatorState.merged.rawValue)+        #expect(row.canonicalID == nil, "the survivorless pointer is kept, not invented")+        #expect(+            CreatorDirectory(rows: rows)[BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(3_000)+        try await fixture.repository.seedCreators([+            SeedCreator(+                id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                nameModifiedAt: BackupV18Fixtures.created,+                stateModifiedAt: BackupV18Fixtures.created)+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.creditsPayload(+                    creators: [+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                            state: .merged, canonicalID: BackupV18Fixtures.absentCreatorID,+                            stateModifiedAt: later)+                    ])))++        let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+        #expect(creators[BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(3_000)+        try await fixture.repository.seedCreators([+            SeedCreator(+                id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                nameModifiedAt: BackupV18Fixtures.created,+                stateModifiedAt: BackupV18Fixtures.created)+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.creditsPayload(+                    creators: [+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                            state: .merged, canonicalID: BackupV18Fixtures.studioID,+                            stateModifiedAt: later),+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.studioID, name: "Studio Lantern"),+                    ])))++        let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+        let mori = try #require(creators[BackupV18Fixtures.moriID])+        #expect(mori.state == .merged)+        #expect(mori.canonicalID == BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(3_000)+        try await fixture.repository.seedCreators([+            SeedCreator(+                id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                nameModifiedAt: touched, stateModifiedAt: touched)+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.creditsPayload(+                    creators: [+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.moriID, name: "Mori Ayane",+                            state: .merged, canonicalID: BackupV18Fixtures.studioID),+                        BackupV18Fixtures.creatorRecord(+                            id: BackupV18Fixtures.studioID, name: "Studio Lantern"),+                    ])))++        let creators = CreatorDirectory(rows: try await fixture.repository.creatorRowValues())+        #expect(creators[BackupV18Fixtures.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: BackupV18Fixtures.created.addingTimeInterval(-1_000),+                createdAt: BackupV18Fixtures.created.addingTimeInterval(-1_000))+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.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[BackupV18Fixtures.moriID] != nil)+        // The earliest-created non-pristine identity survives, and the other+        // reads as it (Req 10.3).+        #expect(creators.canonicalID(of: BackupV18Fixtures.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: BackupV18Fixtures.created,+                positionModifiedAt: BackupV18Fixtures.created,+                createdAt: BackupV18Fixtures.created)+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.creditsPayload()))++        let roles = CreatorRoleDirectory(+            rows: try await fixture.repository.creatorRoleRowValues())+        let letterer = try #require(roles[BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(1_000)+        try await fixture.repository.seedCreatorRoles([+            SeedCreatorRole(+                id: BackupV18Fixtures.lettererRoleID, name: "letterer", position: 3,+                nameModifiedAt: BackupV18Fixtures.created,+                positionModifiedAt: BackupV18Fixtures.created,+                stateModifiedAt: BackupV18Fixtures.created,+                createdAt: BackupV18Fixtures.created),+            SeedCreatorRole(+                id: BackupV18Fixtures.editorRoleID, name: "editor", position: 4,+                state: .removed,+                nameModifiedAt: BackupV18Fixtures.created,+                positionModifiedAt: BackupV18Fixtures.created,+                stateModifiedAt: BackupV18Fixtures.created,+                createdAt: BackupV18Fixtures.created),+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.creditsPayload(+                    creatorRoles: BackupV18Fixtures.seededRoleRecords + [+                        BackupV18Fixtures.creatorRoleRecord(+                            id: BackupV18Fixtures.lettererRoleID, name: "letterer",+                            position: 3, state: .removed, stateModifiedAt: later),+                        BackupV18Fixtures.creatorRoleRecord(+                            id: BackupV18Fixtures.editorRoleID, name: "editor",+                            position: 4, stateModifiedAt: later),+                    ])))++        let roles = CreatorRoleDirectory(+            rows: try await fixture.repository.creatorRoleRowValues())+        #expect(roles[BackupV18Fixtures.lettererRoleID]?.state == .removed)+        #expect(roles[BackupV18Fixtures.lettererRoleID]?.stateModifiedAt == later)+        #expect(roles[BackupV18Fixtures.editorRoleID]?.state == .active)+        #expect(roles[BackupV18Fixtures.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 = BackupV18Fixtures.created.addingTimeInterval(2_000)+        try await fixture.repository.seedCreatorRoles([+            SeedCreatorRole(+                id: BackupV18Fixtures.lettererRoleID, name: "letterer", position: 3,+                state: .removed,+                nameModifiedAt: BackupV18Fixtures.created,+                positionModifiedAt: BackupV18Fixtures.created,+                stateModifiedAt: touched,+                createdAt: BackupV18Fixtures.created)+        ])++        // The archive's `letterer` is active, stamped at `created`.+        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.creditsPayload()))++        let roles = CreatorRoleDirectory(+            rows: try await fixture.repository.creatorRoleRowValues())+        #expect(roles[BackupV18Fixtures.lettererRoleID]?.state == .removed)+        #expect(roles[BackupV18Fixtures.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: BackupV18Fixtures.created,+                positionModifiedAt: BackupV18Fixtures.created,+                stateModifiedAt: BackupV18Fixtures.created,+                createdAt: BackupV18Fixtures.created)+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.creditsPayload()))++        let roles = CreatorRoleDirectory(+            rows: try await fixture.repository.creatorRoleRowValues())+        let letterer = try #require(roles[BackupV18Fixtures.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[BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.creditsPayload()))+        let stored = [+            BackupV18Fixtures.authorRoleID.uuidString,+            BackupV18Fixtures.editorRoleID.uuidString,+        ].sorted()++        func reimport(roleIDs: [UUID], modifiedAt: Date) async throws {+            try await fixture.repository.confirmImport(+                plan: BackupV18Fixtures.plan(+                    BackupV18Fixtures.creditsPayload(+                        credits: [+                            BackupV18Fixtures.creditRecord(+                                id: BackupV18Fixtures.moriCreditID,+                                workID: BackupV18Fixtures.composedWorkID,+                                creatorID: BackupV18Fixtures.moriID,+                                roleIDs: roleIDs, modifiedAt: modifiedAt)+                        ])))+        }++        func roleIDs() async throws -> [String] {+            try await fixture.repository.creditRows()+                .first { $0.id == BackupV18Fixtures.moriCreditID }?.roleIDs ?? []+        }++        // Older: nothing moves.+        try await reimport(+            roleIDs: [BackupV18Fixtures.artistRoleID],+            modifiedAt: BackupV18Fixtures.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: [BackupV18Fixtures.authorRoleID], modifiedAt: BackupV18Fixtures.created)+        #expect(try await roleIDs() == stored)++        // Equal, and a superset: the archive widens it.+        try await reimport(+            roleIDs: [+                BackupV18Fixtures.authorRoleID, BackupV18Fixtures.editorRoleID,+                BackupV18Fixtures.translatorRoleID,+            ], modifiedAt: BackupV18Fixtures.created)+        #expect(try await roleIDs().contains(BackupV18Fixtures.translatorRoleID.uuidString))++        // Strictly later: the archive wins outright, narrowing included.+        try await reimport(+            roleIDs: [BackupV18Fixtures.artistRoleID],+            modifiedAt: BackupV18Fixtures.created.addingTimeInterval(1_000))+        #expect(try await roleIDs() == [BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.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: BackupV18Fixtures.composedWorkID,+                creatorID: BackupV18Fixtures.aliasID,+                roleIDs: [BackupV18Fixtures.translatorRoleID.uuidString])+        ])++        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(BackupV18Fixtures.creditsPayload()))++        let rows = try await fixture.repository.creditRows()+            .filter { $0.workID == BackupV18Fixtures.composedWorkID }+        #expect(rows.map(\.id) == [BackupV18Fixtures.moriCreditID])+        #expect(+            rows.first?.roleIDs+                == [+                    BackupV18Fixtures.authorRoleID.uuidString,+                    BackupV18Fixtures.editorRoleID.uuidString,+                    BackupV18Fixtures.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: BackupV18Fixtures.created,+                createdAt: BackupV18Fixtures.created),+            SeedCreator(+                id: renamed, name: "Ayane Mori",+                nameModifiedAt: BackupV18Fixtures.created,+                createdAt: BackupV18Fixtures.created.addingTimeInterval(1_000)),+        ])+        try await fixture.repository.seedCredits([+            SeedCredit(+                id: keptCredit, workID: BackupV18Fixtures.composedWorkID, creatorID: kept,+                roleIDs: [BackupV18Fixtures.authorRoleID.uuidString],+                createdAt: BackupV18Fixtures.created,+                modifiedAt: BackupV18Fixtures.created),+            SeedCredit(+                id: otherCredit, workID: BackupV18Fixtures.composedWorkID,+                creatorID: renamed,+                roleIDs: [BackupV18Fixtures.artistRoleID.uuidString],+                createdAt: BackupV18Fixtures.created.addingTimeInterval(1_000),+                modifiedAt: BackupV18Fixtures.created.addingTimeInterval(1_000)),+        ])++        // Creators only: no roles, and no credits at all.+        try await fixture.repository.confirmImport(+            plan: BackupV18Fixtures.plan(+                BackupV18Fixtures.creditsPayload(+                    creators: [+                        BackupV18Fixtures.creatorRecord(+                            id: renamed, name: "Mori Ayane",+                            nameModifiedAt: BackupV18Fixtures.created+                                .addingTimeInterval(2_000),+                            createdAt: BackupV18Fixtures.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 == BackupV18Fixtures.composedWorkID }+        #expect(rows.map(\.id) == [keptCredit])+        #expect(+            rows.first?.roleIDs+                == [+                    BackupV18Fixtures.authorRoleID.uuidString,+                    BackupV18Fixtures.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: BackupV18Fixtures.plan(BackupV18Fixtures.coveredPayload()))++        let payload = try await source.repository.backupV18Snapshot()+        let plan = try BackupImporter.plan(+            from: try BackupV18Codec.encode(+                payload: payload, metadata: BackupV18Fixtures.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 == BackupV18Fixtures.groverID })+        #expect(grover.name == "Grover")+        #expect(grover.facts.map(\.quote) == ["promised to guide them home"])+        #expect(grover.workID == BackupV18Fixtures.workID)+        #expect(+            try await target.repository.m5SuppressionRows()+                .contains { $0.id == BackupV18Fixtures.suppressionID })+        #expect(+            try await target.repository.m5EntryCoverage(BackupV18Fixtures.entryID)+                == BackupV18Fixtures.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 == BackupV18Fixtures.keepID })+        #expect(keep.name == "The High Keep")+        #expect(keep.facts.map(\.quote) == ["above the pass"])+        #expect(keep.workID == BackupV18Fixtures.workID)+        #expect(+            try await target.repository.m5PlaceSuppressionRows()+                .contains { $0.id == BackupV18Fixtures.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: BackupV18Fixtures.workID)+                == [ThumbnailColumns(+                    byteCount: BackupV18Fixtures.coverBytes.count,+                    shapeRaw: ThumbnailShape.portrait.rawValue,+                    digest: BackupV18Fixtures.coverDigest)])+        #expect(+            try await target.repository.thumbnailBytes(+                workID: BackupV18Fixtures.workID, digest: BackupV18Fixtures.coverDigest)+                == BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.composedPayload(readingStatus: .catchingUp)))++        let payload = try await source.repository.backupV18Snapshot()+        #expect(+            payload.works.first { $0.id == BackupV18Fixtures.composedWorkID }?.readingStatus+                == .catchingUp)++        let encoded = try BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.decode(encoded).backupFormatVersion == 18)++        let target = try await M5Fixture()+        try await target.repository.confirmImport(plan: try BackupImporter.plan(from: encoded))++        #expect(+            try await target.repository.work(id: BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.composedPayload(readingStatus: .toRead)))++        let payload = try await source.repository.backupV18Snapshot()+        #expect(+            payload.works.first { $0.id == BackupV18Fixtures.composedWorkID }?.readingStatus+                == .toRead)++        let encoded = try BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Fixtures.metadata())+        #expect(try BackupV18Codec.decode(encoded).backupFormatVersion == 18)++        let target = try await M5Fixture()+        try await target.repository.confirmImport(plan: try BackupImporter.plan(from: encoded))++        let restored = try await target.repository.work(id: BackupV18Fixtures.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: BackupV18Fixtures.plan(payload))+        let firstImport = try await fixture.repository.backupV18Snapshot()++        strategy.arm()+        try await fixture.repository.confirmImport(plan: BackupV18Fixtures.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.backupV18Snapshot() == 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: AsterismSchemaV19.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(BackupV18Fixtures.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 = BackupV18Entry(+            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: AsterismSchemaV19.self)+        let container = try ModelContainer(+            for: schema,+            configurations: [+                ModelConfiguration(+                    schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+            ])+        let context = ModelContext(container)+        context.autosaveEnabled = false+        let record = BackupV18Fixtures.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: BackupV18SnapshotProviding, @unchecked Sendable {+    let payload: BackupV18Payload+    init(payload: BackupV18Payload) { self.payload = payload }+    func backupV18Snapshot() async throws -> BackupV18Payload { payload }+}
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18Fixtures.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18Fixtures.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18Fixtures.swiftnew file mode 100644index 00000000..84865088--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18Fixtures.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 BackupV18Fixtures {+    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+    ) -> BackupV18Payload {+        let base = payload()+        return BackupV18Payload(+            entries: base.entries,+            works: base.works.map { record in+                BackupV18Work(+                    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+    ) -> BackupV18WorkType {+        BackupV18WorkType(+            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+    ) -> BackupV18Membership {+        BackupV18Membership(+            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: [BackupV18WorkType] = [workTypeRecord(id: novelTypeID, name: "novel")]+    ) -> BackupV18Payload {+        let host = minimalHost+        let patternID = UUID(uuidString: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")!+        let rawURL = "https://example.com/read/7"++        let pattern = BackupV18TitlePattern(+            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 = BackupV18Site(+            hostname: host, displayName: "Example", mode: .taught)++        let work = BackupV18Work(+            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 = BackupV18Entry(+            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 BackupV18Payload(+            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: [BackupV18WorkType] = [workTypeRecord(id: novelTypeID, name: "novel")]+    ) -> BackupV18Payload {+        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 = BackupV18TitlePattern(+            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 = BackupV18URLRule(+            id: ruleID, version: 1, isCurrent: true, createdAt: created,+            origin: .readerTaught,+            definition: .sequence(locator: .query(name: ExactScalarString("chapter"))),+            siteHostname: host)++        let site = BackupV18Site(+            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 = BackupV18Work(+            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 = BackupV18Entry(+            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 BackupV18Payload(+            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+    ) -> BackupV18Series {+        BackupV18Series(+            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+    ) -> BackupV18Link {+        BackupV18Link(+            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: [BackupV18Series] = [seriesRecord()],+        links: [BackupV18Link] = [linkRecord()],+        firstMembership: (series: UUID, position: Double)? = (seriesID, 1),+        secondMembership: (series: UUID, position: Double)? = (seriesID, 2.5)+    ) -> BackupV18Payload {+        let base = composedPayload()+        let host = "example.com"+        let second = BackupV18Work(+            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 BackupV18Payload(+            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. `BackupV18Work`'s fields are+    /// `let`, so a copy is a full restatement.+    static func placed(+        _ record: BackupV18Work, membership: (series: UUID, position: Double)?+    ) -> BackupV18Work {+        BackupV18Work(+            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: [BackupV18Series] = [seriesRecord()]+    ) -> BackupV18Payload {+        let base = composedPayload()+        return BackupV18Payload(+            entries: base.entries,+            works: base.works.map {+                BackupV18Work(+                    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+    ) -> BackupV18Creator {+        BackupV18Creator(+            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+    ) -> BackupV18CreatorRole {+        BackupV18CreatorRole(+            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) -> BackupV18CreatorRole {+        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: [BackupV18CreatorRole] {+        CreatorRoleSeeding.seeds.map(seededRoleRecord)+    }++    static func creditRecord(+        id: UUID,+        workID: UUID,+        creatorID: UUID,+        roleIDs: [UUID] = [],+        createdAt: Date = created,+        modifiedAt: Date = created+    ) -> BackupV18Credit {+        BackupV18Credit(+            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: [BackupV18Creator] {+        [+            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: [BackupV18CreatorRole] {+        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: [BackupV18Credit] {+        [+            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: [BackupV18Creator]? = nil,+        creatorRoles: [BackupV18CreatorRole]? = nil,+        credits: [BackupV18Credit]? = nil+    ) -> BackupV18Payload {+        let base = seriesPayload()+        return BackupV18Payload(+            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) -> BackupV18Payload {+        let host = "unanchored.example"+        let patternID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff1")!+        let ruleID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff2")!++        let pattern = BackupV18TitlePattern(+            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 = BackupV18URLRule(+            id: ruleID, version: 1, isCurrent: true, createdAt: created,+            origin: .readerTaught,+            definition: .work(locator: .pathBracketed(left: left, right: .unanchored)),+            siteHostname: host)++        let site = BackupV18Site(+            hostname: host, displayName: "Unanchored", mode: .taught)++        return BackupV18Payload(+            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) -> BackupV18Payload {+        let patternID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff3")!+        let ruleID = UUID(uuidString: "ffffffff-ffff-ffff-ffff-fffffffffff4")!++        let pattern = BackupV18TitlePattern(+            id: patternID, siteHostname: combinedRuleHost, version: 1, isActive: true,+            createdAt: created,+            definition: StoredPatternDefinition(definition: .wholeTitle))++        let rule = BackupV18URLRule(+            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 = BackupV18Site(+            hostname: combinedRuleHost, displayName: "Combined", mode: .taught)++        return BackupV18Payload(+            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: `BackupV18Codec.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 = BackupV18Document.formatVersion+        let schema = BackupV18Document.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. `BackupV18Site.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() -> BackupV18Payload {+        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) -> BackupV18TitlePattern {+            BackupV18TitlePattern(+                id: id, siteHostname: host, version: 1, isActive: active, createdAt: createdAt,+                definition: StoredPatternDefinition(definition: .wholeTitle))+        }++        func rule(_ id: UUID, version: Int, current: Bool, createdAt: Date) -> BackupV18URLRule {+            BackupV18URLRule(+                id: id, version: version, isCurrent: current, createdAt: createdAt,+                origin: .readerTaught,+                definition: .sequence(+                    locator: .pathBracketed(left: .literal(ExactScalarString("c")), right: .end)),+                siteHostname: host)+        }++        return BackupV18Payload(+            entries: [], works: [],+            sites: [+                BackupV18Site(+                    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() -> BackupV18Payload {+        let host = "dup.example"+        let patternID = UUID()+        let ruleA = UUID()+        let ruleB = UUID()++        let pattern = BackupV18TitlePattern(+            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) -> BackupV18URLRule {+            BackupV18URLRule(+                id: id, version: version, isCurrent: true, createdAt: created,+                origin: .readerTaught,+                definition: .sequence(+                    locator: .pathBracketed(left: .literal(ExactScalarString("c")), right: .end)),+                siteHostname: host)+        }++        let site = BackupV18Site(+            hostname: host, displayName: "Dup", mode: .taught)++        return BackupV18Payload(+            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+    ) -> BackupV18Character {+        BackupV18Character(+            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+    ) -> BackupV18Suppression {+        BackupV18Suppression(+            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+    ) -> BackupV18Place {+        BackupV18Place(+            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+    ) -> BackupV18PlaceSuppression {+        BackupV18PlaceSuppression(+            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: [BackupV18Character] = [character()],+        suppressions: [BackupV18Suppression] = [suppression()],+        places: [BackupV18Place] = [place()],+        placeSuppressions: [BackupV18PlaceSuppression] = [placeSuppression()],+        entryFingerprint: String? = noteFingerprint,+        workFingerprint: String? = genericNotesFingerprint+    ) -> BackupV18Payload {+        let base = composedPayload()+        return BackupV18Payload(+            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)+        -> BackupV18Metadata+    {+        BackupV18Metadata(appBuild: appBuild, exportedAt: exportedAt)+    }++    static func plan(_ payload: BackupV18Payload) -> BackupImportPlan {+        BackupImportPlan(+            metadata: BackupImportMetadata(+                formatVersion: BackupV18Document.formatVersion,+                schemaVersion: BackupV18Document.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. `BackupV18Entry`'s+    /// fields are `let`, so a copy is a full restatement — stated once here+    /// rather than in each suite.+    private static func noted(_ record: BackupV18Entry, fingerprint: String?) -> BackupV18Entry {+        BackupV18Entry(+            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: BackupV18Work, fingerprint: String?) -> BackupV18Work {+        BackupV18Work(+            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)+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swiftnew file mode 100644index 00000000..5d100467--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.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.+///+/// `BackupV18ArchiveTests` 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 BackupV18ImportMatrixTests {++    // 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: BackupV18Fixtures.plan(BackupV18Fixtures.composedPayload(releaseDays: [])))+        guard case .committed = result else {+            Issue.record("expected committed, got \(result)")+            return+        }++        let work = try await fixture.repository.work(id: BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.composedPayload(releaseDays: [.thursday, .monday])))+        guard case .committed = result else {+            Issue.record("expected committed, got \(result)")+            return+        }++        let work = try await fixture.repository.work(id: BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.composedPayload(releaseDays: [.friday])))+        #expect(+            try await fixture.repository.work(id: BackupV18Fixtures.composedWorkID).releaseDays+                == [.friday])++        // The same record, a second later, with the schedule cleared.+        let cleared = BackupV18Fixtures.composedPayload(releaseDays: [])+        let newer = BackupV18Payload(+            entries: cleared.entries,+            works: cleared.works.map { record in+                BackupV18Work(+                    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: BackupV18Fixtures.plan(newer))++        #expect(+            try await fixture.repository.work(id: BackupV18Fixtures.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: BackupV18Fixtures.plan(+                BackupV18Fixtures.composedPayload(releaseDays: [.friday])))++        let stale = BackupV18Fixtures.composedPayload(releaseDays: [.monday])+        let older = BackupV18Payload(+            entries: stale.entries,+            works: stale.works.map { record in+                BackupV18Work(+                    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: BackupV18Fixtures.plan(older))++        #expect(+            try await fixture.repository.work(id: BackupV18Fixtures.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.releaseDaysOmittedPayloadJSON,+            entryCount: 1, workCount: 1)++        do {+            _ = try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.citationVersionFreePayloadJSON,+            entryCount: 1, workCount: 1)+        let record = try #require(try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.unknownReleaseDayPayloadJSON,+            entryCount: 1, workCount: 1)++        do {+            _ = try BackupV18Codec.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 = BackupV18Fixtures.literalDocument(+            payload: BackupV18Fixtures.populatedReleaseDaysPayloadJSON,+            entryCount: 1, workCount: 1)+        let record = try #require(try BackupV18Codec.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 = BackupV18Fixtures.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("(18/19)"))++        // 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))+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18RestoreAssertions.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18RestoreAssertions.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18RestoreAssertions.swiftnew file mode 100644index 00000000..2301f534--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18RestoreAssertions.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 BackupV18RestoreAssertions {+    private struct Scope: Hashable {+        let workID: UUID+        let day: String+    }++    static func expectExactRecordsAndFreshNoteClears(+        before: BackupV18Payload, after: BackupV18Payload,+        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)+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swiftindex 7a29588e..cc25f3c2 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() == "18",+        #expect(try root.markerText() == "19",                 "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("18\n")+        try root.writeMarker("19\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("18\n")+            try root.writeMarker("19\n")         case .readinessMarkerWithoutAStore:             try root.createStoreDirectory()-            try root.writeMarker("18\n")+            try root.writeMarker("19\n")         case .historicalMarkerWithoutAStore:             try root.createStoreDirectory()             try root.writeHistoricalMarker()
Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swiftindex 2e019932..4c467b67 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("18\n")+        try root.writeMarker("19\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("18\n")+        try root.writeMarker("19\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("18\n")+        try root.writeMarker("19\n")         try #require(StoreMetadata.recordedVersion(at: root.storeURL) == .indeterminate)          #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready,@@ -430,7 +430,7 @@ private struct Cell: Sendable, CustomStringConvertible {         case .fifteen: try root.writeMarker("15\n")         case .sixteen: try root.writeMarker("16\n")         case .seventeen: try root.writeMarker("17\n")-        case .eighteen: try root.writeMarker("18\n")+        case .nineteen: try root.writeMarker("19\n")         case .unrecognisedText: try root.writeMarker("99\n")         case .nonUTF8: try root.writeMarkerBytes(ClassifierRoot.nonUTF8MarkerBytes)         }@@ -443,7 +443,7 @@ 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 == .eighteen, storePresent { return .ready }+        if marker == .nineteen, storePresent { return .ready }         if marker == .seventeen, storePresent { return .markerLagging(generation: "17") }         if marker == .sixteen, storePresent { return .markerLagging(generation: "16") }         if !storePresent {@@ -472,7 +472,7 @@ private enum StoreFamily: String, CaseIterable, Sendable { }  private enum MarkerAxis: String, CaseIterable, Sendable {-    case absent, four, five, six, fourteen, fifteen, sixteen, seventeen, eighteen, unrecognisedText, nonUTF8+    case absent, four, five, six, fourteen, fifteen, sixteen, seventeen, nineteen, unrecognisedText, nonUTF8 }  /// What the seeded main file is meant to record. The expectation is derived from
Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swiftindex b29a7b97..12fbc914 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 = "18\n"+private let readyMarkerBytes = "19\n"  /// The counts of a library seeded with exactly one `Site`. ///
Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swiftindex 52ebd405..9bef3cd6 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 = BackupV17Fixtures.minimalTaughtPayload()+    private static let base = BackupV18Fixtures.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 = BackupV17Fixtures.created-    ) -> BackupV17Payload {+        modifiedAt: Date = BackupV18Fixtures.created+    ) -> BackupV18Payload {         let original = base.works[0]-        let work = BackupV17Work(+        let work = BackupV18Work(             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 BackupV17Payload(+        return BackupV18Payload(             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 BackupV17Codec.encode(payload: original, metadata: BackupV17Fixtures.metadata())-        let work = try #require(try BackupV17Codec.decode(data).payload.works.first)+        let data = try BackupV18Codec.encode(payload: original, metadata: BackupV18Fixtures.metadata())+        let work = try #require(try BackupV18Codec.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 BackupV17Codec.encode(-                    payload: Self.payload(latest: number), metadata: BackupV17Fixtures.metadata())-                _ = try BackupV17Codec.decode(data)+                let data = try BackupV18Codec.encode(+                    payload: Self.payload(latest: number), metadata: BackupV18Fixtures.metadata())+                _ = try BackupV18Codec.decode(data)             }             #expect(throws: BackupCodecError.self) {-                let data = try BackupV17Codec.encode(-                    payload: Self.payload(override: number), metadata: BackupV17Fixtures.metadata())-                _ = try BackupV17Codec.decode(data)+                let data = try BackupV18Codec.encode(+                    payload: Self.payload(override: number), metadata: BackupV18Fixtures.metadata())+                _ = try BackupV18Codec.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: BackupV17Fixtures.created.addingTimeInterval(100))-        _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(local))+                                 modifiedAt: BackupV18Fixtures.created.addingTimeInterval(100))+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.plan(local))         let older = Self.payload(latest: 40, confirmation: Self.confirmedAt.addingTimeInterval(10),-                                 modifiedAt: BackupV17Fixtures.created)-        let plan = BackupV17Fixtures.plan(older)+                                 modifiedAt: BackupV18Fixtures.created)+        let plan = BackupV18Fixtures.plan(older)         _ = try await fixture.repository.confirmImport(plan: plan)-        let first = try await fixture.repository.work(id: BackupV17Fixtures.minimalWorkID)+        let first = try await fixture.repository.work(id: BackupV18Fixtures.minimalWorkID)         #expect(first.catchUp.latest == 40)-        #expect(first.modifiedAt == BackupV17Fixtures.created.addingTimeInterval(100))+        #expect(first.modifiedAt == BackupV18Fixtures.created.addingTimeInterval(100))         saves.arm()         _ = try await fixture.repository.confirmImport(plan: plan)-        let second = try await fixture.repository.work(id: BackupV17Fixtures.minimalWorkID)+        let second = try await fixture.repository.work(id: BackupV18Fixtures.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: BackupV17Fixtures.plan(recent))+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.plan(recent))         let earlier = Self.payload(latest: 30, confirmation: Self.confirmedAt,-                                   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)+                                   modifiedAt: BackupV18Fixtures.created.addingTimeInterval(50))+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.plan(earlier))+        #expect(try await fixture.repository.work(id: BackupV18Fixtures.minimalWorkID).catchUp.latest == 60)          let tied = Self.payload(latest: 75, confirmation: Self.confirmedAt.addingTimeInterval(10))-        _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(tied))-        #expect(try await fixture.repository.work(id: BackupV17Fixtures.minimalWorkID).catchUp.latest == 75)+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.plan(tied))+        #expect(try await fixture.repository.work(id: BackupV18Fixtures.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: BackupV17Fixtures.plan(Self.payload(latest: 30)))+            plan: BackupV18Fixtures.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: BackupV17Fixtures.minimalWorkID,-                title: "Different authored title", hostname: BackupV17Fixtures.minimalHost,-                timestamp: BackupV17Fixtures.created)+                in: context, id: BackupV18Fixtures.minimalWorkID,+                title: "Different authored title", hostname: BackupV18Fixtures.minimalHost,+                timestamp: BackupV18Fixtures.created)             other.genericNotes = "different authored notes"             try context.save()         }         let newer = Self.payload(latest: 80, confirmation: Self.confirmedAt.addingTimeInterval(30),-                                 modifiedAt: BackupV17Fixtures.created.addingTimeInterval(100))-        _ = try await fixture.repository.confirmImport(plan: BackupV17Fixtures.plan(newer))+                                 modifiedAt: BackupV18Fixtures.created.addingTimeInterval(100))+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.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 == BackupV17Fixtures.minimalWorkID }+                .filter { $0.id == BackupV18Fixtures.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: BackupV17Fixtures.plan(Self.payload()))+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.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 == BackupV17Fixtures.minimalWorkID })+                .first { $0.id == BackupV18Fixtures.minimalWorkID })             work.catchUpConfirmationData = Data("broken".utf8)             try context.save()         }         do {-            _ = try await fixture.repository.backupV17Snapshot()+            _ = try await fixture.repository.backupV18Snapshot()             Issue.record("expected an export refusal")-        } catch let error as BackupV17ExportError {+        } catch let error as BackupV18ExportError {             guard case .unrepresentableValue(let record, let field, _) = error else {                 Issue.record("expected named unrepresentable value, got \(error)")                 return             }-            #expect(record.contains(BackupV17Fixtures.minimalWorkID.uuidString))+            #expect(record.contains(BackupV18Fixtures.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 = BackupV17Fixtures.retiredGenerationDocument()+        let old = BackupV18Fixtures.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("(17/18)"))+        #expect(reason.contains("(18/19)"))     } }
Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swiftindex e865beae..ed01f7ef 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpRebaseRepositoryTests.swift@@ -46,13 +46,13 @@ struct CatchUpRebaseRepositoryTests {         WorkMetadataDraft(             displayTitle: work.displayTitle, typeAssignment: work.typeDisplay.assignment,             genreTags: work.genreTags, genericNotes: work.genericNotes,-            workStatus: status ?? work.workStatus, readingStatus: work.readingStatus,+            publicationEdit: status.map { .set(status: $0, returnDate: nil) } ?? .unchanged, readingStatus: work.readingStatus,             verdict: work.verdict, releaseDays: days ?? work.releaseDays,             membership: seriesID.map { SeriesMembership(seriesID: $0, position: 1) },             thumbnail: .keep)     } -    @Test("Status crossing ongoing rebases under the old schedule and note evidence")+    @Test("Pausing and resuming keeps the original confirmation and note evidence")     func statusCrossing() async throws {         for (before, after) in [             (WorkStatus.ongoing, WorkStatus.hiatus),@@ -61,18 +61,13 @@ struct CatchUpRebaseRepositoryTests {             let (fixture, id) = try seeded(status: before)             let repository = try await fixture.openForApp()             let work = try await repository.work(id: id)-            let expected = CatchUpProgress.build(-                work: work, day: CivilDay(WriteFixture.epoch, calendar: calendar()),-                calendar: calendar()).effectiveLatest             let outcome = try await repository.updateWork(                 id: id, basis: WorkEditBasis(work: work),                 draft: draft(work, status: after), calendar: calendar())             #expect(outcome == .committed)-            let updated = try #require(fixture.workRows(id: id).first?.catchUpRecord.confirmation)-            #expect(updated.latest == expected)-            #expect(updated.confirmedAtMilliseconds == MillisecondInstant.milliseconds(WriteFixture.epoch))-            #expect(updated.isEstimate)-            #expect(updated.countsUp)+            let updated = try #require(fixture.workRows(id: id).first?.catchUpRecord)+            #expect(updated == work.catchUp)+         }     } @@ -153,6 +148,9 @@ struct CatchUpRebaseRepositoryTests {             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)+        #expect(try fixture.workRows(id: id).first?.catchUpRecord == work.catchUp)+        let paused = try await repository.work(id: id)+        #expect(CatchUpProgress.build(work: paused, day: CivilDay(WriteFixture.epoch, calendar: calendar()),+                                      calendar: calendar()).effectiveLatest == expected)     } }
Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swiftindex 26a633ca..5a6951a0 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpWriterTests.swift@@ -33,7 +33,7 @@ struct CatchUpWriterTests {         row.lastChapterOverrideData = try JSONBlob.encode(first.override)         #expect(row.catchUpRecord.confirmation == nil)         #expect(row.catchUpRecord.override == first.override)-        let snapshot = LibraryRepository.snapshot(+        let snapshot = try LibraryRepository.snapshot(             row, entries: [], types: .empty, series: .empty, credits: .empty,             history: .empty)         #expect(snapshot.catchUp.confirmation == nil)
Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swiftindex 9850df7f..b328b586 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) == ["18.0.0"],+        #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["19.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) == "18",+        #expect(try markerContent(cfg) == "19",                 "an empty store has nothing to bring forward and is certified at birth (Q26)")         withExtendedLifetime(dir) {}     }
Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swiftindex 8400c561..c4529336 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 `BackupV17ImportTests`, which ask the+/// Shared by `EmptyLibraryTests` and `BackupV18ImportTests`, 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".
Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterDuplicateMachineryTests.swiftindex d3c579d2..9f9a72c4 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: BackupV17ExportError.self) {-            _ = try await fixture.repository.backupV17Snapshot()+        await #expect(throws: BackupV18ExportError.self) {+            _ = try await fixture.repository.backupV18Snapshot()         }         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 `BackupV17Character` carries as its+    /// `CharacterGroup.modifiedAt` is what `BackupV18Character` 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")
Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swiftindex afc3f2b3..e47a00d7 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swiftindex 76a7a974..9ff63689 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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #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 BackupV17Codec.encode(+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))-        let decoded = try BackupV17Codec.decode(encoded)+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+        let decoded = try BackupV18Codec.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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #expect(payload.titlePatterns.count == 1)         #expect(payload.titlePatterns.first?.isActive == true)         #expect(payload.sites.first?.mode == .taught)-        let encoded = try BackupV17Codec.encode(+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))-        _ = try BackupV17Codec.decode(encoded)+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+        _ = try BackupV18Codec.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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()          #expect(payload.urlRules.count == 1)         #expect(payload.urlRules.first?.id == shared)         #expect(payload.urlRules.first?.isCurrent == true)-        let encoded = try BackupV17Codec.encode(+        let encoded = try BackupV18Codec.encode(             payload: payload,-            metadata: BackupV17Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))-        _ = try BackupV17Codec.decode(encoded)+            metadata: BackupV18Metadata(appBuild: "1", exportedAt: RuleGroupStore.epoch))+        _ = try BackupV18Codec.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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         let container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         self.init(context: ModelContext(container))         retained = container
Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swiftindex a8e9a5b6..d6d0f643 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: AsterismSchemaV18.self)+            let schema = Schema(versionedSchema: AsterismSchemaV19.self)             container = try ModelContainer(-                for: schema, migrationPlan: AsterismV18MigrationPlan.self,+                for: schema, migrationPlan: AsterismV19MigrationPlan.self,                 configurations: [                     ModelConfiguration(                         "AsterismV3", schema: schema,
Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swiftindex 6c61fa1b..0e823fe6 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: AsterismSchemaV18.self)+            let schema = Schema(versionedSchema: AsterismSchemaV19.self)             container = try ModelContainer(-                for: schema, migrationPlan: AsterismV18MigrationPlan.self,+                for: schema, migrationPlan: AsterismV19MigrationPlan.self,                 configurations: [                     ModelConfiguration(                         "AsterismV3", schema: schema,
Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swiftindex fca697a5..bd2e5ff3 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swiftindex f5c10052..2ad52f00 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 BackupV17Codec.encode(-            payload: try await fixture.repository.backupV17Snapshot(),-            metadata: BackupV17Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))+        let archive = try BackupV18Codec.encode(+            payload: try await fixture.repository.backupV18Snapshot(),+            metadata: BackupV18Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))          let restored = try await M5Fixture()         try await restored.repository.confirmImport(plan: try BackupImporter.plan(from: archive))@@ -377,7 +377,7 @@ struct CrossSiteDuplicateWorkloadTests {             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],                 genericNotes: "reader prose",-                workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          #expect(outcome == .committed)
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swiftindex 8f5c81b3..485f4f92 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 BackupV17Codec.encode(-            payload: try await source.repository.backupV17Snapshot(),+        let archive = try BackupV18Codec.encode(+            payload: try await source.repository.backupV18Snapshot(),             metadata: BackupGoldenLibrary.metadata)          let target = try await M5Fixture()
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swiftindex 42a297af..8a0acb70 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         seed = ModelContext(container)         if let saveStrategy {
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swiftindex 16cd0294..8f5b349c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift@@ -49,6 +49,37 @@ struct DuplicateResolutionTests {         #expect(try moved.isMarked(workID: survivorID, day: day.description))     } +    @Test("Choosing a duplicate publication state keeps its return and pause evidence")+    func publicationStateChoice() async throws {+        let library = try ResolutionFixture()+        let first = try WorkPublicationState(status: .hiatus, currentPause: .init(+            start: nil, returnDate: CivilDateCodec.parse("2026-10-01")!))+        let chosen = try WorkPublicationState(status: .hiatus, closedPauses: [+            .init(start: nil, end: CivilDateCodec.parse("2026-08-20")!)],+            currentPause: .init(start: CivilDateCodec.parse("2026-09-01")!,+                                returnDate: CivilDateCodec.parse("2026-10-10")!))+        let survivor = UUID()+        try library.seed { store in+            store.insertSite(hostname: "dup.example")+            let a = store.insertWork(id: survivor, title: "Serial", offset: 0, workStatus: .hiatus)+            let b = store.insertWork(title: "Serial", offset: 40, workStatus: .hiatus)+            a.publicationStateData = try first.canonicalData()+            b.publicationStateData = try chosen.canonicalData()+            // The envelope is authoritative even when its compatibility mirror differs.+            b.workStatusRaw = WorkStatus.finished.rawValue+        }+        let repository = try await library.openForApp()+        let preview = try await repository.projectDuplicateResolution(setKey: Self.onlyWorkSetKey(library))+        guard case .work(_, let variants, let fields, _) = preview else { Issue.record("Expected Work choices"); return }+        #expect(fields.contains(.publicationState))+        let choice = try #require(variants.first { $0.publicationState == chosen })+        #expect(choice.workStatus == .hiatus)+        #expect(try await repository.commitDuplicateResolution(preview, choosing: choice.id) == .committed(survivorID: survivor))+        let state = try #require(try library.readContext().fetch(FetchDescriptor<Work>()).first?.decodedPublicationState())+        #expect(state == chosen)+        #expect(try await repository.work(id: survivor).publicationState == chosen)+    }+     // MARK: - Projection (Req 4.2)      @Test("The sheet presents every variant, the fields they differ in, and preselects the leading one")
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swiftindex 65950d18..0ade8e33 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swiftindex 0aa455e0..bae82bac 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift@@ -461,14 +461,14 @@ struct EmptyLibraryTests {         let fixture = try await EmptyLibraryFixture()         try await fixture.seedGoldenLibrary() -        let before = try await fixture.repository.backupV17Snapshot()+        let before = try await fixture.repository.backupV18Snapshot()         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.backupV17Snapshot()+        let after = try await fixture.repository.backupV18Snapshot() -        try BackupV17RestoreAssertions.expectExactRecordsAndFreshNoteClears(+        try BackupV18RestoreAssertions.expectExactRecordsAndFreshNoteClears(             before: before, after: after)         await fixture.tearDown()     }@@ -491,10 +491,10 @@ struct EmptyLibraryTests {         let fixture = try await EmptyLibraryFixture(saveStrategy: strategy)         try await fixture.seedGoldenLibrary() -        let archive = try await fixture.repository.backupV17Snapshot()+        let archive = try await fixture.repository.backupV18Snapshot()         _ = try await fixture.repository.emptyLibrary()         try await fixture.repository.confirmImport(plan: EmptyLibraryFixture.plan(archive))-        let restored = try await fixture.repository.backupV17Snapshot()+        let restored = try await fixture.repository.backupV18Snapshot()         let stamps = try await fixture.repository.modificationStampsForTesting()          strategy.arm()@@ -504,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.backupV17Snapshot() == restored)+        #expect(try await fixture.repository.backupV18Snapshot() == restored)         #expect(try await fixture.repository.modificationStampsForTesting() == stamps)         await fixture.tearDown()     }@@ -516,7 +516,7 @@ struct EmptyLibraryTests {         let fixture = try await EmptyLibraryFixture()         try await fixture.seedGoldenLibrary() -        let archive = try await fixture.repository.backupV17Snapshot()+        let archive = try await fixture.repository.backupV18Snapshot()         let late = try await fixture.repository.capture(             CaptureDraft(                 captureTitle: "Chapter 9 - After the export",@@ -561,7 +561,7 @@ struct EmptyLibraryTests {             id: work.id,             draft: WorkMetadataDraft(                 displayTitle: "A Work", typeAssignment: .none, genreTags: [],-                genericNotes: "", workStatus: .ongoing, readingStatus: .reading, verdict: "",+                genericNotes: "", publicationEdit: .unchanged, readingStatus: .reading, verdict: "",                 releaseDays: [], membership: nil, thumbnail: .keep), calendar: .current)         #expect(try await fixture.repository.work(id: work.id).typeDisplay == .untyped)         await fixture.tearDown()@@ -809,7 +809,7 @@ private final class EmptyLibraryFixture {     func seedGoldenLibrary() async throws {         try await repository.confirmImport(             plan: try BackupImporter.plan(-                from: try BackupV17Codec.encode(+                from: try BackupV18Codec.encode(                     payload: BackupGoldenLibrary.payload,                     metadata: BackupGoldenLibrary.metadata)))     }@@ -858,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: BackupV17Payload) -> BackupImportPlan {+    static func plan(_ payload: BackupV18Payload) -> BackupImportPlan {         BackupImportPlan(             metadata: BackupImportMetadata(-                formatVersion: BackupV17Document.formatVersion,-                schemaVersion: BackupV17Document.schemaVersion,+                formatVersion: BackupV18Document.formatVersion,+                schemaVersion: BackupV18Document.schemaVersion,                 appBuild: "empty-library-test",                 exportedAt: BackupGoldenLibrary.created, capabilityGate: "multi-site",                 entryCount: payload.entries.count, workCount: payload.works.count),
Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EnumTolerancePolicyTests.swiftindex fdf13cc8..da1b30ae 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.backupV17Snapshot()+            _ = try await repository.backupV18Snapshot()             Issue.record("the export archived an unrepresentable value")-        } catch let error as BackupV17ExportError {+        } catch let error as BackupV18ExportError {             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.backupV17Snapshot()+            _ = try await repository.backupV18Snapshot()             Issue.record("the export archived an unreadable citation blob")-        } catch let error as BackupV17ExportError {+        } catch let error as BackupV18ExportError {             guard case .unrepresentableValue(_, let refused, _) = error else {                 Issue.record("expected .unrepresentableValue, got \(error)")                 return
Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swiftindex 5dc7afab..de947eb1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/FanOutWriteTests.swift@@ -269,7 +269,7 @@ struct FanOutWriteTests {                 displayTitle: "Renamed",                 typeAssignment: .configured(Self.fannedTypeID), genreTags: ["fantasy"],                 genericNotes: "reader prose",-                workStatus: .finished, readingStatus: .finished,+                publicationEdit: .set(status: .finished, returnDate: nil), readingStatus: .finished,                 verdict: "  a fine ending  ", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current) @@ -315,7 +315,7 @@ struct FanOutWriteTests {             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],+                publicationEdit: .unchanged, readingStatus: .toRead, verdict: "", releaseDays: [],                 membership: nil, thumbnail: .keep), calendar: .current)          #expect(outcome == .committed)@@ -348,7 +348,7 @@ struct FanOutWriteTests {             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .ongoing, readingStatus: .reading, verdict: "   ", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "   ", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          #expect(outcome == .committed)@@ -379,7 +379,7 @@ struct FanOutWriteTests {          let work = try await repository.work(id: workID) -        #expect(work.workStatus == .hiatus)+        #expect(work.authoredWorkStatus == .hiatus)         #expect(work.readingStatus == .abandoned)         #expect(work.verdict == "stalled")     }@@ -407,7 +407,7 @@ struct FanOutWriteTests {             draft: WorkMetadataDraft(                 displayTitle: "Renamed", typeAssignment: .none, genreTags: [],                 genericNotes: "overwrite",-                workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          guard case .conflict(.torn) = outcome else {@@ -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 = BackupV17Entry(+        let entry = BackupV18Entry(             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 = BackupV17Site(+        let site = BackupV18Site(             hostname: "dup.example", displayName: "Dup", mode: .untaught)         let payload = BackupImportPayload(             entries: [entry], works: [], sites: [site], titlePatterns: [], urlRules: [])
Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FixtureArchiveGeneratorTests.swiftindex a747d26d..3e603cf3 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 `BackupV17Exporter` — the same-/// `backupV17Snapshot()` → `BackupV17Codec.encode` → decode-validate → write path+/// The archive is produced through the real `BackupV18Exporter` — the same+/// `backupV18Snapshot()` → `BackupV18Codec.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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(repository: repository, stagingDirectory: staging)         let result = try await exporter.export(-            metadata: BackupV17Metadata(appBuild: "fixture-5k", exportedAt: exportedAt))+            metadata: BackupV18Metadata(appBuild: "fixture-5k", exportedAt: exportedAt))         withExtendedLifetime(container) {}          try FileManager.default.createDirectory(
Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-17-18-golden.json Added
Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-18-19-golden.json Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-18-19-golden.json b/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-18-19-golden.jsonnew file mode 100644index 00000000..3e0fbd30--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/Fixtures/backup-18-19-golden.json@@ -0,0 +1 @@+{"appBuild":"golden","backupFormatVersion":18,"capabilityGate":"multi-site","checksum":"d1b749a1808cab1f0e580ec42ecf7c22b9beecc2dd8027beecad1b9c714e1632","databaseSchemaVersion":19,"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","publicationState":{"closedPauses":[{"end":"2026-08-10"}],"currentPause":{"returnDate":"2026-09-10","start":"2026-09-01"},"status":"hiatus","version":1},"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}\ No newline at end of file
Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swiftindex 4740985d..090464c8 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 = "18\n"+    private static let markerContents = "19\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", "AsterismSchemaV18",-            "AsterismV17MigrationPlan", "AsterismV18MigrationPlan",+            "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19",+            "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "AsterismV19MigrationPlan",             "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> = [-            "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",+            "BackupV18Entry", "BackupV18Site", "BackupV18TitlePattern", "BackupV18URLRule",+            "BackupV18Work", "BackupV18WorkType", "BackupV18Membership", "BackupV18DistinctPair",+            "BackupV18Character", "BackupV18Codec", "BackupV18Series", "BackupV18Link",+            "BackupV18Document", "BackupV18ExportError", "BackupV18Exporter", "BackupV18Metadata",+            "BackupV18Payload", "BackupV18ReferenceValidator",+            "BackupV18SnapshotProviding", "BackupV18Suppression",+            "BackupV18Creator", "BackupV18CreatorRole", "BackupV18Credit",+            "BackupV18Place", "BackupV18PlaceSuppression", "BackupV18NoEpisodeAction",+            "backupV18Snapshot",             "importedV2", "importedV2Path",-            "mapV17EntryRecord", "mapV17SiteRecord", "mapV17TitlePatternRecord",-            "mapV17URLRuleRecord", "mapV17WorkRecord",-            "mapV17CharacterRecord", "mapV17SuppressionRecord",-            "mapV17PlaceRecord", "mapV17PlaceSuppressionRecord",-            "mapV17CreatorRecords", "mapV17CreatorRoleRecords",-            "projectV17Payload",+            "mapV18EntryRecord", "mapV18SiteRecord", "mapV18TitlePatternRecord",+            "mapV18URLRuleRecord", "mapV18WorkRecord",+            "mapV18CharacterRecord", "mapV18SuppressionRecord",+            "mapV18PlaceRecord", "mapV18PlaceSuppressionRecord",+            "mapV18CreatorRecords", "mapV18CreatorRoleRecords",+            "projectV18Payload",         ]         /// 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", "AsterismSchemaV18",+                "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19",             ],             "the package declares versioned schemas \(declared); Req 3.3 allows only ones a plan references") -        let referenced = AsterismV18MigrationPlan.schemas.map { String(describing: $0) }+        let referenced = AsterismV19MigrationPlan.schemas.map { String(describing: $0) }         #expect(-            referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18"],+            referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19"],             "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(-            AsterismV18MigrationPlan.stages.count == 2,+            AsterismV19MigrationPlan.stages.count == 3,             "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(-            AsterismSchemaV18.versionIdentifier == Schema.Version(18, 0, 0),+            AsterismSchemaV19.versionIdentifier == Schema.Version(19, 0, 0),             "the live schema's version stamp is what every recorded store is compared against")     } 
Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swiftindex bd80aea0..4d73575b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift@@ -268,7 +268,7 @@ struct GroupFetchTests {         #expect(group.carrier === carrier)         #expect(group.variantIDs == before.variantIDs)         #expect(group.authoredContent == before.authoredContent)-        let row = LibraryRepository.snapshot(+        let row = try LibraryRepository.snapshot(             bare, entries: [], types: .empty, series: .empty, credits: .empty,             history: .empty)         #expect(row.catchUp.confirmation == newerConfirmation)@@ -294,12 +294,12 @@ private final class GroupStore {         directory = FileManager.default.temporaryDirectory             .appending(path: "AsterismGroupFetch-\(UUID())", directoryHint: .isDirectory)         try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)-        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swiftindex 3317f151..c8c4cca1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift@@ -693,13 +693,13 @@ struct GroupOrderingTests {             VariantID(components: portrait.orderComponents)                 == VariantID(components: WorkAuthoredContent(                     thumbnail: ThumbnailIdentity(shape: .portrait, digest: "aaa")).orderComponents))-        // The two components sit directly before V15's release days, and+        // The two components precede the release days and publication envelope, and         // absence encodes distinctly from a present empty value, so "no cover"         // cannot key as one.         #expect(portrait.orderComponents.count == bare.orderComponents.count)-        #expect(bare.orderComponents.dropLast(1).suffix(2).map(\.canonicalToken) == ["a~", "a~"])+        #expect(bare.orderComponents.dropLast(2).suffix(2).map(\.canonicalToken) == ["a~", "a~"])         #expect(-            portrait.orderComponents.dropLast(1).suffix(2).map(\.canonicalToken)+            portrait.orderComponents.dropLast(2).suffix(2).map(\.canonicalToken)                 == ["a=portrait", "a=aaa"])     } @@ -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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swiftindex a6c40599..c58bd7c7 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         return try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])     } 
Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swiftindex 0339335c..4104f977 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift@@ -32,7 +32,7 @@ struct IntentReadsTests {             let summary = try #require(summaries.first { $0.id == work.id })             #expect(summary.displayTitle == work.displayTitle)             #expect(summary.readingStatus == work.readingStatus)-            #expect(summary.workStatus == work.workStatus)+            #expect(summary.workStatus == work.authoredWorkStatus)         }         // The torn group really is torn: otherwise the case proves nothing.         #expect(listed.first { $0.id == torn.id }?.groupState.isTorn == true)@@ -237,7 +237,7 @@ struct IntentReadsTests {         }         #expect(created.displayTitle == "A Serial")         #expect(created.readingStatus == .toRead)-        #expect(created.workStatus == .ongoing)+        #expect(created.authoredWorkStatus == .ongoing)         #expect(created.memberships.map(\.hostname) == ["example.com"])         #expect(created.memberships.first?.workURLString == "https://Example.com/story?id=7")         let counts = try await fixture.repository.debugCounts()
Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swiftindex a5f41d2c..5a6cf22f 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         return try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])     } 
Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swiftindex 9e35fbe0..6c2188df 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swiftindex e481cc37..b423cd7a 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let container = try ModelContainer(             for: schema,             configurations: [
Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4BulkChunkPerformanceTests.swiftindex 003f988e..0f5c9d62 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 -> BackupV17Payload {+    static func exportedFixturePayload() async throws -> BackupV18Payload {         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.backupV17Snapshot()+        let payload = try await repository.backupV18Snapshot()         withExtendedLifetime(container) {}         return payload     }
Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4DuplicateScalePerformanceTests.swiftindex 67caea65..f21c4f22 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 `BackupV17Exporter.export`: the encode,+    /// The *projection* is timed, not `BackupV18Exporter.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.backupV17Snapshot()+            _ = try await repository.backupV18Snapshot()         }         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 = BackupV17Exporter(repository: repository, stagingDirectory: staging)+        let exporter = BackupV18Exporter(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: BackupV17Metadata(appBuild: "m4-performance", exportedAt: Date()))+                metadata: BackupV18Metadata(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 BackupV17Exporter(+        let exported = try await BackupV18Exporter(             repository: repository, stagingDirectory: staging-        ).export(metadata: BackupV17Metadata(appBuild: "m4-performance", exportedAt: Date()))+        ).export(metadata: BackupV18Metadata(appBuild: "m4-performance", exportedAt: Date()))         await repository.shutdown()         return (exported.fileURL, try fileSize(of: exported.fileURL))     }
Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swiftindex 08a2ab8c..a264053a 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) == "18",+        #expect(try markerContent(cfg) == "19",                 "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) == "18", "and the open leaves the marker as it found it")+        #expect(try markerContent(cfg) == "19", "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) == "18",+        #expect(try markerContent(cfg) == "19",                 "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) == "18")+        #expect(try markerContent(cfg) == "19")          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, "18\n")+        try writeMarker(cfg, "19\n")         _ = try await LibraryRepository.openForExtension(cfg)-        #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["18.0.0"],+        #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["19.0.0"],                 "the same store converts once the marker check passes")     } 
Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swiftindex 3a2b608f..e8938b08 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("18\n")+        try root.writeMarker("19\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() == "18")+        #expect(try root.markerText() == "19")         #expect(try V4RecordedStoreFixture.recordedModelVersions(at: root.configuration.storeURL)-                == ["18.0.0"], "the store the arm opened is recorded at the version it converted to")+                == ["19.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() == "18")+        #expect(try root.markerText() == "19")         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() == "18")+        #expect(try root.markerText() == "19")         withExtendedLifetime(root) {}     } @@ -217,7 +217,7 @@ struct MarkerGenerationSeventeenTests {             Issue.record("a diagnosable library must still open, got \(result)")             return         }-        #expect(try root.markerText() == "18")+        #expect(try root.markerText() == "19")         #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() == "18")+        #expect(try root.markerText() == "19")          let (result, _) = try await LibraryRepository.openForExtension(root.configuration)         guard case .ready = result else {
Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swiftindex 4d64372b..d5beb87d 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipTestSupport.swiftindex dc3df47a..4fda346f 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 `BackupV17Exporter`+    /// Exports and decode-validates, which is exactly what `BackupV18Exporter`     /// 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 backupV17Snapshot()-            let encoded = try BackupV17Codec.encode(+            let payload = try await backupV18Snapshot()+            let encoded = try BackupV18Codec.encode(                 payload: payload,-                metadata: BackupV17Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))-            _ = try BackupV17Codec.decode(encoded)+                metadata: BackupV18Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))+            _ = try BackupV18Codec.decode(encoded)         } catch {             Issue.record(                 comment ?? "the archive is not legal: \(error)", sourceLocation: sourceLocation)
Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swiftindex 1ab3e506..06178919 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swiftindex 742a296f..e081d901 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 == "18")+        #expect(call.markerVersion == "19")         #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 == "18")+        #expect(log.calls.first?.markerVersion == "19")         #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 == "18")+        #expect(log.calls.first?.markerVersion == "19")         #expect(await repository.mirroring.isMirroring)         withExtendedLifetime(dir) {}     }
Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swiftindex ab7376ec..38e31221 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(AsterismSchemaV18.models.map { String(describing: $0) })+        let declared = Set(AsterismSchemaV19.models.map { String(describing: $0) })         #expect(             phased == declared,             """@@ -274,6 +274,30 @@ struct ModelContractTests {         }     } +    @Test("V19 adds only an optional publication-state blob")+    func publicationBlobIsTheOnlyV19Delta() throws {+        let live = Schema(versionedSchema: AsterismSchemaV19.self)+        let frozen = Schema(versionedSchema: AsterismSchemaV18.self)+        #expect(Set(live.entities.map(\.name)) == Set(frozen.entities.map(\.name)))+        for name in live.entities.map(\.name) {+            var columns = Self.propertyShapes(of: name, in: live)+            let previous = Self.propertyShapes(of: name, in: frozen)+            if name == "Work" {+                #expect(columns.removeValue(forKey: "publicationStateData") != nil)+                let entity = try #require(live.entities.first { $0.name == name })+                let attribute = try #require(entity.attributes.first { $0.name == "publicationStateData" })+                #expect(attribute.isOptional)+                #expect(!attribute.isUnique)+                #expect(attribute.valueType == Data.self || attribute.valueType == Data?.self)+                #expect(!attribute.options.contains(.externalStorage))+            }+            #expect(columns == previous, "Unexpected V18 -> V19 change in \(name)")+        }+        #expect(Work(displayTitle: "Legacy", timestamp: .distantPast).publicationStateData == nil)+        #expect(AsterismV19MigrationPlan.schemas.map { $0.versionIdentifier.major } == [16, 17, 18, 19])+        #expect(AsterismV19MigrationPlan.stages.count == 3)+    }+     /// `releaseDaysRaw` as CloudKit will materialise it and as the store will     /// lay it out (`update-schedule` Q27): **defaulted, non-optional,     /// non-unique** — the shape `genreTags` has had since V5, and the shape that@@ -296,7 +320,7 @@ struct ModelContractTests {         work.releaseDays = [.sunday, .monday, .sunday]         #expect(work.releaseDaysRaw == ["monday", "sunday"], "the setter writes canonical order") -        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.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 +374,7 @@ struct ModelContractTests {         #expect(work.thumbnailShape == nil)         #expect(work.thumbnailIdentity == nil) -        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.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 +466,7 @@ struct ModelContractTests {          // The schema's own view: nothing unique, no relationship on either new         // table, and the owner a column rather than a reference.-        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.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 +543,7 @@ struct ModelContractTests {          // The schema's own view: nothing unique, no relationships on any of the         // three, and every foreign reference a column rather than a reference.-        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.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 +584,7 @@ struct ModelContractTests {          // The schema's own view: nothing unique, no relationships on either new         // table, and the two link ends are UUID columns rather than references.-        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.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 +717,7 @@ struct ModelContractTests {     /// V8-era half of this pin needed an allowlist and this one does not.     @Test("No dropped column is in the live schema")     func droppedColumnsAreGoneFromTheSchema() {-        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         var propertiesByEntity: [String: Set<String>] = [:]         for entity in schema.entities {             propertiesByEntity[entity.name, default: []]@@ -774,7 +798,7 @@ struct ModelContractTests {         #expect(             declaringSnapshots.sorted() == [                 "AsterismSchemaV16.swift", "AsterismSchemaV17.swift",-                "AsterismSchemaV18.swift",+                "AsterismSchemaV18.swift", "AsterismSchemaV19.swift",             ],             """             the package declares versioned schemas in \(declaringSnapshots.sorted()); \@@ -1091,7 +1115,7 @@ private struct ModelFixture {     /// The live schema, in memory. It was `AsterismSchemaV2` — a schema no     /// library was written by, which is exactly the divergence Req 4.1 is about.     init() throws {-        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             schema: schema,             isStoredInMemoryOnly: true,
Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swiftindex cc7f5330..4846f1d7 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", "AsterismSchemaV17Models.swift",+            "AsterismSchemaV16.swift", "AsterismSchemaV17Models.swift", "AsterismSchemaV18Models.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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReviewFixTests.swiftindex 2915621c..6d53dbfa 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 = BackupV17URLRule(+        let rule = BackupV18URLRule(             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: BackupV17ExportError.self) {+        #expect(throws: BackupV18ExportError.self) {             try LibraryRepository.requireCitationsResolve(                 entries: [entry], memberships: [], titlePatterns: [], urlRules: [rule])         }         // Same rule, taught for the Entry's own site: legal.-        let sameSite = BackupV17URLRule(+        let sameSite = BackupV18URLRule(             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 = BackupV17TitlePattern(+        let pattern = BackupV18TitlePattern(             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: BackupV17ExportError.self) {+        #expect(throws: BackupV18ExportError.self) {             try LibraryRepository.requireCitationsResolve(                 entries: [entry], memberships: [], titlePatterns: [pattern], urlRules: [])         }@@ -303,9 +303,9 @@ struct MultiSiteReviewFixTests {      private static func wireEntry(         hostname: String, citations: EntryCitations-    ) -> BackupV17Entry {+    ) -> BackupV18Entry {         let url = "https://\(hostname)/one"-        return BackupV17Entry(+        return BackupV18Entry(             id: UUID(), captureTitle: "Chapter", captureTitleSource: .host, rawURL: url,             canonicalURL: nil, hostname: hostname, entryIdentityKey: url,             conservativeIdentityKey: url, identityBasis: .conservative, urlWorkIdentity: nil,
Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swiftindex ed71e10f..981b4a9e 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRepositoryTests.swift@@ -291,10 +291,10 @@ struct NoEpisodeRepositoryTests {     @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 payload = BackupV18Fixtures.composedPayload()+        let plan = BackupV18Fixtures.plan(payload)         let entryRecord = try #require(payload.entries.first)-        let workID = BackupV17Fixtures.composedWorkID+        let workID = BackupV18Fixtures.composedWorkID         let calendar = Calendar.current         let day = CivilDay(entryRecord.lastSharedAt, calendar: calendar)         _ = try await fixture.repository.confirmImport(plan: plan)
Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swiftindex a3affda3..9e5ffd09 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift@@ -9,7 +9,7 @@ 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 live = Schema(versionedSchema: AsterismSchemaV19.self)         let frozenNames = Set(frozen.entities.map(\.name))         let liveNames = Set(live.entities.map(\.name))         #expect(liveNames.subtracting(frozenNames) == ["NoEpisodeAction"])@@ -19,15 +19,15 @@ struct NoEpisodeStorageTests {         #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)+        #expect(AsterismV19MigrationPlan.schemas.map { $0.versionIdentifier.major } == [16, 17, 18, 19])+        #expect(AsterismV19MigrationPlan.stages.count == 3)     }      @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 schema = Schema(versionedSchema: AsterismSchemaV19.self)         let config = ModelConfiguration(schema: schema, url: url)         let workID = UUID()         let action = try NoEpisodeHistory.Action(workID: workID, key: "mark/\(UUID().uuidString)",@@ -69,7 +69,7 @@ struct NoEpisodeStorageTests {      @Test("an unrelated damaged action does not break a targeted history read")     func malformedActionIsScopedToItsWork() throws {-        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let container = try ModelContainer(             for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)])         let context = ModelContext(container)@@ -96,16 +96,16 @@ struct NoEpisodeStorageTests {         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(+        let record = try BackupV18NoEpisodeAction(mark)+        let payload = BackupV18Payload(             entries: [], works: [], sites: [], titlePatterns: [], urlRules: [],             noEpisodeActions: [record])-        let encoded = try BackupV17Codec.encode(-            payload: payload, metadata: BackupV17Metadata(+        let encoded = try BackupV18Codec.encode(+            payload: payload, metadata: BackupV18Metadata(                 appBuild: "test", exportedAt: Date(timeIntervalSince1970: 0)))-        let decoded = try BackupV17Codec.decode(encoded)-        #expect(decoded.backupFormatVersion == 17)-        #expect(decoded.databaseSchemaVersion == 18)+        let decoded = try BackupV18Codec.decode(encoded)+        #expect(decoded.backupFormatVersion == 18)+        #expect(decoded.databaseSchemaVersion == 19)         #expect(decoded.payload.noEpisodeActions == [record])          var object = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any])@@ -113,19 +113,19 @@ struct NoEpisodeStorageTests {         body.removeValue(forKey: "noEpisodeActions")         object["payload"] = body         #expect(throws: BackupCodecError.self) {-            try BackupV17Codec.decode(JSONSerialization.data(withJSONObject: object))+            try BackupV18Codec.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(+        let conflictingPayload = BackupV18Payload(             entries: [], works: [], sites: [], titlePatterns: [], urlRules: [],-            noEpisodeActions: [record, try BackupV17NoEpisodeAction(conflict)])-        let conflicting = try BackupV17Codec.encode(-            payload: conflictingPayload, metadata: BackupV17Metadata(+            noEpisodeActions: [record, try BackupV18NoEpisodeAction(conflict)])+        let conflicting = try BackupV18Codec.encode(+            payload: conflictingPayload, metadata: BackupV18Metadata(                 appBuild: "test", exportedAt: Date(timeIntervalSince1970: 0)))-        #expect(throws: BackupCodecError.self) { try BackupV17Codec.decode(conflicting) }+        #expect(throws: BackupCodecError.self) { try BackupV18Codec.decode(conflicting) }     }      @Test("archive import unions both arrival orders and an old repeat cannot revive a mark")@@ -139,11 +139,11 @@ struct NoEpisodeStorageTests {             day: "2026-09-29", kind: .clear, observedClearKeys: [])          func plan(_ action: NoEpisodeHistory.Action) throws -> BackupImportPlan {-            let payload = BackupV17Payload(+            let payload = BackupV18Payload(                 entries: [], works: [], sites: [], titlePatterns: [], urlRules: [],-                noEpisodeActions: [try BackupV17NoEpisodeAction(action)])-            let bytes = try BackupV17Codec.encode(-                payload: payload, metadata: BackupV17Metadata(+                noEpisodeActions: [try BackupV18NoEpisodeAction(action)])+            let bytes = try BackupV18Codec.encode(+                payload: payload, metadata: BackupV18Metadata(                     appBuild: "test", exportedAt: Date(timeIntervalSince1970: 0)))             return try BackupImporter.plan(from: bytes)         }
Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swiftindex 2e1d0332..3f91af7f 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PendingCaptureDrainTests.swift@@ -585,7 +585,7 @@ struct PendingCaptureDrainTests {             id: work.id,             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "",-                workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],+                publicationEdit: .unchanged, readingStatus: .toRead, verdict: "", releaseDays: [],                 membership: nil, thumbnail: .keep), calendar: .current)         _ = try await fixture.preserve(             "https://ex.com/read/1", sharedAt: DrainFixture.shareInstant)
Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PlaceDuplicateMachineryTests.swiftindex c041666c..14efce5a 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: BackupV17ExportError.self) {-            _ = try await fixture.repository.backupV17Snapshot()+        await #expect(throws: BackupV18ExportError.self) {+            _ = try await fixture.repository.backupV18Snapshot()         }         withExtendedLifetime(fixture) {}     }
Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swiftindex 5446a8fa..6f860aff 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PostCollapseRedirectTests.swift@@ -212,7 +212,7 @@ struct PostCollapseRedirectTests {             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: ["fantasy"],                 genericNotes: "reader prose",-                workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          #expect(outcome == .committed)@@ -259,7 +259,7 @@ struct PostCollapseRedirectTests {             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],                 genericNotes: "reader prose",-                workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          #expect(outcome == .committed)@@ -297,7 +297,7 @@ struct PostCollapseRedirectTests {             draft: WorkMetadataDraft(                 displayTitle: "The Reader's Rename", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          guard case .conflict(.survivorDiverged(_, let survivorID)) = outcome else {@@ -337,7 +337,7 @@ struct PostCollapseRedirectTests {             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],                 genericNotes: "reader prose",-                workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          guard case .conflict(.survivorDiverged(_, let survivorID)) = outcome else {@@ -381,7 +381,7 @@ struct PostCollapseRedirectTests {             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .finished, readingStatus: .finished,+                publicationEdit: .set(status: .finished, returnDate: nil), readingStatus: .finished,                 verdict: "a fine ending", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current) @@ -413,7 +413,7 @@ struct PostCollapseRedirectTests {             draft: WorkMetadataDraft(                 displayTitle: "The Reader's Rename", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          #expect(outcome == .committed)
Packages/AsterismCore/Tests/AsterismCoreTests/PublicationArchiveTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationArchiveTests.swiftnew file mode 100644index 00000000..a7ebcca5--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationArchiveTests.swift@@ -0,0 +1,131 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Publication archive 18/19", .serialized)+struct PublicationArchiveTests {+    private static let pending = #"{"closedPauses":[],"currentPause":{"returnDate":"2026-10-10","start":"2026-09-01"},"status":"hiatus","version":1}"#+    private static let elapsed = #"{"closedPauses":[{"end":"2026-08-10","start":"2026-08-01"}],"currentPause":{"returnDate":"2026-09-10","start":"2026-09-01"},"status":"hiatus","version":1}"#+    private static let unknown = #"{"closedPauses":[],"currentPause":{"returnDate":"2026-10-10"},"status":"hiatus","version":1}"#++    private static func document(state: String?, status: String = "hiatus") throws -> Data {+        let base = BackupV18Fixtures.minimalTaughtPayload()+        var payload = String(decoding: try BackupCanonicalJSON.encoder().encode(base), as: UTF8.self)+        payload = payload.replacingOccurrences(of: #""workStatus":"ongoing""#, with: #""workStatus":"\#(status)""#)+        if let state {+            payload = payload.replacingOccurrences(of: #""readingStatus":"#,+                with: #""publicationState":\#(state),"readingStatus":"#)+        }+        return BackupV18Fixtures.literalDocument(payload: payload,+            entryCount: base.entries.count, workCount: base.works.count)+    }++    @Test("Pending, elapsed, repeated and unknown-start evidence survives import/export", arguments: [pending, elapsed, unknown])+    func roundTrip(state: String) async throws {+        let fixture = try await M5Fixture()+        let original = try WorkPublicationState.decode(Data(state.utf8))+        _ = try await fixture.repository.confirmImport(plan: BackupImporter.plan(from: Self.document(state: state)))+        let work = try await fixture.repository.work(id: BackupV18Fixtures.minimalWorkID)+        #expect(work.publicationState == original)+        #expect(work.authoredWorkStatus == .hiatus)+        let payload = try await fixture.repository.backupV18Snapshot()+        let encoded = try BackupCanonicalJSON.encoder().encode(payload)+        #expect(String(decoding: encoded, as: UTF8.self).contains(#""publicationState":"#))+        let restored = try await M5Fixture()+        let data = try BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata())+        _ = try await restored.repository.confirmImport(plan: BackupImporter.plan(from: data))+        #expect(try await restored.repository.work(id: work.id).publicationState == original)+    }++    @Test("Missing state stays legacy nil and an older envelope refuses")+    func missingAndOld() async throws {+        let fixture = try await M5Fixture()+        _ = try await fixture.repository.confirmImport(plan: BackupImporter.plan(from: Self.document(state: nil)))+        #expect(try await fixture.repository.work(id: BackupV18Fixtures.minimalWorkID).publicationState == nil)+        #expect(throws: BackupImportError.self) {+            try BackupImporter.plan(from: BackupV18Fixtures.retiredGenerationDocument(format: 17, schema: 18))+        }+    }++    @Test("Malformed dates, noncanonical intervals and inconsistent raw status refuse before mutation")+    func invalidRefuses() async throws {+        let fixture = try await M5Fixture()+        for state in [Self.pending.replacingOccurrences(of: "2026-10-10", with: "2026-02-30"),+                      Self.pending.replacingOccurrences(of: "\"version\":1", with: "\"version\":2"),+                      Self.pending.replacingOccurrences(of: "2026-10-10", with: "2026-09-01")] {+            #expect(throws: BackupImportError.self) { try BackupImporter.plan(from: Self.document(state: state)) }+        }+        #expect(throws: BackupImportError.self) {+            try BackupImporter.plan(from: Self.document(state: Self.pending, status: "ongoing"))+        }+        let count = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking refusal") {+            try $0.fetchCount(FetchDescriptor<Work>())+        }+        #expect(count == 0)+    }++    @Test("Export preserves authored hiatus after return and refuses a contradictory mirror")+    func exportEvidence() async throws {+        let fixture = try await M5Fixture()+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.plan(BackupV18Fixtures.minimalTaughtPayload()))+        let state = try WorkPublicationState.decode(Data(Self.elapsed.utf8))+        try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding publication evidence") { context in+            let row = try #require(context.fetch(FetchDescriptor<Work>()).first)+            row.publicationStateData = try state.canonicalData()+            row.workStatusRaw = WorkStatus.hiatus.rawValue+            try context.save()+        }+        let payload = try await fixture.repository.backupV18Snapshot()+        let encoded = try BackupCanonicalJSON.encoder().encode(payload)+        #expect(String(decoding: encoded, as: UTF8.self).contains(#""publicationState":"#))+        #expect(payload.works.first?.workStatus == .hiatus)+        try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding contradictory mirror") { context in+            let row = try #require(context.fetch(FetchDescriptor<Work>()).first)+            row.workStatusRaw = WorkStatus.ongoing.rawValue+            try context.save()+        }+        await #expect(throws: (any Error).self) { try await fixture.repository.backupV18Snapshot() }+    }++    @Test("Authored recency preserves whole state while independently electing newer progress; repeated import is clean")+    func recencyAndProgress() async throws {+        let saves = ChangeRecordingSaveStrategy()+        let fixture = try await M5Fixture(saveStrategy: saves)+        func payload(state: String, age: TimeInterval, progressAge: TimeInterval, latest: Int) throws -> BackupV18Payload {+            let base = BackupV18Fixtures.minimalTaughtPayload()+            let source = base.works[0]+            let work = BackupV18Work(+                id: source.id, displayTitle: source.displayTitle,+                lastParsedTitle: source.lastParsedTitle, genericNotes: source.genericNotes,+                genreTags: source.genreTags, titleProvenance: source.titleProvenance,+                workStatus: .hiatus, readingStatus: source.readingStatus,+                verdict: source.verdict, releaseDays: source.releaseDays,+                workTypeID: source.workTypeID, typeName: source.typeName,+                createdAt: source.createdAt, modifiedAt: source.modifiedAt.addingTimeInterval(age),+                latestReleasedChapter: latest,+                latestConfirmedAt: source.createdAt.addingTimeInterval(progressAge),+                publicationState: try WorkPublicationState.decode(Data(state.utf8)))+            return BackupV18Payload(entries: base.entries, works: [work], sites: base.sites,+                titlePatterns: base.titlePatterns, urlRules: base.urlRules,+                workTypes: base.workTypes, memberships: base.memberships)+        }+        let local = try payload(state: Self.elapsed, age: 100, progressAge: 10, latest: 30)+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.plan(local))+        let older = try payload(state: Self.pending, age: 0, progressAge: 20, latest: 40)+        let plan = BackupV18Fixtures.plan(older)+        _ = try await fixture.repository.confirmImport(plan: plan)+        let first = try await fixture.repository.work(id: BackupV18Fixtures.minimalWorkID)+        #expect(first.publicationState == local.works[0].publicationState)+        #expect(first.catchUp.latest == 40)+        saves.arm()+        _ = try await fixture.repository.confirmImport(plan: plan)+        #expect(saves.dirtySaves.allSatisfy { !$0 })+        let newer = try payload(state: Self.unknown, age: 200, progressAge: 5, latest: 20)+        _ = try await fixture.repository.confirmImport(plan: BackupV18Fixtures.plan(newer))+        let second = try await fixture.repository.work(id: first.id)+        #expect(second.publicationState == newer.works[0].publicationState)+        #expect(second.catchUp.latest == 40)+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/PublicationProgressTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationProgressTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationProgressTests.swiftnew file mode 100644index 00000000..ab2c6a92--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationProgressTests.swift@@ -0,0 +1,101 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Pause-aware progress preserves original bounds")+struct PublicationProgressTests {+    static let calendar: Calendar = {+        var value = Calendar(identifier: .gregorian)+        value.timeZone = TimeZone(secondsFromGMT: 0)!+        return value+    }()+    static func day(_ text: String) -> CivilDay { CivilDateCodec.parse(text)! }+    static func record(on text: String, latest: Int? = 100, countsUp: Bool = true,+                       override: LastChapterOverride? = nil) -> CatchUpRecord {+        .init(confirmation: .init(latest: latest,+            confirmedAtMilliseconds: MillisecondInstant.milliseconds(day(text).date(in: calendar)),+            countsUp: countsUp, isEstimate: false), override: override)+    }+    static func progress(_ record: CatchUpRecord, state: WorkPublicationState?, on text: String,+                         notes: [NumberedNote] = [], marks: Set<CivilDay> = []) -> CatchUpProgress {+        CatchUpProgress.build(record: record, notes: notes, releaseDays: ReleaseDay.allCases,+            noEpisodeDays: marks, workStatus: state?.authoredStatus ?? .ongoing,+            publicationState: state, day: day(text), calendar: calendar)+    }++    @Test("Known-start pauses retain prior accrual; repeated and future reads are deterministic")+    func retainsPrePauseAndProjectsReturn() throws {+        let state = try WorkPublicationState(status: .hiatus, closedPauses: [+            .init(start: Self.day("2026-09-02"), end: Self.day("2026-09-04")),+        ], currentPause: .init(start: Self.day("2026-09-06"), returnDate: Self.day("2026-09-10")))+        let record = Self.record(on: "2026-09-01")+        #expect(Self.progress(record, state: state, on: "2026-09-05").effectiveLatest == 102)+        #expect(Self.progress(record, state: state, on: "2026-09-09").effectiveLatest == 102)+        #expect(Self.progress(record, state: state, on: "2026-09-10").effectiveLatest == 103)+        #expect(Self.progress(record, state: state, on: "2026-09-12").effectiveLatest == 105)+        #expect(Self.progress(record, state: state, on: "2026-09-12") == Self.progress(record, state: state, on: "2026-09-12"))+        #expect(record == Self.record(on: "2026-09-01"))+        #expect(Self.progress(record, state: state, on: "2026-09-12", marks: [Self.day("2026-09-07"), Self.day("2026-09-11")]).effectiveLatest == 104)+    }++    @Test("Same-day pause and return preserve confirmation and actual-read bounds")+    func sameDayBounds() throws {+        let state = try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: Self.day("2026-09-30"), returnDate: Self.day("2026-09-30")))+        let yesterday = Self.record(on: "2026-09-29")+        #expect(Self.progress(yesterday, state: state, on: "2026-09-30").effectiveLatest == 101)+        let note = NumberedNote(number: 105, firstCapturedAt: Self.day("2026-09-30").date(in: Self.calendar), title: "105")+        #expect(Self.progress(yesterday, state: state, on: "2026-09-30", notes: [note]).effectiveLatest == 105)+        let overridden = Self.record(on: "2026-09-29", override: .value(105,+            atMilliseconds: MillisecondInstant.milliseconds(Self.day("2026-09-30").date(in: Self.calendar))))+        #expect(Self.progress(overridden, state: state, on: "2026-09-30").effectiveLatest == 105)+        #expect(Self.progress(Self.record(on: "2026-09-30"), state: state, on: "2026-09-30").effectiveLatest == 100)+        let future = NumberedNote(number: 110, firstCapturedAt: Self.day("2026-10-01").date(in: Self.calendar), title: "future")+        #expect(Self.progress(yesterday, state: state, on: "2026-09-30", notes: [future]).effectiveLatest == 110)+    }++    @Test("Unknown starts, finished status, unknown latest and disabled counting preserve baselines")+    func legacyAndSwitches() throws {+        let unknown = try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: nil, returnDate: Self.day("2026-09-30")))+        let record = Self.record(on: "2026-09-01")+        #expect(Self.progress(record, state: unknown, on: "2026-09-29").effectiveLatest == 100)+        #expect(Self.progress(record, state: unknown, on: "2026-10-01").effectiveLatest == 102)+        #expect(Self.progress(Self.record(on: "2026-09-01", countsUp: false), state: unknown, on: "2026-10-01").effectiveLatest == 100)+        #expect(Self.progress(Self.record(on: "2026-09-01", latest: nil), state: unknown, on: "2026-10-01").effectiveLatest == nil)+        #expect(Self.progress(record, state: try WorkPublicationState(status: .finished), on: "2026-10-01").effectiveLatest == 100)+        #expect(CatchUpProgress.build(record: record, notes: [], releaseDays: ReleaseDay.allCases,+            workStatus: .hiatus, day: Self.day("2026-10-01"), calendar: Self.calendar).effectiveLatest == 100)+    }++    @Test("Snapshot builder, explicit rebase and Today counts share the pause boundaries")+    func snapshotAndRebase() throws {+        let state = try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: Self.day("2026-09-05"), returnDate: Self.day("2026-09-10")))+        let record = Self.record(on: "2026-09-01", override: .value(100,+            atMilliseconds: MillisecondInstant.milliseconds(Self.day("2026-09-01").date(in: Self.calendar))))+        let work = Work(displayTitle: "Serial", timestamp: Self.day("2026-09-01").date(in: Self.calendar))+        work.publicationStateData = try state.canonicalData()+        work.releaseDays = ReleaseDay.allCases+        work.readingStatus = .catchingUp+        work.catchUpConfirmationData = try JSONBlob.encode(record.confirmation)+        work.lastChapterOverrideData = try JSONBlob.encode(record.override)+        let entry = Entry(captureTitle: "Chapter 100", captureTitleSource: .host,+            rawURLString: "https://example.test/100", hostname: "example.test",+            entryIdentityKey: "100", timestamp: Self.day("2026-09-01").date(in: Self.calendar))+        entry.chapterSequence = "100"+        let snapshot = try LibraryRepository.snapshot(work, entries: [LibraryRepository.snapshot(entry)],+            types: .empty, series: .empty, credits: .empty, history: .empty)+        let day = Self.day("2026-09-12")+        #expect(CatchUpProgress.build(work: snapshot, day: day, calendar: Self.calendar).effectiveLatest == 106)+        let rebased = CatchUpProgress.rebased(record: record, notes: [], releaseDays: ReleaseDay.allCases,+            workStatus: .hiatus, publicationState: state, now: day.date(in: Self.calendar), calendar: Self.calendar)+        #expect(rebased?.latest == 106)+        #expect(rebased?.override == record.override)+        let plan = TodayDayPlan.build(day: day, currentDay: day,+            schedule: TodaySchedule.build(works: [snapshot], calendar: Self.calendar),+            presentation: .init(groups: [], actionableCount: 0), calendar: Self.calendar)+        #expect(plan.catchingUp.first?.progress.effectiveLatest == 106)+        #expect(plan.catchingUp.first?.releasesSince == 6)+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/PublicationScheduleTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationScheduleTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationScheduleTests.swiftnew file mode 100644index 00000000..97f9dd94--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PublicationScheduleTests.swift@@ -0,0 +1,130 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Returned works share selected-day release eligibility", .serialized)+struct PublicationScheduleTests {+    static var calendar: Calendar { PublicationProgressTests.calendar }+    static func day(_ text: String) -> CivilDay { CivilDateCodec.parse(text)! }+    static func state() throws -> WorkPublicationState {+        try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: day("2026-09-20"), returnDate: day("2026-09-30")))+    }+    static func snapshot(reading: ReadingStatus = .reading, days: [ReleaseDay] = ReleaseDay.allCases) throws -> WorkSnapshot {+        let work = Work(displayTitle: "Returns", timestamp: day("2026-09-01").date(in: calendar))+        work.workStatus = .hiatus+        work.readingStatus = reading+        work.releaseDays = days+        work.publicationStateData = try state().canonicalData()+        return try LibraryRepository.snapshot(work, entries: [], types: .empty, series: .empty, credits: .empty, history: .empty)+    }++    @Test("Cold readers retain known-start undated candidates and closed-pause gaps")+    func historicalColdParity() async throws {+        for dated in [false, true] {+            let fixture = try WriteFixture()+            let id = UUID()+            let state = try WorkPublicationState(status: .hiatus, closedPauses: [+                .init(start: Self.day("2026-09-20"), end: Self.day("2026-09-22"))+            ], currentPause: .init(start: Self.day("2026-09-30"),+                returnDate: dated ? Self.day("2026-10-02") : nil))+            let bytes = try state.canonicalData()+            try fixture.seed { store in+                store.insertSite(hostname: "dup.example")+                let work = store.insertWork(id: id, hostname: "dup.example", title: "Returns", offset: 0)+                work.workStatus = .hiatus+                work.publicationStateData = bytes+                work.releaseDays = ReleaseDay.allCases+            }+            let (_, repository) = try await LibraryRepository.openForExtension(fixture.configuration,+                clock: FixedRepositoryClock(Self.day("2026-09-29").date(in: Self.calendar)))+            let original = try await repository.work(id: id)+            let presentation = try await repository.todayPresentation(calendar: Self.calendar)+            let works = try await repository.works().works+            #expect(presentation.schedule == TodaySchedule.build(works: works, calendar: Self.calendar))+            for text in ["2026-09-19", "2026-09-20", "2026-09-22", "2026-09-29", "2026-09-30", "2026-10-02"] {+                let selected = Self.day(text)+                let eligible = text != "2026-09-20" && text != "2026-09-30" && (dated || text != "2026-10-02")+                let answer = IntentAnswers.releasingToday(presentation, currentDay: selected, calendar: Self.calendar)+                #expect(answer.map(\.workID) == (eligible ? [id] : []))+                #expect(original.effectiveWorkStatus(on: selected) == (eligible ? .ongoing : .hiatus))+            }+            #expect(WorkEditBasis(work: try await repository.work(id: id)) == WorkEditBasis(work: original))+            #expect(try await repository.workSummaries(ids: [id]).first?.workStatus == .ongoing)+            await repository.shutdown()+        }+    }++    @Test("Candidate membership projects return while actual current status stays authored hiatus")+    func candidateAndSelectedDays() throws {+        let snapshot = try Self.snapshot()+        let schedule = TodaySchedule.build(works: [snapshot], calendar: Self.calendar)+        #expect(schedule.works.count == 1)+        #expect(TodaySchedule.admits(readingStatus: .reading, workStatus: .hiatus,+            releaseDays: ReleaseDay.allCases, publicationState: try Self.state()) == .scheduled)+        let current = Self.day("2026-09-29")+        for text in ["2026-09-29", "2026-09-30", "2026-10-01"] {+            let plan = TodayDayPlan.build(day: Self.day(text), currentDay: current, schedule: schedule,+                presentation: .init(groups: [], actionableCount: 0), calendar: Self.calendar)+            #expect(plan.releases.count == (text == "2026-09-29" ? 0 : 1))+            if let row = plan.releases.first { #expect(row.workStatus == .ongoing) }+        }+        #expect(snapshot.authoredWorkStatus == .hiatus)+        #expect(snapshot.effectiveWorkStatus(on: current) == .hiatus)+        #expect(try snapshot.publicationState == Self.state())+    }++    @Test("Every reading status keeps catch-up priority and returns add no weekday")+    func readingAndWeekdayRules() throws {+        for reading in ReadingStatus.allCases {+            let schedule = TodaySchedule.build(works: [try Self.snapshot(reading: reading, days: [.monday])], calendar: Self.calendar)+            #expect(schedule.works.count == (reading == .reading ? 1 : 0))+            #expect(schedule.catchingUp.count == (reading == .catchingUp ? 1 : 0))+            let returnDay = Self.day("2026-09-30") // Wednesday, not the schedule.+            let plan = TodayDayPlan.build(day: returnDay, currentDay: returnDay, schedule: schedule,+                presentation: .init(groups: [], actionableCount: 0), calendar: Self.calendar)+            #expect(plan.releases.isEmpty)+            #expect(plan.catchingUp.count == (reading == .catchingUp ? 1 : 0))+            #expect(plan.catchingUp.first?.workStatus == (reading == .catchingUp ? .ongoing : nil))+        }+        #expect(TodaySchedule.build(works: [try Self.snapshot(days: [])], calendar: Self.calendar).works.isEmpty)+    }++    @Test("Cold extension reads agree with full snapshot schedules and current summaries")+    func coldIntentAndPrefilterParity() async throws {+        let fixture = try WriteFixture()+        let id = UUID()+        let bytes = try Self.state().canonicalData()+        try fixture.seed { store in+            store.insertSite(hostname: "dup.example")+            let work = store.insertWork(id: id, hostname: "dup.example", title: "Returns", offset: 0)+            work.workStatus = .hiatus+            work.publicationStateData = bytes+            work.releaseDays = ReleaseDay.allCases+        }+        let current = Self.day("2026-09-29")+        let (_, before) = try await LibraryRepository.openForExtension(fixture.configuration,+            clock: FixedRepositoryClock(current.date(in: Self.calendar)))+        let presentation = try await before.todayPresentation(calendar: Self.calendar)+        let works = try await before.works().works+        #expect(presentation.schedule == TodaySchedule.build(works: works, calendar: Self.calendar))+        #expect(IntentAnswers.releasingToday(presentation, currentDay: current, calendar: Self.calendar).isEmpty)+        #expect(try await before.workSummaries(ids: [id]).first?.workStatus == .hiatus)+        #expect(try await before.markNoEpisode(workID: id, day: Self.day("2026-09-30"), calendar: Self.calendar) == .committed)+        #expect(try await before.markNoEpisode(workID: id, day: current, calendar: Self.calendar) != .committed)+        await before.shutdown()+        let returned = Self.day("2026-09-30")+        let (_, after) = try await LibraryRepository.openForExtension(fixture.configuration,+            clock: FixedRepositoryClock(returned.date(in: Self.calendar)))+        #expect(try await after.workSummaries(ids: [id]).first?.workStatus == .ongoing)+        let marked = try await after.todayPresentation(calendar: Self.calendar)+        #expect(IntentAnswers.releasingToday(marked, currentDay: returned, calendar: Self.calendar).isEmpty)+        #expect(try await after.undoNoEpisode(workID: id, day: returned) == .committed)+        let unmarked = try await after.todayPresentation(calendar: Self.calendar)+        #expect(IntentAnswers.releasingToday(unmarked, currentDay: returned, calendar: Self.calendar).map(\.workID) == [id])+        #expect(try await after.work(id: id).authoredWorkStatus == .hiatus)+        #expect(try await after.work(id: id).publicationStateData == bytes)+        await after.shutdown()+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RecordRowTests.swiftindex 6c0fa26c..58112da2 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 = BackupV17Character(+        let record = BackupV18Character(             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: BackupV17Suppression(+            let imported = CharacterSuppression.make(imported: BackupV18Suppression(                 id: Self.absent, workID: Self.workID, kindRaw: "fact", nameKey: "bruce",                 sourceKindRaw: "genericNotes", sourceEntryID: nil, evidence: "he left",                 statusRaw: "cleared", actionAt: M5Fixture.epoch))
Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RefreshUnionInvariantTests.swiftindex 7d83a85f..ce198ed1 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 `BackupV17Exporter.swift:41` would+/// (`+ReparseCapture.swift:284`, `:396`), and `BackupV18Exporter.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.backupV17Snapshot()+            let payload = try await repository.backupV18Snapshot()             // One wire Site per hostname, including the duplicated one and the             // rowless one (Q38, Q40).             #expect(Set(payload.sites.map(\.hostname))
Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swiftindex 55b26a91..e49dd6a8 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ReleaseDayWritePathTests.swift@@ -24,7 +24,7 @@ struct ReleaseDayWritePathTests {     ) -> WorkMetadataDraft {         WorkMetadataDraft(             displayTitle: title, typeAssignment: .none, genreTags: [], genericNotes: "",-            workStatus: .ongoing, readingStatus: .reading, verdict: "",+            publicationEdit: .unchanged, readingStatus: .reading, verdict: "",             releaseDays: releaseDays, membership: nil, thumbnail: .keep)     } 
Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swiftindex 1cbe8d35..8af5d185 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift@@ -155,7 +155,7 @@ struct RepositoryCaptureTests {         let work = try #require(             try await fixture.repository.works().works                 .first { $0.memberships.contains { $0.urlIdentity == "99" } })-        #expect(work.workStatus == .ongoing)+        #expect(work.authoredWorkStatus == .ongoing)         #expect(work.readingStatus == .reading)         #expect(work.verdict == "")     }@@ -174,7 +174,7 @@ struct RepositoryCaptureTests {             id: work.id,             draft: WorkMetadataDraft(                 displayTitle: work.displayTitle, typeAssignment: .none, genreTags: [],-                genericNotes: "", workStatus: .hiatus, readingStatus: .abandoned,+                genericNotes: "", publicationEdit: .set(status: .hiatus, returnDate: nil), readingStatus: .abandoned,                 verdict: "stopped at 12", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current) @@ -184,7 +184,7 @@ struct RepositoryCaptureTests {         let after = try #require(try await fixture.repository.works().works.first)         #expect(after.id == work.id)         #expect(after.entries.count == 2)-        #expect(after.workStatus == .hiatus)+        #expect(after.authoredWorkStatus == .hiatus)         #expect(after.readingStatus == .abandoned)         #expect(after.verdict == "stopped at 12")     }@@ -213,7 +213,7 @@ struct RepositoryCaptureTests {         #expect(after.entries.count == 2)         #expect(after.readingStatus == .reading)         // Req 3.4: nothing else about the work moved.-        #expect(after.workStatus == .ongoing)+        #expect(after.authoredWorkStatus == .ongoing)         #expect(after.verdict == "")         #expect(after.releaseDays.isEmpty)     }@@ -239,7 +239,7 @@ struct RepositoryCaptureTests {             try await fixture.repository.works().works.first { $0.id == planned.id })         #expect(after.entries.count == 1, "the claim attached the captured entry")         #expect(after.readingStatus == .reading)-        #expect(after.workStatus == .ongoing)+        #expect(after.authoredWorkStatus == .ongoing)         #expect(after.verdict == "")     } @@ -471,7 +471,7 @@ private struct CaptureRepositoryFixture {             draft: WorkMetadataDraft(                 displayTitle: work.displayTitle, typeAssignment: work.typeDisplay.assignment,                 genreTags: work.genreTags, genericNotes: work.genericNotes,-                workStatus: work.workStatus, readingStatus: status, verdict: work.verdict,+                publicationEdit: .unchanged, readingStatus: status, verdict: work.verdict,                 releaseDays: work.releaseDays, membership: work.membership,                 thumbnail: .keep), calendar: .current)     }
Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swiftindex b87e251d..ab2efd77 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryReShareTests.swift@@ -229,7 +229,7 @@ struct RepositoryReShareTests {             id: work.id,             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [], genericNotes: "",-                workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],+                publicationEdit: .unchanged, readingStatus: .toRead, verdict: "", releaseDays: [],                 membership: nil, thumbnail: .keep), calendar: .current)          let lookupResult = try await fixture.repository.captureLookup(
Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swiftindex 947908e7..9bd40b9a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryTeachingTests.swift@@ -346,7 +346,7 @@ struct RepositoryTeachingTests {                 displayTitle: "Fiction Renamed",                 typeAssignment: .configured(UUID(uuidString: "0E7A0000-0000-4000-8000-0000000000A1")!),                 genreTags: [], genericNotes: "",-                workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)         save.resetCount() 
Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swiftindex b51a9da1..5708c604 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift@@ -46,13 +46,13 @@ struct RepositoryWorksTests {         let planned = try await fixture.repository.createWork(             NewWorkDraft(displayTitle: "Planned", hostname: "example.com", readingStatus: .toRead))         #expect(planned.readingStatus == .toRead)-        #expect(planned.workStatus == .ongoing)+        #expect(planned.authoredWorkStatus == .ongoing)         #expect(planned.verdict.isEmpty)          let defaulted = try await fixture.repository.createWork(             NewWorkDraft(displayTitle: "Unstated", hostname: "example.com"))         #expect(defaulted.readingStatus == .reading)-        #expect(defaulted.workStatus == .ongoing)+        #expect(defaulted.authoredWorkStatus == .ongoing)         #expect(defaulted.verdict.isEmpty)          // The status is on the row, not only in the returned snapshot.@@ -128,7 +128,7 @@ struct RepositoryWorksTests {                 typeAssignment: .configured(Self.renamedTypeID),                 genreTags: [" fantasy ", "", "fantasy", "Fantasy", "action", "action "],                 genericNotes: "Notes",-                workStatus: .hiatus, readingStatus: .reading, verdict: ""+                publicationEdit: .set(status: .hiatus, returnDate: nil), readingStatus: .reading, verdict: ""             , releaseDays: [], membership: nil,             thumbnail: .keep)         , calendar: .current)@@ -138,7 +138,7 @@ struct RepositoryWorksTests {         #expect(updated.typeDisplay.assignment == .configured(Self.renamedTypeID))         #expect(updated.genreTags == ["fantasy", "Fantasy", "action"])         #expect(updated.genericNotes == "Notes")-        #expect(updated.workStatus == .hiatus)+        #expect(updated.authoredWorkStatus == .hiatus)         #expect(updated.readingStatus == .reading)         #expect(updated.verdict == "")         #expect(updated.titleProvenance == .manual)@@ -199,7 +199,7 @@ struct RepositoryWorksTests {         let fixture = try await WorksRepositoryFixture()         let created = try await fixture.repository.createWork(             NewWorkDraft(displayTitle: "New Work", hostname: "example.com"))-        #expect(created.workStatus == .ongoing)+        #expect(created.authoredWorkStatus == .ongoing)         #expect(created.readingStatus == .reading)         #expect(created.verdict == "") @@ -209,7 +209,7 @@ struct RepositoryWorksTests {         let moved = try #require(             try await fixture.repository.works().works                 .first { $0.displayTitle == "Created from Entry" })-        #expect(moved.workStatus == .ongoing)+        #expect(moved.authoredWorkStatus == .ongoing)         #expect(moved.readingStatus == .reading)         #expect(moved.verdict == "")     }@@ -237,7 +237,7 @@ struct RepositoryWorksTests {         #expect(after.entries.map(\.id) == [entry.id])         // Req 3.4: the promotion adds nothing to what the move already writes.         #expect(after.displayTitle == "Planned")-        #expect(after.workStatus == .ongoing)+        #expect(after.authoredWorkStatus == .ongoing)         #expect(after.verdict == "")         #expect(after.releaseDays.isEmpty)     }@@ -358,7 +358,7 @@ struct RepositoryWorksTests {             id: planned.id, basis: basis,             draft: WorkMetadataDraft(                 displayTitle: "Planned", typeAssignment: .none, genreTags: [],-                genericNotes: "a note the reader typed", workStatus: .ongoing,+                genericNotes: "a note the reader typed", publicationEdit: .unchanged,                 readingStatus: .toRead, verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current) @@ -387,12 +387,12 @@ struct RepositoryWorksTests {             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .finished, readingStatus: .finished,+                publicationEdit: .set(status: .finished, returnDate: nil), readingStatus: .finished,                 verdict: "\n  a fine ending\n", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)          let updated = try await fixture.repository.work(id: work.id)-        #expect(updated.workStatus == .finished)+        #expect(updated.authoredWorkStatus == .finished)         #expect(updated.readingStatus == .finished)         // Q33: trimmed here, and nowhere else.         #expect(updated.verdict == "a fine ending")@@ -413,7 +413,7 @@ struct RepositoryWorksTests {                 draft: WorkMetadataDraft(                     displayTitle: "Changed", typeAssignment: .configured(Self.renamedTypeID),                     genreTags: ["x"], genericNotes: "changed",-                    workStatus: .ongoing, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,+                    publicationEdit: .unchanged, readingStatus: .reading, verdict: "", releaseDays: [], membership: nil,                     thumbnail: .keep)             , calendar: .current)         }@@ -511,7 +511,7 @@ private struct WorksRepositoryFixture {             draft: WorkMetadataDraft(                 displayTitle: work.displayTitle, typeAssignment: work.typeDisplay.assignment,                 genreTags: work.genreTags, genericNotes: work.genericNotes,-                workStatus: work.workStatus, readingStatus: status, verdict: work.verdict,+                publicationEdit: .unchanged, readingStatus: status, verdict: work.verdict,                 releaseDays: work.releaseDays, membership: work.membership,                 thumbnail: .keep), calendar: .current)     }
Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swiftindex 9af2ec86..96b47b8c 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         return try ModelContainer(             for: schema,             configurations: [ModelConfiguration(
Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swiftindex 28718680..1f8ac6e7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift@@ -502,7 +502,7 @@ struct SeriesRepositoryTests {                     displayTitle: snapshot.displayTitle,                     typeAssignment: snapshot.typeDisplay.assignment,                     genreTags: snapshot.genreTags, genericNotes: snapshot.genericNotes,-                    workStatus: snapshot.workStatus, readingStatus: snapshot.readingStatus,+                    publicationEdit: .unchanged, readingStatus: snapshot.readingStatus,                     verdict: snapshot.verdict, releaseDays: [], membership: nil,                     thumbnail: .keep), calendar: .current) == .committed) 
Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swiftindex a17805bb..a8de4cb9 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)         self.saveStrategy = saveStrategy ?? saveRecorder
Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swiftindex 4f5e8f2d..dd37f099 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }
Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swiftindex ddab9da7..c00fdf1b 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) == ["18.0.0"],+        #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["19.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")
Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swiftindex 4f3e8c46..2dce2594 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift@@ -79,6 +79,7 @@ struct ThumbnailBytesReachTests {         "Models.swift",         "AsterismSchemaV16.swift",         "AsterismSchemaV17Models.swift",+        "AsterismSchemaV18Models.swift",         "GroupOrdering.swift",         "Thumbnails/ThumbnailStoreProbe.swift",         "LibraryRepository+Thumbnails.swift",
Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swiftindex 8b7466ce..d1d25e41 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: AsterismSchemaV18.self).entities.map(\.name))+        let live = Set(Schema(versionedSchema: AsterismSchemaV19.self).entities.map(\.name))         let frozen = Set(Schema(versionedSchema: AsterismSchemaV16.self).entities.map(\.name))         #expect(live.isDisjoint(with: probeNames))         #expect(frozen.isDisjoint(with: probeNames))
Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swiftindex 90e67547..44d82258 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         container = try ModelContainer(             for: schema,             configurations: [ModelConfiguration(
Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swiftindex 61b753a2..c0e7ed6b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayDayPlanTests.swift@@ -76,7 +76,7 @@ struct TodayDayPlanTests {             memberships: [WorkSiteMembershipSnapshot(id: UUID(), hostname: hostname)],             genericNotes: "", genreTags: [], titleProvenance: .parsed,             createdAt: .distantPast, modifiedAt: .distantPast, entries: entries,-            workStatus: workStatus, readingStatus: readingStatus,+            authoredWorkStatus: workStatus, readingStatus: readingStatus,             releaseDays: releaseDays, catchUp: catchUp,             noEpisodeHistory: noEpisodeHistory)     }@@ -849,7 +849,7 @@ struct TodayDayPlanTests {             ],             genericNotes: "", genreTags: [], titleProvenance: .parsed,             createdAt: .distantPast, modifiedAt: .distantPast, entries: [],-            workStatus: .ongoing, readingStatus: .reading, releaseDays: [.thursday])+            authoredWorkStatus: .ongoing, readingStatus: .reading, releaseDays: [.thursday])         let plan = TodayDayPlan.build(             day: Self.thursday, currentDay: Self.thursday,             schedule: TodaySchedule.build(works: [work], calendar: calendar),@@ -990,7 +990,7 @@ struct TodayDayPlanTests {                 ],                 genericNotes: "", genreTags: [], titleProvenance: .parsed,                 createdAt: .distantPast, modifiedAt: .distantPast, entries: [],-                workStatus: .ongoing, readingStatus: .reading, releaseDays: [.thursday])+                authoredWorkStatus: .ongoing, readingStatus: .reading, releaseDays: [.thursday])         }         #expect(snapshot("https://example.test/fiction/1").primaryURL != nil)         #expect(snapshot("HTTP://example.test/fiction/1").primaryURL != nil)
Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swiftindex b457a70a..acd659d9 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: BackupV17Payload) throws -> URLTwoFieldTemplate? {+  private static func combinedRule(of payload: BackupV18Payload) 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 = BackupV17Fixtures.sequencePresenceOmittedDocument()+    let document = BackupV18Fixtures.sequencePresenceOmittedDocument()     #expect(!String(decoding: document, as: UTF8.self).contains("sequencePresence")) -    let decoded = try BackupV17Codec.decode(document)+    let decoded = try BackupV18Codec.decode(document) -    #expect(decoded.payload == BackupV17Fixtures.combinedRulePayload(presence: .required))+    #expect(decoded.payload == BackupV18Fixtures.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 BackupV17Codec.encode(-      payload: BackupV17Fixtures.combinedRulePayload(presence: .required),-      metadata: BackupV17Metadata(-        appBuild: "pre-feature", exportedAt: BackupV17Fixtures.created))+    let encoded = try BackupV18Codec.encode(+      payload: BackupV18Fixtures.combinedRulePayload(presence: .required),+      metadata: BackupV18Metadata(+        appBuild: "pre-feature", exportedAt: BackupV18Fixtures.created))     let json = String(decoding: encoded, as: UTF8.self)      #expect(!json.contains("sequencePresence"))     #expect(-      json.contains(BackupV17Fixtures.sequencePresenceOmittedPayloadJSON),+      json.contains(BackupV18Fixtures.sequencePresenceOmittedPayloadJSON),       "the exported payload is no longer the pre-feature payload")-    #expect(encoded == BackupV17Fixtures.sequencePresenceOmittedDocument())+    #expect(encoded == BackupV18Fixtures.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 = BackupV17Fixtures.combinedRulePayload(presence: .optional)-    let encoded = try BackupV17Codec.encode(+    let payload = BackupV18Fixtures.combinedRulePayload(presence: .optional)+    let encoded = try BackupV18Codec.encode(       payload: payload,-      metadata: BackupV17Metadata(appBuild: "with-feature", exportedAt: BackupV17Fixtures.created))+      metadata: BackupV18Metadata(appBuild: "with-feature", exportedAt: BackupV18Fixtures.created))     #expect(String(decoding: encoded, as: UTF8.self).contains(#""sequencePresence":"optional""#)) -    let decoded = try BackupV17Codec.decode(encoded)+    let decoded = try BackupV18Codec.decode(encoded)     #expect(decoded.payload == payload)     #expect(try Self.combinedRule(of: decoded.payload)?.sequencePresence == .optional) -    let schema = Schema(versionedSchema: AsterismSchemaV18.self)+    let schema = Schema(versionedSchema: AsterismSchemaV19.self)     let container = try ModelContainer(       for: schema,       configurations: [
Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/UnknownSiteModeTests.swiftindex aa1e5871..95f4952e 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.backupV17Snapshot()+            _ = try await repository.backupV18Snapshot()             Issue.record("expected the export to refuse a Site whose mode has no case")-        } catch let error as BackupV17ExportError {+        } catch let error as BackupV18ExportError {             guard case .unrepresentableValue(let record, let field, let value) = error else {                 Issue.record("expected .unrepresentableValue, got \(error)")                 await repository.shutdown()
Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swiftindex b6fe4bab..6136c794 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() == ["18.0.0"])-        #expect(try root.markerText() == "18")+        #expect(try root.recordedVersions() == ["19.0.0"])+        #expect(try root.markerText() == "19")         #expect(counts.works == 1)         #expect(counts.entries == 3)         #expect(counts.sites == 1)@@ -81,6 +81,7 @@ struct V16RecordedStoreTests {         #expect(facts.releaseDays == Fixture.releaseDays)         #expect(facts.catchUpConfirmationData == nil)         #expect(facts.lastChapterOverrideData == nil)+        #expect(facts.publicationStateData == nil)          // MARK: V14's three columns, which this stage may not touch. The         // fixture seeds all three away from nil — the bytes included, which@@ -392,8 +393,8 @@ struct V16RecordedStoreTests {         #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready)         let (_, second) = try await LibraryRepository.openForApp(root.configuration)         await second.shutdown()-        #expect(try root.markerText() == "18")-        #expect(try root.recordedVersions() == ["18.0.0"])+        #expect(try root.markerText() == "19")+        #expect(try root.recordedVersions() == ["19.0.0"])         withExtendedLifetime(root) {}     } }@@ -577,6 +578,7 @@ private struct ConvertedV17Library: Sendable {     let releaseDays: [ReleaseDay]     let catchUpConfirmationData: Data?     let lastChapterOverrideData: Data?+    let publicationStateData: Data?      let memberships: [MembershipFacts]     let entries: [UUID: EntryFacts]@@ -649,6 +651,7 @@ private struct ConvertedV17Library: Sendable {         releaseDays = work.releaseDays         catchUpConfirmationData = work.catchUpConfirmationData         lastChapterOverrideData = work.lastChapterOverrideData+        publicationStateData = work.publicationStateData         series = try context.fetch(FetchDescriptor<Series>())             .sorted { $0.id.uuidString < $1.id.uuidString }             .map {
Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swiftindex b23cfcd7..e0ba90b4 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift@@ -33,15 +33,16 @@ struct V17RecordedStoreTests {         ) { 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)+            return (works.map(\.id), works.map(\.displayTitle), actions.count, works.allSatisfy { $0.publicationStateData == nil })         }         #expect(facts.0 == [workID])         #expect(facts.1 == ["Migrating Work"])         #expect(facts.2 == 0)+        #expect(facts.3)         #expect(try String(contentsOf: configuration.readinessMarkerURL,-                           encoding: .utf8) == "18\n")+                           encoding: .utf8) == "19\n")         #expect(try V4RecordedStoreFixture.recordedModelVersions(-            at: configuration.storeURL) == ["18.0.0"])+            at: configuration.storeURL) == ["19.0.0"])         await repository.shutdown()     } 
Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swiftnew file mode 100644index 00000000..8aca1e74--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift@@ -0,0 +1,94 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("V19 migration and readiness", .serialized)+struct V18RecordedStoreTests {+    @Test("V18 keeps authored content, progress, thumbnail and action history")+    func conversion() async throws {+        let root = FileManager.default.temporaryDirectory.appending(path: "V18Recorded-\(UUID())")+        defer { try? FileManager.default.removeItem(at: root) }+        let configuration = LibraryConfiguration(rootDirectory: root)+        try FileManager.default.createDirectory(+            at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true)+        let workID = UUID()+        let confirmation = Data("{\"baseline\":23}".utf8)+        let thumbnail = Data(repeating: 42, count: 100_000)+        let action = try NoEpisodeHistory.Action(+            workID: workID, key: "mark/\(UUID().uuidString)", day: "2026-09-29",+            kind: .mark, observedClearKeys: [])+        let payload = try action.canonicalData()+        // The frozen container is released when seed returns. Never keep it+        // alive while opening the live schema: SwiftData's entity registry is global.+        try seed(at: configuration.storeURL, workID: workID, confirmation: confirmation,+                 thumbnail: thumbnail, action: action, payload: payload)+        try Data("18\n".utf8).write(to: configuration.readinessMarkerURL)+        await #expect(throws: Error.self) { try await LibraryRepository.openForExtension(configuration) }+        #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "18\n")+        #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["18.0.0"])++        let (_, repository) = try await LibraryRepository.openForApp(configuration)+        let facts = try await repository.withLockedContext(mode: .shared, operation: "checking V18 conversion") { context in+            let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+            let actions = try context.fetch(FetchDescriptor<NoEpisodeAction>())+            return (work.id, work.displayTitle, work.workStatusRaw, work.publicationStateData,+                    work.catchUpConfirmationData, work.thumbnailData, actions.map(\.payloadData))+        }+        await repository.shutdown()+        #expect(facts.0 == workID)+        #expect(facts.1 == "Paused Work")+        #expect(facts.2 == "hiatus")+        #expect(facts.3 == nil)+        #expect(facts.4 == confirmation)+        #expect(facts.5 == thumbnail)+        #expect(facts.6 == [payload])+        #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "19\n")+        #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["19.0.0"])+        let (_, extensionRepository) = try await LibraryRepository.openForExtension(configuration)+        await extensionRepository.shutdown()+    }++    @Test("App accepts 16–19 while the extension refuses every lagging marker",+          arguments: ["16", "17", "18", "19"])+    func markerContracts(marker: String) async throws {+        let root = FileManager.default.temporaryDirectory.appending(path: "Marker19-\(UUID())")+        defer { try? FileManager.default.removeItem(at: root) }+        let configuration = LibraryConfiguration(rootDirectory: root)+        let (_, initial) = try await LibraryRepository.openForApp(configuration)+        await initial.shutdown()+        try Data("\(marker)\n".utf8).write(to: configuration.readinessMarkerURL)+        #expect(try LibraryRepository.classify(configuration, fileManager: .default)+                == (marker == "19" ? .ready : .markerLagging(generation: marker)))+        if marker != "19" {+            await #expect(throws: Error.self) { try await LibraryRepository.openForExtension(configuration) }+            #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "\(marker)\n")+        }+        let (_, app) = try await LibraryRepository.openForApp(configuration)+        await app.shutdown()+        #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "19\n")+    }++    private func seed(at url: URL, workID: UUID, confirmation: Data, thumbnail: Data,+                      action: NoEpisodeHistory.Action, payload: Data) throws {+        let schema = Schema(versionedSchema: AsterismSchemaV18.self)+        let container = try ModelContainer(for: schema, configurations: [+            ModelConfiguration("AsterismV3", schema: schema, url: url, cloudKitDatabase: .none)])+        let context = ModelContext(container)+        let work = AsterismSchemaV18.Work()+        work.id = workID+        work.displayTitle = "Paused Work"+        work.workStatusRaw = "hiatus"+        work.catchUpConfirmationData = confirmation+        work.thumbnailData = thumbnail+        context.insert(work)+        let row = AsterismSchemaV18.NoEpisodeAction()+        row.workID = workID+        row.key = action.key+        row.payloadData = payload+        context.insert(row)+        try context.save()+        withExtendedLifetime(container) {}+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swiftindex d50e8b33..7fc8ddb0 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditCreditsTests.swift@@ -68,7 +68,7 @@ struct WorkEditCreditsTests {             typeAssignment: work.typeDisplay.assignment,             genreTags: work.genreTags,             genericNotes: notes ?? work.genericNotes,-            workStatus: work.workStatus,+            publicationEdit: .unchanged,             readingStatus: work.readingStatus,             verdict: work.verdict,             releaseDays: [],
Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swiftindex 993b987b..a540dcd3 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkEditTests.swift@@ -27,7 +27,7 @@ struct WorkEditTests {             typeAssignment: work.typeDisplay.assignment,             genreTags: work.genreTags,             genericNotes: notes ?? work.genericNotes,-            workStatus: work.workStatus,+            publicationEdit: .unchanged,             readingStatus: work.readingStatus,             verdict: work.verdict,             releaseDays: [],@@ -66,7 +66,7 @@ struct WorkEditTests {             id: UUID(), basis: identity,             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],-                genericNotes: "reader prose", workStatus: .ongoing, readingStatus: .reading,+                genericNotes: "reader prose", publicationEdit: .unchanged, readingStatus: .reading,                 verdict: "", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)         #expect(refused.conflict?.survivorID == survivor)@@ -86,7 +86,7 @@ struct WorkEditTests {             id: UUID(), basis: matching,             draft: WorkMetadataDraft(                 displayTitle: "A Serial", typeAssignment: .none, genreTags: [],-                genericNotes: "reader prose", workStatus: .ongoing, readingStatus: .reading,+                genericNotes: "reader prose", publicationEdit: .unchanged, readingStatus: .reading,                 verdict: "",                 releaseDays: [],                 membership: SeriesMembership(seriesID: seriesID, position: 1),
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swiftindex 610faca6..ca5a56b0 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift@@ -693,7 +693,7 @@ struct WorkMergePlannerTests {                 genericNotes: notes, genreTags: tags, titleProvenance: provenance,                 createdAt: Date(timeIntervalSince1970: 1),                 modifiedAt: Date(timeIntervalSince1970: 2), entries: entries,-                workStatus: workStatus, readingStatus: readingStatus, verdict: verdict,+                authoredWorkStatus: workStatus, readingStatus: readingStatus, verdict: verdict,                 membership: membership,                 series: membership.map { SeriesDisplay(id: $0.seriesID, name: "Arcs", createdAt: nil) },                 credits: credits, thumbnail: thumbnail, releaseDays: releaseDays)@@ -882,7 +882,7 @@ struct WorkMergePlannerTests {             createdAt: Date(timeIntervalSince1970: 1),             modifiedAt: Date(timeIntervalSince1970: 2),             entries: entries,-            workStatus: workStatus,+            authoredWorkStatus: workStatus,             readingStatus: readingStatus,             verdict: verdict,             thumbnail: thumbnail,
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swiftindex 4e4e6775..3dc74411 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeRepositoryTests.swift@@ -60,14 +60,14 @@ struct WorkMergeRepositoryTests {             draft: WorkMetadataDraft(                 displayTitle: "Target Work", typeAssignment: .none, genreTags: [],                 genericNotes: "target notes",-                workStatus: .finished, readingStatus: .finished, verdict: "a fine ending", releaseDays: [], membership: nil,+                publicationEdit: .set(status: .finished, returnDate: nil), readingStatus: .finished, verdict: "a fine ending", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)         try await fixture.repository.updateWork(             id: sourceID,             draft: WorkMetadataDraft(                 displayTitle: "Source Work", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .hiatus, readingStatus: .abandoned,+                publicationEdit: .set(status: .hiatus, returnDate: nil), readingStatus: .abandoned,                 verdict: "gave up in book two", releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current) @@ -87,7 +87,7 @@ struct WorkMergeRepositoryTests {         }          let target = try await fixture.repository.work(id: targetID)-        #expect(target.workStatus == .finished)+        #expect(target.authoredWorkStatus == .finished)         #expect(target.readingStatus == .finished)         #expect(target.verdict == "a fine ending")         #expect(target.genericNotes.contains("Verdict: gave up in book two"))@@ -106,7 +106,7 @@ struct WorkMergeRepositoryTests {             draft: WorkMetadataDraft(                 displayTitle: "Source Work", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],+                publicationEdit: .unchanged, readingStatus: .toRead, verdict: "", releaseDays: [],                 membership: nil, thumbnail: .keep), calendar: .current)          let contract = try await fixture.repository.projectMerge(@@ -138,7 +138,7 @@ struct WorkMergeRepositoryTests {             draft: WorkMetadataDraft(                 displayTitle: "Target Work", typeAssignment: .none, genreTags: [],                 genericNotes: "",-                workStatus: .ongoing, readingStatus: .toRead, verdict: "", releaseDays: [],+                publicationEdit: .unchanged, readingStatus: .toRead, verdict: "", releaseDays: [],                 membership: nil, thumbnail: .keep), calendar: .current)          let contract = try await fixture.repository.projectMerge(@@ -171,7 +171,7 @@ struct WorkMergeRepositoryTests {             id: sourceID,             draft: WorkMetadataDraft(                 displayTitle: "Source Work", typeAssignment: .none, genreTags: [],-                genericNotes: "", workStatus: .ongoing, readingStatus: .reading, verdict: "",+                genericNotes: "", publicationEdit: .unchanged, readingStatus: .reading, verdict: "",                 releaseDays: [],                 membership: nil, thumbnail: .set(cover)), calendar: .current) @@ -207,7 +207,7 @@ struct WorkMergeRepositoryTests {                 id: id,                 draft: WorkMetadataDraft(                     displayTitle: title, typeAssignment: .none, genreTags: [],-                    genericNotes: "", workStatus: .ongoing, readingStatus: .reading,+                    genericNotes: "", publicationEdit: .unchanged, readingStatus: .reading,                     verdict: "", releaseDays: [], membership: nil, thumbnail: .set(cover)), calendar: .current)         } @@ -338,7 +338,7 @@ struct WorkMergeRepositoryTests {                 typeAssignment: .configured(UUID(uuidString: "0E7A0000-0000-4000-8000-0000000000A1")!),                 genreTags: [],                 genericNotes: "Changed",-                workStatus: .ongoing, readingStatus: .reading, verdict: ""+                publicationEdit: .unchanged, readingStatus: .reading, verdict: ""             , releaseDays: [], membership: nil,             thumbnail: .keep)         , calendar: .current)
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swiftindex 765ea061..ff18db48 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift@@ -16,6 +16,36 @@ struct WorkMergeToReadMatchTests {      private static let noLongerACandidate = "These works no longer look like the same story." +    @Test("To-read status adoption moves the whole publication state, and ongoing history is not pristine",+          arguments: [false, true])+    func publicationStateAdoption(targetHasHistory: Bool) async throws {+        let library = try ToReadMergeFixture()+        let source = UUID(), target = UUID()+        let captured = try WorkPublicationState(status: .hiatus, currentPause: .init(+            start: CivilDateCodec.parse("2026-09-01")!,+            returnDate: CivilDateCodec.parse("2026-10-10")!))+        let history = try WorkPublicationState(status: .ongoing, closedPauses: [+            .init(start: nil, end: CivilDateCodec.parse("2026-09-20")!)])+        try library.seed { store in+            store.insertSite()+            let work = store.insertCaptured(id: source, title: "Serial", offset: 0)+            work.publicationStateData = try captured.canonicalData()+            let other = store.insertToRead(id: target, title: "Serial", offset: 20)+            other.publicationStateData = targetHasHistory ? try history.canonicalData() : nil+        }+        let repository = try await library.openForApp()+        let preview = try await repository.projectMerge(+            sourceWorkID: source, targetWorkID: target, request: .toReadMatch)+        let expected = targetHasHistory ? history : captured+        #expect(preview.outcome.publicationState == expected)+        #expect(preview.outcome.rawOverrides?.publicationStateData == (try expected.canonicalData()))+        if targetHasHistory { #expect(preview.outcome.discardedFields.contains(.sourcePublicationState)) }+        #expect(try await repository.commitMerge(preview) == .committed(targetID: target))+        let result = try await repository.work(id: target)+        #expect(result.publicationState == expected)+        #expect(result.authoredWorkStatus == expected.authoredStatus)+    }+     // MARK: - Req 4.2, 4.3: what the survivor carries      @Test("An unchanged library commits every override, and the survivor keeps the to-read UUID")
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationMergeTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationMergeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationMergeTests.swiftnew file mode 100644index 00000000..cf42e781--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationMergeTests.swift@@ -0,0 +1,64 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Publication state merge preservation", .serialized)+struct WorkPublicationMergeTests {+    @Test("Ordinary merge keeps the complete target state and reports differing source evidence")+    func ordinaryMergeKeepsTargetEnvelope() async throws {+        let fixture = try await M5Fixture()+        let source = try await fixture.repository.createWork(NewWorkDraft(displayTitle: "Source", hostname: "example.com"))+        let target = try await fixture.repository.createWork(NewWorkDraft(displayTitle: "Target", hostname: "example.com"))+        let kept = try WorkPublicationState(status: .hiatus, currentPause: .init(+            start: CivilDateCodec.parse("2026-09-01")!,+            returnDate: CivilDateCodec.parse("2026-10-10")!))+        let dropped = try WorkPublicationState(status: .ongoing, closedPauses: [+            .init(start: nil, end: CivilDateCodec.parse("2026-09-20")!)])+        try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding publication state") { context in+            for work in try context.fetch(FetchDescriptor<Work>()) {+                let state = work.id == target.id ? kept : dropped+                work.publicationStateData = try state.canonicalData()+                work.workStatusRaw = state.authoredStatus.rawValue+            }+            try context.save()+        }+        let preview = try await fixture.repository.projectMerge(sourceWorkID: source.id, targetWorkID: target.id)+        #expect(preview.outcome.publicationState == kept)+        #expect(preview.outcome.discardedFields.contains(.sourcePublicationState))+        #expect(try await fixture.repository.commitMerge(preview) == .committed(targetID: target.id))+        let result = try await fixture.repository.work(id: target.id)+        #expect(result.publicationState == kept)+        #expect(result.authoredWorkStatus == .hiatus)+    }+    @Test("A return-date-only change refreshes the merge preview")+    func returnDateChangesInvalidatePreview() async throws {+        let fixture = try await M5Fixture()+        let source = try await fixture.repository.createWork(NewWorkDraft(displayTitle: "Source", hostname: "example.com"))+        let target = try await fixture.repository.createWork(NewWorkDraft(displayTitle: "Target", hostname: "example.com"))+        let original = try WorkPublicationState(status: .hiatus, currentPause: .init(+            start: nil, returnDate: CivilDateCodec.parse("2026-10-10")!))+        let changed = try WorkPublicationState(status: .hiatus, currentPause: .init(+            start: nil, returnDate: CivilDateCodec.parse("2026-10-11")!))+        try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding return date") { context in+            let work = try #require(try context.fetch(FetchDescriptor<Work>()).first { $0.id == target.id })+            work.workStatus = .hiatus+            work.publicationStateData = try original.canonicalData()+            try context.save()+        }+        let preview = try await fixture.repository.projectMerge(sourceWorkID: source.id, targetWorkID: target.id)+        try await fixture.repository.withLockedContext(mode: .exclusive, operation: "changing return date") { context in+            let work = try #require(try context.fetch(FetchDescriptor<Work>()).first { $0.id == target.id })+            work.publicationStateData = try changed.canonicalData()+            try context.save()+        }+        guard case .refreshed(let fresh) = try await fixture.repository.commitMerge(preview) else {+            Issue.record("A changed return date must refresh the preview")+            return+        }+        #expect(fresh.outcome.publicationState == changed)+        #expect(try await fixture.repository.work(id: source.id).id == source.id)+    }++}
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationProjectionTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationProjectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationProjectionTests.swiftnew file mode 100644index 00000000..2986a9de--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationProjectionTests.swift@@ -0,0 +1,131 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Publication evidence follows authored content", .serialized)+struct WorkPublicationProjectionTests {+    private static func state(returnDate: String = "2026-09-30") throws -> WorkPublicationState {+        try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: CivilDateCodec.parse("2026-09-20"), returnDate: CivilDateCodec.parse(returnDate)))+    }++    private static func work() -> Work {+        let work = Work(displayTitle: "A Serial", timestamp: Date(timeIntervalSince1970: 0))+        work.lastParsedTitle = work.displayTitle+        work.titleProvenance = .parsed+        return work+    }++    private static func snapshot(_ work: Work) throws -> WorkSnapshot {+        try LibraryRepository.snapshot(work, entries: [], types: .empty, series: .empty, credits: .empty, history: .empty)+    }++    @Test("Snapshots retain authored status while explicit days resolve return and bases stay stable")+    func readOnlySnapshotAndBasis() throws {+        let work = Self.work()+        let state = try Self.state()+        work.workStatus = .hiatus+        work.publicationStateData = try state.canonicalData()+        let snapshot = try Self.snapshot(work)+        let basis = WorkEditBasis(work: snapshot)+        let content = GroupOrdering.authoredContent(of: work, types: .empty)+        let fingerprint = VariantID(components: content.orderComponents)+        #expect(snapshot.publicationState == state)+        #expect(snapshot.authoredWorkStatus == .hiatus)+        #expect(snapshot.effectiveWorkStatus(on: CivilDateCodec.parse("2026-09-29")!) == .hiatus)+        #expect(snapshot.effectiveWorkStatus(on: CivilDateCodec.parse("2026-09-30")!) == .ongoing)+        #expect(basis.matches(content, types: .empty))+        #expect(WorkEditBasis(work: try Self.snapshot(work)) == basis)+        #expect(VariantID(components: GroupOrdering.authoredContent(of: work, types: .empty).orderComponents) == fingerprint)+        work.publicationStateData = try Self.state(returnDate: "2026-10-01").canonicalData()+        #expect(!basis.matches(GroupOrdering.authoredContent(of: work, types: .empty), types: .empty))+    }++    @Test("Envelopes are authored, complete and canonical comparison includes completed history")+    func fingerprintsAndPristine() throws {+        let work = Self.work()+        #expect(GroupOrdering.authoredContent(of: work, types: .empty).isBare)+        let state = try WorkPublicationState(status: .ongoing, closedPauses: [+            .init(start: nil, end: CivilDateCodec.parse("2026-09-30")!),+        ])+        work.publicationStateData = try state.canonicalData()+        let content = GroupOrdering.authoredContent(of: work, types: .empty)+        #expect(!content.isBare)+        let key = VariantID(components: content.orderComponents)+        // JSON key layout is not a second authored value.+        work.publicationStateData = Data(#"{ "closedPauses": [{ "end": "2026-09-30" }], "status": "ongoing", "version": 1 }"#.utf8)+        #expect(GroupOrdering.authoredContent(of: work, types: .empty) == content)+        #expect(VariantID(components: GroupOrdering.authoredContent(of: work, types: .empty).orderComponents) == key)+    }++    @Test("A split snapshot carries one whole envelope while progress elects independently")+    func carrierAndIndependentProgress() throws {+        let bare = Self.work()+        let carrier = Self.work()+        carrier.id = bare.id+        carrier.publicationStateData = try Self.state().canonicalData()+        carrier.workStatus = .hiatus+        let newer = CatchUpConfirmation(latest: 100, confirmedAtMilliseconds: 2_000, countsUp: true, isEstimate: false)+        bare.catchUpConfirmationData = try JSONBlob.encode(newer)+        carrier.catchUpConfirmationData = try JSONBlob.encode(CatchUpConfirmation(+            latest: 90, confirmedAtMilliseconds: 1_000, countsUp: false, isEstimate: false))+        let group = try #require(LibraryRepository.workGroup(id: bare.id, rows: [bare, carrier], types: .empty))+        #expect(group.carrier === carrier)+        let snapshot = try LibraryRepository.snapshot(group, entryRows: [], canonicalWorkIDs: [:],+            types: .empty, series: .empty, credits: .empty, history: .empty)+        #expect(try snapshot.publicationState == Self.state())+        #expect(snapshot.catchUp.confirmation == newer)+        #expect(snapshot.publicationStateData == carrier.publicationStateData)+    }++    @Test("Malformed non-nil evidence is an explicit snapshot error")+    func malformedSnapshot() throws {+        let work = Self.work()+        work.publicationStateData = Data("invalid".utf8)+        #expect(throws: (any Error).self) { try Self.snapshot(work) }+    }++    @Test("Silent reconciliation copies the carrier's complete state and separately elected progress")+    func silentReconciliation() async throws {+        let fixture = try WriteFixture()+        let workID = UUID()+        let bytes = try Self.state().canonicalData()+        let confirmation = CatchUpConfirmation(latest: 100, confirmedAtMilliseconds: 2_000, countsUp: true, isEstimate: false)+        try fixture.seed { store in+            store.insertSite(hostname: "dup.example")+            let bare = store.insertWork(id: workID, hostname: "dup.example", title: "A Serial", offset: 0)+            let carrier = store.insertWork(hostname: "dup.example", title: "A Serial", offset: 60)+            carrier.workStatus = .hiatus+            carrier.publicationStateData = bytes+            bare.catchUpConfirmationData = try JSONBlob.encode(confirmation)+        }+        let repository = try await fixture.openForApp()+        _ = try await repository.reconcileAfterSync()+        let result = try await repository.work(id: workID)+        #expect(result.publicationStateData == bytes)+        #expect(result.catchUp.confirmation == confirmation)+        #expect(try fixture.workRows(id: workID).allSatisfy { $0.publicationStateData == bytes })+        await repository.shutdown()+    }++    @Test("Malformed sync evidence refuses reconciliation and is never rewritten as legacy")+    func malformedReconciliation() async throws {+        let fixture = try WriteFixture()+        let id = UUID()+        try fixture.seed { store in+            store.insertSite(hostname: "dup.example")+            store.insertWork(id: id, hostname: "dup.example", title: "A Serial", offset: 0)+        }+        let repository = try await fixture.openForApp()+        let bad = Data("invalid incoming evidence".utf8)+        try fixture.seedAdditional { store in+            let twin = store.insertWork(id: id, hostname: "dup.example", title: "A Serial", offset: 60)+            twin.publicationStateData = bad+        }+        await #expect(throws: (any Error).self) { try await repository.work(id: id) }+        await #expect(throws: (any Error).self) { try await repository.reconcileAfterSync() }+        #expect(try fixture.workRows(id: id).contains { $0.publicationStateData == bad })+        await repository.shutdown()+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationStateTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationStateTests.swiftnew file mode 100644index 00000000..2d8e18d0--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationStateTests.swift@@ -0,0 +1,156 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Publication state: civil dates, authored evidence and pause arithmetic")+struct WorkPublicationStateTests {+    static func day(_ spelling: String) -> CivilDay { CivilDateCodec.parse(spelling)! }+    static var calendar: Calendar {+        var calendar = Calendar(identifier: .gregorian)+        calendar.timeZone = TimeZone(secondsFromGMT: 0)!+        return calendar+    }++    @Test("A return resolves before, on and after its boundary without mutating evidence")+    func returnBoundary() throws {+        let state = try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: Self.day("2026-09-20"), returnDate: Self.day("2026-09-30")))+        let bytes = try state.canonicalData()+        #expect(state.status(on: Self.day("2026-09-29")) == .hiatus)+        #expect(state.pendingReturn(on: Self.day("2026-09-29")) == Self.day("2026-09-30"))+        for text in ["2026-09-30", "2026-10-20"] {+            #expect(state.status(on: Self.day(text)) == .ongoing)+            #expect(state.pendingReturn(on: Self.day(text)) == nil)+        }+        #expect(try state.canonicalData() == bytes)+        #expect(try WorkPublicationState.decode(bytes) == state)+        #expect(try WorkPublicationState(status: .hiatus, currentPause: .init(start: nil))+            .status(on: Self.day("2099-12-31")) == .hiatus)+        #expect(try WorkPublicationState(status: .finished).pendingReturn(on: Self.day("2026-09-29")) == nil)+    }++    @Test("Unknown-start legacy pauses exclude all pre-return releases")+    func unknownStartAndLegacy() throws {+        let work = Work(displayTitle: "Legacy", timestamp: Date(timeIntervalSince1970: 0))+        work.workStatus = .hiatus+        #expect(try work.decodedPublicationState() == nil)+        let state = try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: nil, returnDate: Self.day("2026-09-30")))+        #expect(state.excludingPauses(after: Self.day("2026-01-01"), through: Self.day("2026-09-29"),+            releaseDays: ReleaseDay.allCases, calendar: Self.calendar) == 0)+        #expect(state.excludingPauses(after: Self.day("2026-01-01"), through: Self.day("2026-10-01"),+            releaseDays: ReleaseDay.allCases, calendar: Self.calendar) == 2)+        work.publicationStateData = try state.canonicalData()+        #expect(try work.decodedPublicationState() == state)+        work.publicationStateData = Data("invalid".utf8)+        #expect(throws: (any Error).self) { try work.decodedPublicationState() }+    }++    @Test("Repeated pauses coalesce, drop empty intervals and retain history after return")+    func canonicalIntervals() throws {+        let state = try WorkPublicationState(status: .ongoing, closedPauses: [+            .init(start: Self.day("2024-03-05"), end: Self.day("2024-03-07")),+            .init(start: Self.day("2024-03-01"), end: Self.day("2024-03-05")),+            .init(start: Self.day("2024-03-06"), end: Self.day("2024-03-10")),+            .init(start: Self.day("2024-04-01"), end: Self.day("2024-04-01")),+        ])+        #expect(state.closedPauses == [.init(start: Self.day("2024-03-01"), end: Self.day("2024-03-10"))])+        #expect(state.status(on: Self.day("2024-03-05")) == .hiatus)+        #expect(state.isPaused(on: Self.day("2024-03-05")))+        #expect(!state.isPaused(on: Self.day("2024-03-10")))+        let sameDay = try WorkPublicationState(status: .hiatus,+            currentPause: .init(start: Self.day("2024-03-10"), returnDate: Self.day("2024-03-10")))+        #expect(sameDay.authoredStatus == .ongoing)+        #expect(sameDay.currentPause == nil)+        #expect(sameDay.closedPauses.isEmpty)+        #expect(try WorkPublicationState.decode(state.canonicalData()) == state)+    }++    @Test("Selected-day status and weekday eligibility match recorded intervals")+    func eligibilityOracle() throws {+        let origin = Self.day("2024-02-20")+        for seed in 0..<8 {+            let closedStart = 2 + seed+            let closedEnd = 7 + seed+            let currentStart = 20 + seed+            for dated in [false, true] {+                let currentEnd = dated ? 30 + seed : 60+                let state = try WorkPublicationState(status: .hiatus, closedPauses: [+                    .init(start: origin.adding(days: closedStart, calendar: Self.calendar),+                          end: origin.adding(days: closedEnd, calendar: Self.calendar))+                ], currentPause: .init(start: origin.adding(days: currentStart, calendar: Self.calendar),+                    returnDate: dated ? origin.adding(days: currentEnd, calendar: Self.calendar) : nil))+                let restored = try WorkPublicationState.decode(state.canonicalData())+                for mask in [1, 42, 85, 127] {+                    let weekdays = ReleaseDay.allCases.enumerated().compactMap {+                        mask & (1 << $0.offset) != 0 ? $0.element : nil+                    }+                    for offset in 0..<50 {+                        let day = origin.adding(days: offset, calendar: Self.calendar)+                        let paused = (closedStart..<closedEnd).contains(offset)+                            || (currentStart..<currentEnd).contains(offset)+                        #expect(restored.status(on: day) == (paused ? .hiatus : .ongoing))+                        #expect(TodaySchedule.isReleaseEligible(readingStatus: .reading,+                            workStatus: .hiatus, releaseDays: weekdays, publicationState: restored,+                            on: day, calendar: Self.calendar)+                            == (!paused && weekdays.contains(day.weekday(calendar: Self.calendar))))+                    }+                }+            }+        }+        let finished = try WorkPublicationState(status: .finished, closedPauses: [+            .init(start: nil, end: origin)+        ])+        #expect(finished.status(on: origin.adding(days: -1, calendar: Self.calendar)) == .finished)+    }++    @Test("Invalid dates, versions, status combinations and noncanonical intervals are errors")+    func rejectsInvalidPayloads() {+        let invalid = [+            #"{"version":2,"status":"ongoing","closedPauses":[]}"#,+            #"{"version":1,"status":"hiatus","closedPauses":[]}"#,+            #"{"version":1,"status":"ongoing","closedPauses":[],"currentPause":{"start":"2024-01-01"}}"#,+            #"{"version":1,"status":"hiatus","closedPauses":[],"currentPause":{"start":"2024-02-30"}}"#,+            #"{"version":1,"status":"hiatus","closedPauses":[],"currentPause":{"start":"2024-03-02","returnDate":"2024-03-01"}}"#,+            #"{"version":1,"status":"ongoing","closedPauses":[{"start":"2024-03-02","end":"2024-03-01"}]}"#,+            #"{"version":1,"status":"ongoing","closedPauses":[{"start":"2024-03-01","end":"2024-03-03"},{"start":"2024-03-02","end":"2024-03-05"}]}"#,+            #"{"version":1,"status":"hiatus","closedPauses":[{"start":"2024-03-01","end":"2024-03-03"}],"currentPause":{"start":"2024-03-02"}}"#,+        ]+        for text in invalid {+            #expect(throws: (any Error).self) { try WorkPublicationState.decode(Data(text.utf8)) }+        }+        for text in ["2024-2-01", "2024-02-1", "0000-01-01", "2023-02-29", "2024-02-30", " 2024-02-29"] {+            #expect(CivilDateCodec.parse(text) == nil)+        }+        #expect(CivilDateCodec.parse("2024-02-29") != nil)+    }++    @Test("All weekday sets match a seeded bounded oracle across leap day and DST", arguments: [0, 1, 2, 3])+    func arithmeticOracle(seed: Int) throws {+        var calendar = Self.calendar+        calendar.timeZone = TimeZone(identifier: ["UTC", "Australia/Melbourne", "America/New_York", "Europe/London"][seed])!+        let start = Self.day("2024-02-20")+        let end = Self.day("2024-04-20")+        let state = try WorkPublicationState(status: .hiatus, closedPauses: [+            .init(start: start.adding(days: 3 + seed, calendar: calendar), end: start.adding(days: 13 + seed, calendar: calendar)),+            .init(start: start.adding(days: 20, calendar: calendar), end: start.adding(days: 24, calendar: calendar)),+        ], currentPause: .init(start: start.adding(days: 30, calendar: calendar),+                              returnDate: start.adding(days: 39 + seed, calendar: calendar)))+        let marks = Set((1...55).filter { ($0 * 17 + seed) % 5 == 0 }.map { start.adding(days: $0, calendar: calendar) })+        for mask in 0..<128 {+            let weekdays = ReleaseDay.allCases.enumerated().compactMap { mask & (1 << $0.offset) != 0 ? $0.element : nil }+            let count = state.excludingPauses(after: start, through: end, releaseDays: weekdays,+                                               noEpisodeDays: marks, calendar: calendar)+            if weekdays.isEmpty { #expect(count == nil); continue }+            let oracle = (1...end.days(since: start, calendar: calendar)).map { start.adding(days: $0, calendar: calendar) }+                .filter { day in+                    let offset = day.days(since: start, calendar: calendar)+                    let paused = (3 + seed..<13 + seed).contains(offset)+                        || (20..<24).contains(offset) || (30..<39 + seed).contains(offset)+                    return weekdays.contains(day.weekday(calendar: calendar)) && !paused && !marks.contains(day) }.count+            #expect(count == oracle)+        }+        #expect(CivilDateCodec.spelling(Self.day("2024-02-29")) == "2024-02-29")+        #expect(CivilDay(Self.day("2024-02-29").date(in: calendar), calendar: calendar) == Self.day("2024-02-29"))+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationValidationTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationValidationTests.swiftnew file mode 100644index 00000000..8c7db8e4--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationValidationTests.swift@@ -0,0 +1,21 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Unreadable publication evidence refuses readiness", .serialized)+struct WorkPublicationValidationTests {+    @Test("Failed publication validation leaves readiness unchanged", arguments: ["18", "19"])+    func malformedStateCannotAdvanceReadiness(marker: String) async throws {+        let fixture = try WriteFixture()+        try fixture.seed { store in+            let work = store.insertWork(hostname: "dup.example", title: "A Serial", offset: 0)+            work.publicationStateData = Data("malformed publication evidence".utf8)+        }+        try Data("\(marker)\n".utf8).write(to: fixture.configuration.readinessMarkerURL)+        await #expect(throws: (any Error).self) {+            try await LibraryRepository.openForApp(fixture.configuration)+        }+        #expect(try String(contentsOf: fixture.configuration.readinessMarkerURL, encoding: .utf8) == "\(marker)\n")+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationWriterTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationWriterTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationWriterTests.swiftnew file mode 100644index 00000000..9bee18eb--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkPublicationWriterTests.swift@@ -0,0 +1,274 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Atomic publication edits", .serialized)+struct WorkPublicationWriterTests {+    private var calendar: Calendar {+        var value = Calendar(identifier: .gregorian)+        value.timeZone = TimeZone(secondsFromGMT: 0)!+        return value+    }+    private func day(_ text: String) -> CivilDay { CivilDateCodec.parse(text)! }+    private var today: CivilDay { day("2026-09-30") }++    private func seeded(status: WorkStatus = .ongoing, state: WorkPublicationState? = nil,+                        latest: Int? = 100, save: any RepositorySaveStrategy = InstrumentedSaveStrategy(),+                        clock: (any RepositoryClock)? = nil) async throws -> (M5Fixture, UUID) {+        let fixture = try await M5Fixture(clock: clock ?? FixedRepositoryClock(today.date(in: calendar)), saveStrategy: save)+        let work = try await fixture.repository.createWork(NewWorkDraft(displayTitle: "Serial", hostname: "example.com"))+        let confirmationAt = day("2026-09-28").date(in: calendar)+        try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding progress") { context in+            let row = try #require(try context.fetch(FetchDescriptor<Work>()).first)+            row.workStatus = status+            row.publicationStateData = try state?.canonicalData()+            row.releaseDays = ReleaseDay.allCases+            if let latest {+                row.catchUpConfirmationData = try JSONBlob.encode(CatchUpConfirmation(+                    latest: latest, confirmedAtMilliseconds: MillisecondInstant.milliseconds(confirmationAt),+                    countsUp: true, isEstimate: false))+            }+            row.lastChapterOverrideData = try JSONBlob.encode(LastChapterOverride.value(+                95, atMilliseconds: MillisecondInstant.milliseconds(confirmationAt)))+            try context.save()+        }+        return (fixture, work.id)+    }++    @Test("Saving hiatus today preserves yesterday through date edits, removal and early resume")+    func historicalReleaseAfterSave() async throws {+        for returnDate in [nil, day("2026-10-10")] {+            let (fixture, id) = try await seeded()+            let yesterday = today.adding(days: -1, calendar: calendar)+            let original = try await fixture.repository.work(id: id)+            func releases(_ selected: CivilDay) async throws -> [UUID] {+                let presentation = try await fixture.repository.todayPresentation(calendar: calendar)+                let snapshots = try await fixture.repository.works().works+                #expect(presentation.schedule == TodaySchedule.build(works: snapshots, calendar: calendar))+                return TodayDayPlan.build(day: selected, currentDay: today, schedule: presentation.schedule,+                    presentation: presentation, calendar: calendar).releases.map(\.id)+            }+            #expect(try await releases(yesterday) == [id])+            for intent in [WorkPublicationEdit.set(status: .hiatus, returnDate: returnDate),+                           .set(status: .hiatus, returnDate: day("2026-10-12")),+                           .set(status: .hiatus, returnDate: nil)] {+                let paused = try await edit(fixture, id: id, intent: intent)+                #expect(paused.publicationState?.currentPause?.start == today)+                #expect(paused.catchUp == original.catchUp)+                #expect(try await releases(yesterday) == [id])+                #expect(try await releases(today).isEmpty)+                #expect(try await fixture.repository.markNoEpisode(workID: id, day: today, calendar: calendar) != .committed)+            }+            let beforeBrowsing = try await fixture.repository.work(id: id)+            _ = try await releases(yesterday)+            #expect(WorkEditBasis(work: try await fixture.repository.work(id: id)) == WorkEditBasis(work: beforeBrowsing))+            #expect(try await fixture.repository.markNoEpisode(workID: id, day: yesterday, calendar: calendar) == .committed)+            let marked = try await fixture.repository.todayPresentation(calendar: calendar)+            #expect(TodayDayPlan.build(day: yesterday, currentDay: today, schedule: marked.schedule,+                presentation: marked, calendar: calendar).releases.first?.releaseState == .noEpisode)+            #expect(try await fixture.repository.undoNoEpisode(workID: id, day: yesterday) == .committed)+            #expect(try await releases(yesterday) == [id])+            let resumed = try await edit(fixture, id: id, intent: .set(status: .ongoing, returnDate: nil))+            #expect(resumed.catchUp == original.catchUp)+            #expect(try await releases(yesterday) == [id])+            #expect(try await releases(today) == [id])+        }+    }++    @Test("Save captures its day once even when persistence crosses midnight or fails")+    func saveCrossesMidnight() async throws {+        for fails in [false, true] {+            let clock = SeriesMutableClock(today.date(in: calendar).addingTimeInterval(86399))+            let strategy = MidnightSaveStrategy(clock: clock,+                nextDay: today.adding(days: 1, calendar: calendar).date(in: calendar))+            let (fixture, id) = try await seeded(save: strategy, clock: clock)+            let original = try await fixture.repository.work(id: id)+            strategy.arm(fails: fails)+            if fails {+                await #expect(throws: Error.self) {+                    try await fixture.repository.updateWork(id: id, basis: WorkEditBasis(work: original),+                        draft: draft(original, edit: .set(status: .hiatus, returnDate: nil)), calendar: calendar)+                }+            } else {+                _ = try await edit(fixture, id: id, intent: .set(status: .hiatus, returnDate: nil))+            }+            #expect(CivilDay(clock.now(), calendar: calendar) == today.adding(days: 1, calendar: calendar))+            let result = try await fixture.repository.work(id: id)+            #expect(result.catchUp == original.catchUp)+            #expect(result.publicationState?.currentPause?.start == (fails ? nil : today))+            #expect(result.effectiveWorkStatus(on: today) == (fails ? .ongoing : .hiatus))+            #expect(result.effectiveWorkStatus(on: today.adding(days: -1, calendar: calendar)) == .ongoing)+        }+    }++    @Test("An editor basis opened yesterday starts its new hiatus on today's Save")+    func editorCrossesMidnight() async throws {+        let clock = SeriesMutableClock(today.adding(days: -1, calendar: calendar).date(in: calendar))+        let (fixture, id) = try await seeded(clock: clock)+        let opened = try await fixture.repository.work(id: id)+        clock.set(today.date(in: calendar))+        #expect(try await fixture.repository.updateWork(id: id, basis: WorkEditBasis(work: opened),+            draft: draft(opened, edit: .set(status: .hiatus, returnDate: nil)), calendar: calendar) == .committed)+        #expect(try await fixture.repository.work(id: id).publicationState?.currentPause?.start == today)+    }++    @Test("A Save inside retained closed evidence retains the existing authoring refusal")+    func closedPauseAuthoringRefusal() throws {+        let state = try WorkPublicationState(status: .ongoing, closedPauses: [+            .init(start: day("2026-09-20"), end: day("2026-10-01"))+        ])+        #expect(throws: WorkPublicationState.StateError.invalidPause) {+            try WorkPublicationWriter.prepare(state: state, legacyStatus: .ongoing,+                edit: .set(status: .hiatus, returnDate: nil), today: today)+        }+    }+    private func draft(_ work: WorkSnapshot, edit: WorkPublicationEdit, days: [ReleaseDay]? = nil) -> WorkMetadataDraft {+        WorkMetadataDraft(displayTitle: work.displayTitle, typeAssignment: work.typeDisplay.assignment,+            genreTags: work.genreTags, genericNotes: "edited notes", publicationEdit: edit,+            readingStatus: work.readingStatus, verdict: work.verdict, releaseDays: days ?? work.releaseDays,+            membership: work.membership, thumbnail: .keep)+    }+    private func edit(_ fixture: M5Fixture, id: UUID, intent: WorkPublicationEdit,+                      days: [ReleaseDay]? = nil) async throws -> WorkSnapshot {+        let before = try await fixture.repository.work(id: id)+        #expect(try await fixture.repository.updateWork(id: id, basis: WorkEditBasis(work: before),+            draft: draft(before, edit: intent, days: days), calendar: calendar) == .committed)+        return try await fixture.repository.work(id: id)+    }++    @Test("Pausing and resuming preserves original confirmation and override bytes")+    func pauseResume() async throws {+        let (fixture, id) = try await seeded()+        let original = try await fixture.repository.work(id: id)+        let paused = try await edit(fixture, id: id, intent: .set(status: .hiatus, returnDate: day("2026-10-10")))+        #expect(paused.catchUp == original.catchUp)+        #expect(paused.publicationState?.currentPause?.start == today)+        #expect(CatchUpProgress.build(work: paused, day: today, calendar: calendar).effectiveLatest == 101)+        let resumed = try await edit(fixture, id: id, intent: .set(status: .ongoing, returnDate: nil))+        #expect(resumed.catchUp == original.catchUp)+        #expect(resumed.publicationState?.currentPause == nil)+        #expect(resumed.publicationState?.closedPauses.isEmpty == true)+        #expect(CatchUpProgress.build(work: resumed, day: today, calendar: calendar).effectiveLatest == 102)+    }++    @Test("Legacy hiatus keeps unknown start while changing and removing a return")+    func legacyHiatus() async throws {+        let (fixture, id) = try await seeded(status: .hiatus)+        let initial = try await fixture.repository.work(id: id)+        let dated = try await edit(fixture, id: id, intent: .set(status: .hiatus, returnDate: day("2026-10-10")))+        #expect(dated.publicationState?.currentPause?.start == nil)+        let undated = try await edit(fixture, id: id, intent: .set(status: .hiatus, returnDate: nil))+        #expect(undated.publicationState?.currentPause?.returnDate == nil)+        let resumed = try await edit(fixture, id: id, intent: .set(status: .ongoing, returnDate: nil))+        #expect(resumed.publicationState?.closedPauses == [.init(start: nil, end: today)])+        #expect(resumed.catchUp == initial.catchUp)+        #expect(CatchUpProgress.build(work: resumed, day: today, calendar: calendar).effectiveLatest == 101)+    }++    @Test("Unchanged elapsed returns preserve evidence; a renewed hiatus starts today")+    func elapsedAndRenewed() async throws {+        let state = try WorkPublicationState(status: .hiatus, currentPause: .init(+            start: day("2026-09-20"), returnDate: day("2026-09-29")))+        let (fixture, id) = try await seeded(status: .hiatus, state: state)+        let unchanged = try await edit(fixture, id: id, intent: .unchanged)+        #expect(unchanged.publicationState == state)+        let renewed = try await edit(fixture, id: id, intent: .set(status: .hiatus, returnDate: nil))+        #expect(renewed.publicationState?.closedPauses == [.init(start: day("2026-09-20"), end: day("2026-09-29"))])+        #expect(renewed.publicationState?.currentPause?.start == today)+        #expect(renewed.publicationState?.currentPause?.returnDate == nil)+    }++    @Test("Today returns normalize empty pauses and never invent a confirmation")+    func todayReturn() async throws {+        let (fixture, id) = try await seeded(latest: nil)+        let result = try await edit(fixture, id: id, intent: .set(status: .hiatus, returnDate: today))+        #expect(result.publicationState?.authoredStatus == .ongoing)+        #expect(result.publicationState?.closedPauses.isEmpty == true)+        #expect(result.publicationState?.currentPause == nil)+        #expect(result.catchUp.confirmation == nil)+    }++    @Test("Finishing an active hiatus rebases its paused estimate, preserving override")+    func finishPaused() async throws {+        let state = try WorkPublicationState(status: .hiatus, currentPause: .init(start: day("2026-09-29")))+        let (fixture, id) = try await seeded(status: .hiatus, state: state)+        let original = try await fixture.repository.work(id: id)+        let finished = try await edit(fixture, id: id, intent: .set(status: .finished, returnDate: nil))+        #expect(finished.catchUp.latest == 100)+        #expect(finished.catchUp.confirmation?.confirmedAtMilliseconds == MillisecondInstant.milliseconds(today.date(in: calendar)))+        #expect(finished.catchUp.override == original.catchUp.override)+        #expect(finished.publicationState?.closedPauses == [.init(start: day("2026-09-29"), end: today)])+    }++    @Test("Combined schedule and pause edits rebase once using resulting pause boundaries")+    func combinedSchedule() async throws {+        let save = InstrumentedSaveStrategy()+        let (fixture, id) = try await seeded(save: save)+        save.resetCounts()+        let paused = try await edit(fixture, id: id, intent: .set(status: .hiatus, returnDate: nil), days: [.monday])+        #expect(save.attemptCount == 1)+        #expect(paused.catchUp.latest == 101)+        #expect(paused.catchUp.confirmation?.confirmedAtMilliseconds == MillisecondInstant.milliseconds(today.date(in: calendar)))+    }++    @Test("Expired selections and failed saves leave publication and progress untouched")+    func refusalAndRollback() async throws {+        let save = InstrumentedSaveStrategy()+        let (fixture, id) = try await seeded(save: save)+        let before = try await fixture.repository.work(id: id)+        await #expect(throws: Error.self) {+            try await fixture.repository.updateWork(id: id, basis: WorkEditBasis(work: before),+                draft: draft(before, edit: .set(status: .hiatus, returnDate: day("2026-09-29"))), calendar: calendar)+        }+        #expect(try await fixture.repository.work(id: id).publicationState == nil)+        save.shouldFail = true+        await #expect(throws: Error.self) {+            try await fixture.repository.updateWork(id: id, basis: WorkEditBasis(work: before),+                draft: draft(before, edit: .set(status: .hiatus, returnDate: today), days: []), calendar: calendar)+        }+        let after = try await fixture.repository.work(id: id)+        #expect(after.publicationState == nil)+        #expect(after.catchUp == before.catchUp)+    }+    @Test("Metadata-only edits copy the carrier state to bare synchronized siblings")+    func unchangedFansOutCarrier() async throws {+        let state = try WorkPublicationState(status: .hiatus, currentPause: .init(+            start: nil, returnDate: day("2026-10-10")))+        let (fixture, id) = try await seeded(status: .hiatus, state: state)+        let bytes = try state.canonicalData()+        let timestamp = today.date(in: calendar)+        try await fixture.repository.withLockedContext(mode: .exclusive, operation: "adding bare sibling") { context in+            let sibling = Work.create(in: context, id: id, title: "Serial", hostname: "example.com", timestamp: timestamp)+            sibling.titleProvenance = .parsed+            sibling.lastParsedTitle = "Serial"+            try context.save()+        }+        _ = try await edit(fixture, id: id, intent: .unchanged)+        let values = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking sibling state") { context in+            try context.fetch(FetchDescriptor<Work>()).map { ($0.publicationStateData, $0.workStatusRaw) }+        }+        #expect(values.count == 2)+        #expect(values.allSatisfy { $0.0 == bytes && $0.1 == "hiatus" })+    }++}++private final class MidnightSaveStrategy: RepositorySaveStrategy, @unchecked Sendable {+    private let lock = NSLock()+    private let clock: SeriesMutableClock+    private let nextDay: Date+    private var armed = false+    private var fails = false+    init(clock: SeriesMutableClock, nextDay: Date) { self.clock = clock; self.nextDay = nextDay }+    func arm(fails: Bool) { lock.withLock { armed = true; self.fails = fails } }+    func save(_ context: ModelContext) throws {+        let action = lock.withLock { (armed, fails) }+        if action.0 {+            clock.set(nextDay)+            if action.1 { throw CocoaError(.fileWriteUnknown) }+        }+        try context.save()+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/WorkSnapshotMembershipTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkSnapshotMembershipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkSnapshotMembershipTests.swiftindex c5f86537..2954ec04 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkSnapshotMembershipTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkSnapshotMembershipTests.swift@@ -190,7 +190,7 @@ struct WorkSnapshotMembershipTests {             ])          let fresh = try await fixture.repository.work(id: Self.workID)-        #expect(fresh.workStatus == .ongoing)+        #expect(fresh.authoredWorkStatus == .ongoing)         #expect(fresh.readingStatus == .reading)         #expect(fresh.verdict == "") @@ -199,7 +199,7 @@ struct WorkSnapshotMembershipTests {             verdict: "lost the thread")          let work = try await fixture.repository.work(id: Self.workID)-        #expect(work.workStatus == .finished)+        #expect(work.authoredWorkStatus == .finished)         #expect(work.readingStatus == .abandoned)         #expect(work.verdict == "lost the thread") 
Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swiftindex 44d59c69..1c3996b7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkThumbnailRepositoryTests.swift@@ -467,7 +467,7 @@ struct WorkThumbnailRepositoryTests {     ) -> WorkMetadataDraft {         WorkMetadataDraft(             displayTitle: "A Serial", typeAssignment: .none, genreTags: [],-            genericNotes: notes, workStatus: .ongoing, readingStatus: .reading, verdict: "",+            genericNotes: notes, publicationEdit: .unchanged, readingStatus: .reading, verdict: "",             releaseDays: [],             membership: nil, thumbnail: thumbnail)     }
Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swiftindex 866ed58f..ebb6995a 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: AsterismSchemaV18.self)+            let schema = Schema(versionedSchema: AsterismSchemaV19.self)             container = try ModelContainer(-                for: schema, migrationPlan: AsterismV18MigrationPlan.self,+                for: schema, migrationPlan: AsterismV19MigrationPlan.self,                 configurations: [                     ModelConfiguration(                         "AsterismV3", schema: schema,
Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swiftindex 42a6a240..206c5da7 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: AsterismSchemaV18.self)+            let schema = Schema(versionedSchema: AsterismSchemaV19.self)             container = try ModelContainer(-                for: schema, migrationPlan: AsterismV18MigrationPlan.self,+                for: schema, migrationPlan: AsterismV19MigrationPlan.self,                 configurations: [                     ModelConfiguration(                         "AsterismV3", schema: schema,
Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swiftindex c425ffe4..f137df61 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: AsterismSchemaV18.self)+            let schema = Schema(versionedSchema: AsterismSchemaV19.self)             let configuration = ModelConfiguration(                 "AsterismV3", schema: schema,                 url: directory.appending(path: "library.store"), cloudKitDatabase: .none)             container = try ModelContainer(-                for: schema, migrationPlan: AsterismV18MigrationPlan.self,+                for: schema, migrationPlan: AsterismV19MigrationPlan.self,                 configurations: [configuration])             context = ModelContext(container)         }
Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swiftindex d1306ccb..33059d1c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeWritePathTests.swift@@ -199,7 +199,7 @@ struct WorkTypeWritePathTests {             draft: WorkMetadataDraft(                 displayTitle: work.displayTitle, typeAssignment: assignment,                 genreTags: work.genreTags, genericNotes: work.genericNotes,-                workStatus: work.workStatus, readingStatus: work.readingStatus,+                publicationEdit: .unchanged, readingStatus: work.readingStatus,                 verdict: work.verdict, releaseDays: [], membership: nil,                 thumbnail: .keep), calendar: .current)         #expect(outcome == .committed)
Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swiftindex b9eae53f..ab2d3879 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let container = try ModelContainer(             for: schema,             configurations: [ModelConfiguration(@@ -418,7 +418,7 @@ struct WriteSiteRelationshipTests {         let context = ModelContext(container)          try LibraryRepository.materializeArchive(-            BackupImportPayload(BackupV17Fixtures.minimalTaughtPayload()), into: context)+            BackupImportPayload(BackupV18Fixtures.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) == "18",+        #expect(try markerContent(cfg) == "19",                 "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) == "18", "the import republishes nothing")+        #expect(try markerContent(cfg) == "19", "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) == "18")+        #expect(try markerContent(cfg) == "19")         try expectEveryRelationshipPopulated(cfg)         withExtendedLifetime(dir) {}     }@@ -553,7 +553,7 @@ struct WriteSiteRelationshipTests {     }      private func importPlan() throws -> BackupImportPlan {-        let payload = BackupImportPayload(BackupV17Fixtures.minimalTaughtPayload())+        let payload = BackupImportPayload(BackupV18Fixtures.minimalTaughtPayload())         return BackupImportPlan(             metadata: BackupImportMetadata(                 formatVersion: 8, schemaVersion: 9, appBuild: "test",
Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLCompatibilityTests.swiftindex 8c05ae91..ea3bcf6c 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(BackupV17Document.formatVersion == 17)-        #expect(BackupV17Document.schemaVersion == 18)+        #expect(BackupV18Document.formatVersion == 18)+        #expect(BackupV18Document.schemaVersion == 19)     }      @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 BackupV17Codec.decode(archive)+        let decoded = try BackupV18Codec.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 = BackupV17Exporter(+        let exporter = BackupV18Exporter(             repository: repository, stagingDirectory: directory.appending(path: "staging"))         let result = try await exporter.export(-            metadata: BackupV17Metadata(+            metadata: BackupV18Metadata(                 appBuild: "test-1.0",                 exportedAt: WrongHostWorkURLCompatibilityTests.epoch))         let data = try Data(contentsOf: result.fileURL)
Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLImportTests.swiftindex 77c68c54..2e63455e 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.             [-                BackupV17Membership(+                BackupV18Membership(                     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?-) -> BackupV17Membership {-    BackupV17Membership(+) -> BackupV18Membership {+    BackupV18Membership(         id: id, workID: work, hostname: hostname, createdAt: epoch,         urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil,         workURLString: workURL) } -private func url(of records: [BackupV17Membership], _ id: UUID) -> String? {+private func url(of records: [BackupV18Membership], _ id: UUID) -> String? {     records.first { $0.id == id }?.workURLString ?? nil } @@ -418,14 +418,14 @@ private func url(of records: [BackupV17Membership], _ id: UUID) -> String? { /// a test can address them. private func makePlan(     activePattern: Bool = true,-    memberships: (_ workID: UUID, _ otherMembershipID: UUID) -> [BackupV17Membership]+    memberships: (_ workID: UUID, _ otherMembershipID: UUID) -> [BackupV18Membership] ) -> BackupImportPlan {     let workID = UUID()     let otherMembershipID = UUID()     let patternID = UUID()     let rawURL = "https://\(siteHostname)/chapter/1" -    let entry = BackupV17Entry(+    let entry = BackupV18Entry(         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 = BackupV17Work(+    let work = BackupV18Work(         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 = [-        BackupV17TitlePattern(+        BackupV18TitlePattern(             id: patternID, siteHostname: siteHostname, version: 1, isActive: activePattern,             createdAt: epoch,             definition: StoredPatternDefinition(definition: .wholeTitle))     ]     let sites = [siteHostname, otherHostname].map {-        BackupV17Site(hostname: $0, displayName: $0, mode: $0 == siteHostname ? .taught : .untaught)+        BackupV18Site(hostname: $0, displayName: $0, mode: $0 == siteHostname ? .taught : .untaught)     }     let payload = BackupImportPayload(         entries: [entry], works: [work], sites: sites, titlePatterns: patterns,
Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift Modified
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swiftindex 81a844b4..e18519a4 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: AsterismSchemaV18.self)+        let schema = Schema(versionedSchema: AsterismSchemaV19.self)         let configuration = ModelConfiguration(             "AsterismV3", schema: schema,             url: directory.appending(path: "library.store"), cloudKitDatabase: .none)         container = try ModelContainer(-            for: schema, migrationPlan: AsterismV18MigrationPlan.self,+            for: schema, migrationPlan: AsterismV19MigrationPlan.self,             configurations: [configuration])         context = ModelContext(container)     }

Docs (11)

CHANGELOG.md Modified
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3bc83eaf..1b7f6a40 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,8 +6,50 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ## [Unreleased] +### Added++- **Hiatus end date — Review explanation (T-2375):** document publication-state+  behavior at three expertise levels, verification evidence and the remaining+  two-Development-device before-merge prerequisite.++- **Hiatus end date — Save-day correction plan (T-2375):** define successful+  Save as the start of a new hiatus, preserving earlier scheduled releases and+  gaps between pauses. Approve dated/undated eligibility regressions and+  follow-up tasks 20–22 using existing V19 publication state.++- **Hiatus end date — Interface and verification phase (T-2375):** add native+  return-date controls, draft preservation and current-day status presentation.+  Verify save/cancel, same-day return, renewed hiatus and accessibility on phone+  and iPad. Full Core, simulator units, affected UI and signed Xcode MCP Mac+  gates pass. Record the remaining two-Development-device before-merge check.++- **Hiatus end date — Release behaviour phase (T-2375):** exclude pauses from+  chapter estimates while retaining confirmation and read bounds. Add atomic+  publication edits, complete archive 18/19 state round trips, and share+  selected-day eligibility between Today, shortcuts and no-episode commands.+  Focused Core, simulator unit and signed Xcode MCP Mac checks pass.++- **Hiatus end date — Core and persistence phase (T-2375):** add V19+  publication-state storage with retained V16–V18 upgrades, strict civil-date+  decoding and interval-based pause arithmetic. Preserve the selected authored+  state through snapshots, fingerprints, reconciliation and merges. Advance+  the archive envelope to 18/19; payload support follows in the next phase.+  Focused Core and simulator checks pass; signed Mac build passes via Xcode MCP.++- **Hiatus end date — Specification (T-2375):** document approved requirements,+  design, decisions and 19 implementation tasks for announced returns from+  hiatus, normal release schedules and pause-aware chapter estimates. Add+  implementation prerequisites and register the feature in the specs overview.+ ### Fixed +- **Hiatus end date — Save-day eligibility correction (T-2375):** retain+  scheduled releases before a saved hiatus begins, including undated hiatus,+  and resolve past dates against recorded pauses and gaps. Verify Save-day and+  midnight boundaries, dated/undated phone and iPad journeys, full Core and+  simulator gates, and a signed Xcode MCP Mac build. Reuse existing persistence+  and catch-up contracts; two-Development-device verification remains before merge.+ - **No-episode review hardening (T-2374):** isolate targeted work reads from   unrelated corrupt actions and validate note-clear keys without breaking   retained keys after work merges. Recognize concrete plain-text share types
CLAUDE.md Modified
diff --git a/CLAUDE.md b/CLAUDE.mdindex a897b90b..78df01ac 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -85,9 +85,10 @@ bar. `make verify-identity` (a `test-core` prerequisite) is an identity lint, not a style one: it checks the App Group / CloudKit identifier declarations without building anything — see `specs/configuration-identity/`. -**The live store schema is V17** (`specs/catch-up-progress/`), the readiness-marker generation is `"17"`, `AsterismSchemaV16` is the one frozen snapshot left,-and the archive generation is **16/17**. The archive envelope test pins its+**The live store schema is V19** (`specs/hiatus-end-date/`), the readiness+marker generation is `"19"`, and the retained migration chain is V16 → V17 →+V18 → V19. V16, V17 and V18 are frozen snapshots; app markers 16–19 remain+accepted, while the extension opens only 19. The archive generation is **18/19**. The archive envelope test pins its schema version to the live store. `docs/agent-notes/schema-migration.md` is the procedure for moving all four. 
docs/agent-notes/device-installation.md Modified
diff --git a/docs/agent-notes/device-installation.md b/docs/agent-notes/device-installation.mdindex e3b513f3..cc34cd2c 100644--- a/docs/agent-notes/device-installation.md+++ b/docs/agent-notes/device-installation.md@@ -31,4 +31,17 @@ to fall under an approved folder; a parent-folder grant can cover future worktrees. Do not broaden grants automatically.  The existing Personal/Development device-run rules in `CLAUDE.md` still apply.-Builds and tests otherwise continue using the Makefile.+Tests otherwise continue using the Makefile.++## Mac builds++Owner instruction, 2026-09-30: use **Xcode MCP for macOS builds**. CLI signing+also failed with `errSecInternalComponent` for the Development Mac extension;+the same worktree built successfully through MCP.++Open the worktree's project, explicitly select the requested scheme and the+native `My Mac` destination, then use `BuildProject` with `buildForTesting: false`.+Verify success from the tool result and confirm the built app contains+`Contents/PlugIns/AsterismShareExtensionMac.appex`, retaining the Makefile's+embedded-extension gate. Do not run Mac tests or launch the app for this build+check. Existing Personal device-run approval rules still apply to launches.
specs/OVERVIEW.md Modified
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex d20bc937..fedfb3c5 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -57,6 +57,7 @@ | [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. |+| [Hiatus End Date](#hiatus-end-date) | 2026-09-30 | Done | Full spec (T-2375). All 22 tasks complete, including save-day eligibility that preserves earlier releases for dated and undated hiatus. Core, simulator, focused phone/iPad UI and signed Xcode MCP Mac gates pass. Two-Development-device sync verification remains before merge. |  --- @@ -936,3 +937,17 @@ Full spec (T-2374). The release context menu marks or unmarks the selected date. - [decision_log.md](no-episode-today/decision_log.md) - [verification-run.md](no-episode-today/verification-run.md) - [implementation.md](no-episode-today/implementation.md)++## Hiatus End Date++**Created:** 2026-09-30 · **Status:** Done — all 22 tasks complete and automated gates passed; two-Development-device verification remains before merge.++Full spec (T-2375). Records an announced return date in the Work Status editor. Effective status, Today projections and shortcut answers derive the return without background writes; normal weekdays and existing reading-status rules apply. Retained pause intervals exclude hiatus days from chapter estimates while preserving original confirmation and note boundaries. Schema V19 adds one optional Work attribute, archive 18/19 preserves the state, and V16/V17/V18 upgrade paths remain supported.++- [requirements.md](hiatus-end-date/requirements.md)+- [design.md](hiatus-end-date/design.md)+- [tasks.md](hiatus-end-date/tasks.md)+- [decision_log.md](hiatus-end-date/decision_log.md)+- [prerequisites.md](hiatus-end-date/prerequisites.md)+- [verification-run.md](hiatus-end-date/verification-run.md)+- [implementation.md](hiatus-end-date/implementation.md)
specs/hiatus-end-date/decision_log.md Modified
diff --git a/specs/hiatus-end-date/decision_log.md b/specs/hiatus-end-date/decision_log.mdnew file mode 100644index 00000000..f7d2d83d--- /dev/null+++ b/specs/hiatus-end-date/decision_log.md@@ -0,0 +1,115 @@+# Decision Log: Hiatus End Date++## Quick Decisions++| ID | Date | Decision | Rationale |+|----|------|----------|-----------|+| Q1 | 2026-09-29 | Use the full spec workflow for T-2375. | Owner approved the scope assessment: the feature adds persisted data and needs decisions about return-date behaviour. |+| Q2 | 2026-09-29 | Name the feature `hiatus-end-date`. | Owner approved the name derived from the ticket. |+| Q3 | 2026-09-29 | Automatically change the work to ongoing on its return date. | Owner wants the announced date to end the hiatus without a manual status change. |+| Q4 | 2026-09-29 | Follow normal release weekdays after returning. | Owner confirmed the return date does not create an extra release. |+| Q5 | 2026-09-29 | Resume chapter estimates after the hiatus period. | Owner confirmed hiatus days must not inflate estimated chapter counts. |+| Q6 | 2026-09-29 | Allow today and future return dates, using Today's local calendar day. | Owner approved; saving today ends the hiatus immediately. |+| Q7 | 2026-09-29 | Clear the pending return date when the work becomes ongoing or finished. | Owner approved; a later hiatus must not reuse an old date. The pending date can be changed or removed before expiry. |+| Q8 | 2026-09-29 | Preview releases and estimates from the announced return date when browsing future dates. | Owner approved seeing the projected return while the work remains on hiatus today. |+| Q9 | 2026-09-29 | Preserve the existing paused estimate for works whose hiatus start is unknown. | Owner approved resuming from the return date without reconstructing unavailable history. |+| Q10 | 2026-09-29 | Manual early return resumes estimates from the day of the status change. | Owner approved excluding the elapsed hiatus under the existing counting rules. |+| Q11 | 2026-09-29 | Requirements approved; proceed to design. | Owner explicitly approved the updated requirements and asked to continue. |+| Q12 | 2026-09-30 | Keep V16 and V17 migration support when adding V19. | Live V18 retains both stages; there is no approved population check allowing retirement. |+| Q13 | 2026-09-30 | Retain the existing concurrent schedule/progress-edit limitation. | Peer review found that an offline schedule rebase can contain increments from an unseen hiatus; the existing independent confirmation election cannot reverse them. Hiatus-only edits create no confirmation. Set latest remains the correction path. |+| Q14 | 2026-09-30 | Design approved, including Decisions 2 and 3; proceed to task planning. | Owner approved after receiving the spec documents on their phone. |+| Q15 | 2026-09-30 | All 19 implementation tasks approved. | Owner reviewed the task plan and asked to continue; branch selection is the remaining spec setup step. |+| Q16 | 2026-09-30 | Use `T-2375/hiatus-end-date` as the implementation branch. | Owner approved the proposed branch name and requested committing all prepared files. |+| Q17 | 2026-10-01 | A newly saved hiatus starts on its successful Save's local day; preserve scheduled releases before that day. | Owner observed retroactive disappearance and requested updating requirements/design. Today has day-level schedules, so Save takes effect immediately with its day as the first paused day. Keep unknown-start legacy treatment and reuse existing pause boundaries; no intraday release history is introduced. |+| Q18 | 2026-10-01 | Save-day/historical-release requirements and design approved; prepare follow-up tasks. | Owner explicitly approved the revised documents and requested task creation and implementation. Task-plan approval remains the workflow's next gate. |+| Q19 | 2026-10-01 | Follow-up tasks 20–22 approved; commit the plan and implement through make-it-so with a subagent. | Owner explicitly approved the task plan and authorized implementation. |++## Decision 1: Derive Automatic Return Without Background Writes++**Date**: 2026-09-30+**Status**: accepted++### Context++The release shortcut must recognize a return without opening the app. Future-date browsing must project the return without changing today's status, and estimates need the return boundary after the pending date disappears.++### Decision++Resolve effective status and pending return date from stored publication state and an explicit civil day. Expiry performs no write. Preserve its date internally as estimate evidence. The owner explicitly approved this approach.++### Rationale++Every reader can resolve the same state without depending on a background execution opportunity or another device's save. Authored fingerprints remain stable when time passes.++### Alternatives Considered++- **Background transition at midnight:** cannot ensure execution and creates redundant writes across devices.+- **Materialize on next app launch:** leaves cold shortcuts dependent on a separate writer and needs crash/retry coordination with estimate rebasing.++### Consequences++**Positive:** read-only expiry, deterministic future projections, no return-time save failure.++**Negative:** every status consumer must explicitly distinguish authored state from day-dependent presentation; internal evidence outlives the visible pending date.++---++## Decision 2: Store Publication State as One Authored Value++**Date**: 2026-09-30+**Status**: accepted++### Context++Effective status, return date and excluded pause periods must agree. Estimates can span multiple pauses, including a legacy hiatus whose beginning is unknown. The existing Work grouping and explicit merge flows select authored content from a carrier.++### Decision++Use one optional, versioned publication-state blob containing authored status, closed pause intervals and the current pause. A nil value retains legacy behaviour. Select and copy the value with its authored carrier; do not independently merge its fields or add action rows. Keep completed intervals for arithmetic without exposing a history editor.++### Rationale++One value prevents partial status/date delivery from inventing a return. Closed intervals preserve releases-since calculations across repeated pauses without storing a mutable count for every possible last-read date.++### Alternatives Considered++- **Independent status, start and return columns:** permits mismatched values during sync and cannot retain more than one pause.+- **One resume lower bound:** loses releases between earlier pauses when the last-read date predates them.+- **Append-only transition actions:** adds a new conflict policy and tables beyond the existing authored-content semantics required here.++### Consequences++**Positive:** coherent per-work state, no new table, correct union of excluded days.++**Negative:** all authored-copy and backup paths must preserve the blob; concurrent edits retain existing whole-value conflict limitations; interval storage grows with recorded pauses.++---++## Decision 3: Preserve Baselines Across the Return Boundary++**Date**: 2026-09-30+**Status**: accepted++### Context++The existing generic status rebase confirms an estimate on the day of the edit. Applying it on manual return excludes that day's release, while applying it only when the app next opens loses releases between the announced return and the opening day.++### Decision++Status/date-only hiatus edits preserve catch-up confirmation and override values. Count eligible days outside recorded pauses, including days before a known pause start, so both confirmation and last-read branches pause and resume without changing their bounds. An existing unknown-start hiatus contributes no pre-return accrual. Explicit schedule and finished-status changes retain the existing rebasing rules, evaluated with pause-aware arithmetic.++### Rationale++The return day can contribute its normal release once, independently of when the reader opens the app. Actual notes and confirmations remain authoritative. Critic and peer review exposed same-day suppression and higher-note double counting when an estimate is frozen into a new confirmation. Retaining the two original bounds avoids both errors and needs no added confirmation field.++### Alternatives Considered++- **Rebase on return-day Save:** the exclusive confirmation-day bound suppresses a release due that day.+- **Rebase on late launch:** counts from the launch day rather than the announced return and introduces a read-time mutation.+- **Separate accrual date on a frozen confirmation:** introduces extra metadata and must preserve the provenance of competing note/confirmation bounds; pause intervals already express the needed exclusion.++### Consequences++**Positive:** explicit return-day arithmetic and no duplicate increments across launches.++**Negative:** counting while paused must retain pre-pause accrual; explicit schedule edits still have their existing confirmation-day and concurrent-edit limitations.
specs/hiatus-end-date/design.md Modified
diff --git a/specs/hiatus-end-date/design.md b/specs/hiatus-end-date/design.mdnew file mode 100644index 00000000..7b1729fc--- /dev/null+++ b/specs/hiatus-end-date/design.md@@ -0,0 +1,166 @@+# Design: Hiatus End Date++Transit: T-2375. Save-day hiatus boundaries and historical release eligibility.++## Overview++Store an optional publication-state value on each Work and derive its effective status for a supplied civil day. The same value excludes hiatus days from release calculations, including future projections; reaching a return date performs no write (Decision 1).++## Data Model++Add `publicationStateData: Data? = nil` to Work in V19. The versioned, canonical JSON value `WorkPublicationState` contains:++| Field | Meaning |+|---|---|+| `version` | Initially 1; reject unsupported versions |+| `status` | Authored work status, including hiatus with an announced return |+| `closedPauses` | Sorted, disjoint civil-date intervals `[start, end)`; start can be unknown only for a legacy hiatus |+| `currentPause` | Present exactly when authored status is hiatus: start is the successful new-hiatus Save's local day; optional return date; start is unknown only for legacy hiatus |++A nil column means the legacy status in `workStatusRaw`, with no recorded pauses. On its first explicit publication edit, a legacy hiatus acquires an unknown-start pause: keep it current when setting a return date, or close it at today when manually resuming. No migration guesses a start date. Preserve the existing paused catch-up baseline; an unknown-start pause excludes dates before its end from new release arithmetic.++Capture a new hiatus start inside the publication-write transaction, using its single clock/calendar value. That captured day is the boundary even if persistence completes after midnight; it takes effect only if Save succeeds. Do not use editor entry, picker selection, work creation or a later date edit as the start. Today's unit is a civil day: after Save, its captured day is paused, and earlier calendar days remain eligible. There is no release-time or sub-day history model. The existing V19 envelope already carries the required boundaries; no extra column or envelope version is needed (Q17).++The envelope is authoritative when present. Keep `workStatusRaw` as its authored-status compatibility mirror, written in the same explicit edit; never use that mirror to override a valid envelope. Status and pause boundaries travel in one attribute, avoiding partial delivery of separately stored status/date fields. Do not elect pause history independently of its authored content carrier. Existing concurrent Work-edit conflict semantics apply; this is not an event log or a new multi-device merge policy (Decision 2).++Encode dates as validated Gregorian `YYYY-MM-DD` strings, using `CivilDay` semantics. Extract the strict parser currently inside `NoEpisodeHistory.Action` into a shared civil-date codec, keeping its accepted spellings unchanged. Reject invalid dates, reversed intervals, invalid open/closed combinations and unsupported envelope versions. Writers normalize interval order and coalesce overlap; decoding validates canonical structure. An empty interval is omitted.++Keep completed pause intervals internally across later hiatuses and explicit status changes: a last-read date can precede more than one pause. There is no history editor. Date clearing in requirement 1.6 concerns the pending date: `pendingReturn(on:)` returns nil once effective status is ongoing or finished. The internal evidence remains available to arithmetic and backup.++Keep `CatchUpConfirmation` and its timestamp election unchanged. A status/date-only hiatus edit leaves the confirmation and override untouched; recorded pause intervals provide the pause in arithmetic.++## Pure Components and Contracts++New Core files live in `Packages/AsterismCore/Sources/AsterismCore/`.++```swift+// WorkPublicationState.swift+func status(on day: CivilDay) -> WorkStatus+func pendingReturn(on currentDay: CivilDay) -> CivilDay?+func excludingPauses(after start: CivilDay, through end: CivilDay,+    releaseDays: [ReleaseDay], noEpisodeDays: Set<CivilDay>,+    calendar: Calendar) -> Int?++// WorkPublicationWriter.swift — stages changes, never saves+enum WorkPublicationEdit {+    case unchanged+    case set(status: WorkStatus, returnDate: CivilDay?)+}+```++For envelope-backed ongoing or hiatus works, `status(on: d)` returns hiatus exactly when `isPaused(on: d)` is true, otherwise ongoing. A known-start current pause covers `[S, R)` with a return, or `[S, infinity)` without one; closed pauses cover their stored intervals. Thus days before S and gaps between repeated pauses remain ongoing, and R itself is eligible under normal weekdays. Authored finished remains finished under the existing finished-status policy. A nil envelope keeps legacy status behaviour; an unknown-start legacy pause has no invented lower bound. This resolver is read-only and has no ambient clock. Browsing a past or future date changes only its input.++Count ordinary release weekdays in `(start, end]`, subtract the union of recorded pause days, and subtract no-episode dates only where they were not already excluded by a pause. Retain the existing whole-week arithmetic in `TodayDayPlan.releaseCount`; count interval intersections arithmetically rather than enumerating every day. A pause is start-inclusive and return-exclusive, so the return day's weekday counts once. A caller's confirmation/read bound still excludes its own day. Complexity is proportional to pause intervals and no-episode marks, not elapsed calendar days.++Both `CatchUpProgress.build` overloads resolve publication state for their requested day. For an envelope-backed ongoing or hiatus work, count eligible days outside its pauses, including days before a known pause start: the count therefore stays frozen while paused and resumes after its end. Finished works still accrue zero. Legacy hiatus with no envelope keeps its existing zero-accrual rule. Do not retain an unconditional `workStatus == .ongoing` guard that would discard pre-pause accrual or block future return projections. Keep the existing confirmation/read bounds, estimate flag, unknown state, cap and count-up switch. A returned work with count-up off stays unincremented. `TodayDayPlan.row` uses the same pause-aware helper for `releasesSince`, preserving that field's existing count-up semantics.++## Explicit Edits and Estimate Boundaries++Add a required `publicationEdit` to `WorkMetadataDraft`; remove its separate writable `workStatus` field so every caller explicitly preserves or changes publication state. Extend `WorkEditBasis`/content fingerprints with the authored envelope. Wall-clock passage is not a content change and cannot invalidate an otherwise unchanged edit basis.++`LibraryRepository.updateWork` resolves the current group and stages publication and catch-up changes inside its existing exclusive lock and single save. Use one captured `clock.now()` and calendar for the whole operation. The writer affects every row of the resolved group and leaves `CatchUpRecord.override` intact.++| Edit | Publication and estimate handling |+|---|---|+| Title, notes or reading-status edit only | `.unchanged`; preserve the envelope, even if its return passed while editing |+| Enter a new hiatus | Close any elapsed dated pause at its announced return; set current pause start to the successful Save's local day and no return unless chosen. Preserve confirmation and override; release rows and arithmetic exclude only the resulting pause, keeping earlier eligible days |+| Change/remove a pending return | Keep the pause start; replace only the return. Do not rebase or move the confirmation merely for editing the date |+| Save a return of today | Same pause logic, with end today; effective status is ongoing immediately and the pending date disappears |+| Manually resume early | Close the current pause at today and set authored status ongoing. Keep the paused latest baseline and original confirmation bound so today's eligible release can count; do not use the existing generic current-day rebase for this transition |+| Set finished during hiatus | Rebase the current paused estimate under the existing explicit-status-change rules, close the pause at today and clear the pending date; finished status prevents further estimates |+| Edit an already elapsed return | Seed the editor with ongoing and no pending date. An explicit new hiatus starts today; unrelated saves retain the elapsed evidence |+| Change release weekdays | Rebase once under old weekdays and pause-aware arithmetic, then write new weekdays and preserve pause intervals. This explicit schedule edit keeps the existing current-day confirmation bound, including its exclusion of a release on the edit day |++A combined weekday/status/date edit performs only the schedule rebase. Evaluate old weekdays with the resulting pause boundaries through today, then stamp that baseline today and apply the new weekdays. Subsequent accrual starts after today under the existing confirmation-day rule; a status/date-only edit never creates that confirmation. Transitions from finished to ongoing/hiatus retain the existing explicit rebase before applying the new pause, preventing finished time from becoming estimated releases.++Same-day example: with yesterday's confirmation at 100 and a release due today, entering hiatus pauses the answer at 100. Returning today creates no excluded day, so the answer is 101. If a note or override establishes 105 today, the unchanged read-day bound instead yields 105, not 106. If 100 was explicitly confirmed today, its bound remains today and the answer stays 100. A same-day pause with a return of today is normalized to ongoing with no current or closed empty interval; a two-save pause/return retains the same arithmetic result.++Only a newly selected date is validated as today-or-future at save time. A previously stored date that elapsed while the editor was open remains valid with `.unchanged`; it must not be silently moved forward. If a newly chosen date becomes past before Save, retain the draft and ask the reader to choose today or later through the editor's existing validation error path.++## Status Projection and Today++Snapshots and group/content comparison retain authored data. Add `publicationState` plus `effectiveWorkStatus(on:)` to `WorkSnapshot`; rename its stored `workStatus` member to `authoredWorkStatus` so presentation call sites cannot accidentally retain the raw-status check. Use current day for Work Detail, Works groups/filters and WorkEntity; use selected day for Today rows and future projections. Do not put `Date.now` in a model accessor or authored fingerprint.++`TodaySchedule.admits` is a candidate test: reading works with weekdays qualify when authored ongoing, or when authored hiatus has a known start or a return date. A known-start undated hiatus must remain a candidate so past days can be shown. Unknown-start undated legacy hiatus retains its existing exclusion; catching-up retains first priority. Both `TodaySchedule.build` and `LibraryRepository.todaySchedule` use that exact predicate, including the carrier's decoded envelope. `ScheduledWork` carries the state. `TodaySchedule.isReleaseEligible` and `TodayDayPlan.build` resolve the selected day against all pause intervals and normal weekdays. Candidate membership alone must never answer “releases today.”++`WorkSummary`/`WorkEntity` resolve current-day status from the carrier with a captured clock/calendar. `ChaptersReleasingTodayIntent` continues through `IntentAnswers.releasingToday` and the same day plan, so it needs no main-app launch or preparation write. `markNoEpisode` validates eligibility for the supplied selected day through the same rule, including eligible days before a known hiatus start and projected releases after return; undo retains its existing rules.++Use `AppLifecycle`'s existing day/clock/time-zone/locale refresh through `AppLibraryModel.refreshAll`. Current-day resolution uses the published calendar/day consistently. A displayed Work Detail re-evaluates presentation when that day changes; do not replace an open editor's draft. Derived dates/status do not dirty the library, publish a save generation, or alter a conflict basis. A device moving back across a date boundary derives its status from its new local day, consistently with requirement 5.3.++## Work Detail UI++Inside the existing Status card, directly below the hiatus status selection, show `Return date` with `Set date…` when absent, or the formatted date plus `Remove date` when set. The date action opens a date-only picker bounded from today's start, following `StatsView.periodPicker`'s native picker, sheet toolbar and accessibility patterns. Reuse `constellationCaptionedField` and existing status typography; keep platform presentation differences in the existing platform support layer.++In view mode show `Returns {date}` only while effective status is hiatus with a pending date. Seed the draft from effective current status and pending date on editor entry; track publication-control changes independently from other metadata edits. Switching to ongoing/finished clears the draft date. Cancellation restores the stored projection. A saved or rolled-over return never reappears when the reader later chooses hiatus. Update `releaseDaysNote` to explain the dated pause and normal weekdays rather than claiming all hiatus works are absent from Today.++Date values are civil dates in the draft; convert to/from `Date` only for the native control under the publication calendar. VoiceOver announces `Hiatus return date` and the selected value; the control and removal action have stable identifiers. The same editor contract applies on iPhone, iPad and Mac (requirements 1.1–1.6).++## Integration and Pattern Audit++The audit covers production references to `workStatus`, `workStatusRaw`, `CatchUpProgress`, `TodaySchedule.admits/build` and `releaseCount`. Frozen schema copies remain frozen. Tests and fixture constructors must explicitly choose legacy or dated state.++| Call sites / files | Needs equivalent | Contract |+|---|---|---|+| `Models`, `Snapshots`, `LibraryRepository.snapshot`, `LibraryRepository+Groups` | Yes | Carry authored envelope; expose date-aware status without hidden clocks |+| `RepositoryDrafts`, `LibraryWrites`, `LibraryRepository.updateWork`, `WorkDetailModel` | Yes | Explicit publication intent, basis comparison, one atomic save and pause-aware rebase |+| `GroupOrdering.WorkContent`, `DuplicateReconciler`, `DuplicateResolution`, `LibraryRepository+DuplicateResolution` | Yes | Canonical envelope belongs to carrier content, pristine check, fingerprint, divergence and selected-variant copy |+| `WorkVariantUnion`, `WorkMergePlanner`, `ProjectionContract`, `LibraryRepository+WorkMerge` | Yes | Carry source/target state through preview/basis/commit; preserve selected authored state, report discarded differing publication state, do not union pauses from different selected variants |+| `LibraryRepository+Redirect`, `LibraryRepository+ConfirmImport` | Yes | Preserve/copy authored envelope wherever work content is copied; no derived-date writeback |+| `BackupArchiveProjection`, `ArchiveRecordBuilders`, backup Work types, codec, import projection/commit | Yes | Export/import complete authored state; never export effective ongoing as a replacement for pause evidence |+| `TodaySchedule.admits/build`, `LibraryRepository+TodayPresentation.todaySchedule`, `ScheduledWork`, `TodayDayPlan.build/row` | Yes | Include future-return candidates and resolve each selected day |+| Both `CatchUpProgress.build` overloads and `rebased`, `LibraryRepository+CatchUpProgress`, `WorkDetailView` progress | Yes | Selected-day publication state and shared pause-aware counts; Set latest keeps explicit confirmation-day semantics |+| `CatchUpRecord/Fold/Writer` | No | Existing independent confirmation and override election/encoding remains unchanged |+| `LibraryRepository+NoEpisode.markNoEpisode` | Yes | Selected-day eligibility matches Today; marks inside a pause are not double-subtracted |+| `WorksListOptions` filters/groups/counts and `releasesToday/isNewToday`, `WorksView` status display | Yes | Resolve current-day status; live dated hiatus is not a current release merely because it is a candidate |+| `WorkDetailModel/View`, `DuplicateResolutionView`, `TodaySections` | Yes | Current-day status in details/variant labels; selected-day status in Today rows; retain authored values in write bases |+| `LibraryRepository+Intents`, `WorkEntity`, `AddPageToReadFlow`, `IntentAnswers`, release shortcut | Yes | Capture current day for status; preserve authored state in commands and resolve release answers without app launch |+| `AppLibraryModel` refresh and fixture builders, `CoveredWorkFixture` | Yes | Refresh derived presentation and carry the new state through copy constructors |+| `WorksSearchToken`, `WorkStatusPresentation` | No | Static status labels/filter choices remain the same; consumers resolve status |+| No-episode note reconciliation, capture, new-work creation, deletion | No new action | Legacy nil state for new works; capture preserves Work state; deleting Work deletes its attribute; retain existing no-episode hooks |++## Persistence, Sync and Backup++Freeze all V18 models, including `NoEpisodeAction` and attribute/relationship options, and introduce nested V19 live models. Append a lightweight V18→V19 stage to the existing V16→V17→V18 chain; retain its older snapshots and marker acceptance because no device-population retirement has been approved. App accepts markers 16–19, upgrades/validates before publishing 19, and extensions open only marker 19. Update live-schema references, recorded-store fixtures and schema-delta contracts together.++Advance backup envelope 17/18 to 18/19 using the established single supported format/schema pair. The new Work record carries an optional structured publication state; missing state defaults to nil. This satisfies the supported-backup-without-dates case; an old 17/18 archive remains outside the new supported pair. Keep the payload's authored raw status consistent with its envelope. New exports retain expired pause evidence, and import validates all dates/state before writing. Add the state to import equality and authored-content recency handling, not the independent catch-up fold. Retain existing no-episode action import/export unchanged.++Same-identity duplicate collapse copies the selected carrier's complete authored envelope. Explicit cross-work merge follows the chosen Work variant; preview discloses discarded differing state. Never combine one variant's return date with another variant's status or pause list. Automatic passage of time emits no new conflict participant. Current builds agree for identical synced content and calendar context; supporting older clients is outside scope.++Preserve `catch-up-progress`'s existing limitation for concurrent schedule/progress edits: a confirmation rebased by an offline device that did not know about a hiatus can win its independent election and already contain an overestimate. Do not attempt to reverse a saved confirmation or introduce a cross-record merge rule. Status/date-only hiatus edits generate no confirmation of their own; the reader can correct the estimate through Set latest after such a concurrent edit.++## Error Handling++Invalid newly chosen dates use existing editor validation and retain all draft fields. Store or backup decoding errors for a non-nil envelope are explicit errors, not silent “no return date” fallbacks; archive validation must finish before mutation. Transaction failures use the repository's existing rollback/error path and leave both publication and catch-up state uncommitted. Date rollover requires no I/O and therefore introduces no return-time save failure.++## Testing Strategy++| Requirements | Focused verification |+|---|---|+| 1.1–1.7 | Model save/cancel/failure, today/future bounds, removal, status toggles, accessible date controls on compact/wide layouts; save-day start after editor midnight rollover; date edits preserve start |+| 2.1–2.4 | Resolver before/on/after return, late launch, live day change, future navigation read-only, no midnight fingerprint/save change |+| 3.1–3.6 | Before/on/after known start for dated and undated hiatus, return-day inclusion, closed/repeated pauses and gaps, unknown-start legacy behaviour; candidate/prefilter parity, cold shortcut and past/future no-episode eligibility |+| 4.1–4.7 | Return-day inclusion, known/unknown hiatus start, multiple pauses, manual early resume, same-day pause/return, weekday+status combined edit, count-up off, unknown latest, newer confirmation/read bounds, no-episode overlap and notes during hiatus |+| 5.1–5.4 | Recorded-store V16/V17/V18 upgrades, raw nil added field, markers/extension refusal, backup round trip and absent state, malformed payload rejection before writes, duplicate/merge carrier integrity, DST and time-zone identity |++Use Swift Testing with seeded generated cases, without adding a property-testing dependency: compare optimized counts with a bounded day-by-day oracle; assert invariance under interval coalescing, no double subtraction, read idempotence and encode/decode round trips. Include February/leap years and DST zones. Existing projection/repository tests prove no write occurs on automatic expiry; UI tests prove the open editor retains unrelated draft changes.++Add a regression that reads yesterday's scheduled release, saves a new hiatus today, and reads yesterday again: eligibility is unchanged, while today and paused future days are excluded. Run with and without a return date; then change/remove the date and manually resume. Earlier closed pauses stay excluded and gaps stay visible. Assert retained V19/18–19 state round trips and unchanged catch-up bounds; past browsing performs no write. Preserve legacy unknown-start tests rather than assigning history during migration.++Separately test a transaction that captures day D but completes on D+1: success retains D as the pause start, while failure leaves release eligibility unchanged. An editor opened on D and saved on D+1 instead starts the pause on D+1.++Use Makefile tooling: focused `make test-core CORE_TEST=…` and `make test-only TEST=…` while implementing, then full Core and simulator-unit gates. Use `make test-quick SKIP_MAC=1` plus a signed native Xcode MCP Mac build and embedded-extension check, following `docs/agent-notes/device-installation.md`. Run affected iPhone/iPad UI suites through the existing targets. A two-device Development check covers offline return, date edit sync and matching past-date eligibility after reconciliation; record results before merge.++## Risks and Assumptions++- Risk: a retained multi-generation SwiftData chain may expose frozen-model identity problems | Verify: recorded-store upgrades before wiring UI | If wrong: fix the frozen nesting/stage wiring and keep older accepted generations; do not bypass the readiness gate.+- Risk: real CloudKit delivery may reveal an overlooked writer that copies the legacy status without its envelope | Verify: two-device Development test plus authored-copy contract tests | If wrong: fix that copy path before merge; do not add automatic repair writes on reads.++## References++- Existing code: `TodayDayPlan.swift`, `CatchUpProgress.swift`, `LibraryRepository.updateWork`, `AppLifecycle`, and `StatsView.periodPicker`.+- Apple: [DatePicker](https://developer.apple.com/documentation/swiftui/datepicker) and [SchemaMigrationPlan](https://developer.apple.com/documentation/swiftdata/schemamigrationplan).+- Local migration procedure: `docs/agent-notes/schema-migration.md`; live version and retained stages are taken from `AsterismSchemaV19.swift`.++## Review Status++Explain-like self-validation, design-critic review and two independent local peer reviews completed on 2026-10-01 with no material blockers. External review tools were unavailable. Owner approved this revision and follow-up tasks 20–22 on 2026-10-01. All tasks are implemented and the resulting state passed design-critic review. `verification-run.md` records the initial and save-day correction gates; two-Development-device verification remains before merge.
specs/hiatus-end-date/prerequisites.md Modified
diff --git a/specs/hiatus-end-date/prerequisites.md b/specs/hiatus-end-date/prerequisites.mdnew file mode 100644index 00000000..1614d3cf--- /dev/null+++ b/specs/hiatus-end-date/prerequisites.md@@ -0,0 +1,32 @@+# Prerequisites for Hiatus End Date++Transit: T-2375++## Confirmed Behaviour++- [x] Preview expected releases and chapter estimates from the announced return date when browsing future dates in Today; keep the current work status on hiatus until the actual return date.+- [x] Preserve the existing paused estimate for works already on hiatus, without reconstructing an unknown hiatus start.+- [x] When the reader manually ends hiatus early, resume estimates from that day, excluding the elapsed hiatus under the existing counting rules.+- [x] A newly saved hiatus must preserve releases from before it was set. Owner requested this requirements/design revision on 2026-10-01 (Q17).++Initial choices were confirmed on 2026-09-29 (Q8–Q10); preservation of earlier releases was requested and approved on 2026-10-01 (Q17–Q18).++## Before Design++- [x] Owner reviews and approves the updated requirements document. Approved on 2026-09-29.++## Before Implementation++- [x] Owner reviews and approves the design. Approved on 2026-09-30.+- [x] Owner reviews and approves the task list. Approved on 2026-09-30.++### Save-day eligibility revision++- [x] Owner approves the revised requirements and design, including the date-based Save boundary. Approved on 2026-10-01.+- [x] Owner approves follow-up tasks 20–22. Approved on 2026-10-01; owner requested committing the plan and running make-it-so with a subagent.++## Before Merge++- [ ] Verify offline return, date-edit synchronization and matching results after reconciliation on two Development devices. This is the device check specified by the design; record its result during implementation.++The design retains the existing V16 and V17 migration stages when adding V19, so no device-population confirmation is required to retire an older stage.
specs/hiatus-end-date/requirements.md Modified
diff --git a/specs/hiatus-end-date/requirements.md b/specs/hiatus-end-date/requirements.mdnew file mode 100644index 00000000..44ac1b42--- /dev/null+++ b/specs/hiatus-end-date/requirements.md@@ -0,0 +1,98 @@+# Requirements: Hiatus End Date++Transit: T-2375++## Introduction++Authors sometimes announce when a work will return from hiatus. Recording that date lets the reader see expected releases again without remembering to change the work's status manually. Chapter estimates must resume without counting releases during the hiatus.++## Non-Goals++- Looking up return dates, verifying announcements, or sending return notifications.+- Changing recurring release weekdays or creating an extra release on the return date.+- Changing reading status automatically.+- A user-editable history of past hiatus periods.+- Release times within a day or reconstruction of historical reading and finished statuses.+- Supporting backup versions outside the build's supported version pair or guaranteeing interoperability with pre-feature builds.++## Definitions++- **Return date:** the first calendar day on which the work is ongoing again; the preceding day is the last hiatus day.+- **Current day:** the actual local calendar day used by Today, distinct from a date the reader selects to browse.+- **Hiatus start day:** the local calendar day captured when saving a new hiatus. It becomes the first paused day only after Save succeeds; opening the editor does not establish it.+- **Eligible release day:** a normal release weekday subject to the existing reading-status and no-episode rules.++## Relationship to Existing Specs++- Extends `work-and-reading-status` with a dated automatic transition from hiatus to ongoing.+- Extends `update-schedule` and `app-intents` so returned works regain their existing release eligibility.+- Extends `catch-up-progress` with estimates that resume after a dated hiatus, retaining `no-episode-today` exclusions.++## Requirements++### 1. Set and Edit a Return Date++**User Story:** As a reader, I want to record an announced return date, so that I do not have to remember to end the hiatus manually.++**Acceptance Criteria:**++1. <a name="1.1"></a>WHEN the draft work status is hiatus, Work Detail SHALL allow the reader to set, change, or remove an optional return date in its existing Status editor on iPhone, iPad, and Mac.  +2. <a name="1.2"></a>Saving SHALL commit the date with the other work edits; cancelling SHALL discard draft changes, and a failed save SHALL retain the draft and report the failure using the existing editor behaviour.  +3. <a name="1.3"></a>WHILE a work has a pending return date, Work Detail SHALL display that date alongside its hiatus status; the date control and displayed value SHALL have accessible labels identifying them as the hiatus return date.  +4. <a name="1.4"></a>WHERE no return date is set, the work SHALL remain on hiatus until the reader changes its status.  +5. <a name="1.5"></a>The date picker SHALL allow today and future dates using Today's local calendar day; saving today SHALL immediately end the hiatus.  +6. <a name="1.6"></a>WHEN the work becomes ongoing or finished, its pending return date SHALL be cleared; a later hiatus SHALL start without a return date.  +7. <a name="1.7"></a>WHEN a new hiatus is successfully saved, it SHALL take effect from its start day; unsaved, cancelled or failed edits SHALL NOT change release eligibility. Changing or removing its return date SHALL NOT move that start day.  ++### 2. End the Hiatus Automatically++**User Story:** As a reader, I want the work to become ongoing on its return date, so that its status reflects the announcement without another edit.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHEN the current day reaches or passes a hiatus work's return date, the work SHALL become ongoing without reader confirmation; its reading status and normal release weekdays SHALL remain unchanged.  +2. <a name="2.2"></a>IF the app was closed on the return date, opening it later SHALL show the work as ongoing and calculate resumed releases from the return date rather than the opening date.  +3. <a name="2.3"></a>WHEN the return date arrives while the app is open, the displayed status and Today results SHALL refresh through the existing day-change behaviour without requiring an app restart.  +4. <a name="2.4"></a>Browsing a future date in Today SHALL NOT itself end the hiatus before the current day reaches the return date.  ++### 3. Resume Scheduled Releases++**User Story:** As a reader, I want returned works to reappear on their normal release days, so that Today reflects their resumed schedules.++**Acceptance Criteria:**++1. <a name="3.1"></a>From the return date onward, a returned work SHALL qualify for Releasing Today under the existing release-weekday and reading-status rules; the return date alone SHALL NOT create a release.  +2. <a name="3.2"></a>The Chapters Releasing Today shortcut SHALL apply the same return-date eligibility without requiring the reader to open the main app first, retaining its existing no-episode exclusions.  +3. <a name="3.3"></a>A work without release weekdays SHALL become ongoing on its return date but SHALL NOT gain a scheduled release.  +4. <a name="3.4"></a>Before the actual return date, browsing future dates in Today SHALL show projected releases on eligible weekdays on or after the announced return date, without changing the work's current hiatus status.  +5. <a name="3.5"></a>WHERE a hiatus has a known start day, scheduled releases before that day SHALL retain their ordinary eligibility, subject to other recorded pauses and the existing weekday, reading-status and no-episode rules. Releases from the start day until the return day SHALL be excluded; without a return date, exclusion SHALL continue from the start day onward.  +6. <a name="3.6"></a>After return and across repeated hiatuses, hiatus-related release exclusions SHALL cover only dates within recorded hiatus periods. Return-date changes or removal SHALL preserve releases outside those periods.  ++### 4. Resume Chapter Estimates++**User Story:** As a reader, I want estimates to exclude the hiatus, so that a returning work does not appear to have released chapters while paused.++**Acceptance Criteria:**++1. <a name="4.1"></a>After an automatic return, chapter estimates and displayed estimated releases-since counts SHALL exclude the hiatus period and resume counting eligible releases on or after the return date.  +2. <a name="4.2"></a>A scheduled release on the return date SHALL be eligible to count once, subject to existing confirmation-day, read-day, count-up, and no-episode rules; a return date outside the schedule SHALL add no estimated chapter.  +3. <a name="4.3"></a>Ending a hiatus SHALL preserve recorded notes and last-read overrides, SHALL NOT invent a confirmed latest chapter where none exists, and SHALL preserve the existing distinction between confirmed and estimated counts.  +4. <a name="4.4"></a>Repeated app launches or access from multiple synced devices SHALL NOT count the same resumed release more than once.  +5. <a name="4.5"></a>For a work already on hiatus with no known start date, estimates SHALL retain the existing paused baseline and resume from the return date without reconstructing unavailable history.  +6. <a name="4.6"></a>WHEN the reader manually changes a hiatus work to ongoing before its announced return, estimates SHALL resume from the day of that change, excluding the elapsed hiatus and retaining the existing counting rules.  +7. <a name="4.7"></a>Before the actual return date, estimates shown for future dates SHALL include eligible releases from the announced return date through the date being shown, subject to the existing counting rules, without changing the work's current hiatus status.  ++### 5. Preserve Dates and Existing Libraries++**User Story:** As a reader, I want the return date to travel with my library, so that my devices and backups retain it.++**Acceptance Criteria:**++1. <a name="5.1"></a>Updating an existing library or importing a supported backup without return dates SHALL leave those works with no return date and their existing behaviour.  +2. <a name="5.2"></a>Synchronization and supported backup export and restore SHALL preserve pending return dates and the information needed to exclude hiatus releases from resumed estimates.  +3. <a name="5.3"></a>Devices with the same synced content, current day, and calendar context SHALL agree on the work's status, release eligibility, and estimates.  +4. <a name="5.4"></a>A return date SHALL retain its selected calendar date when the device's time zone changes; it SHALL NOT shift to an adjacent date.  ++## Review Status++The save-day start and preservation of earlier releases were reviewed by the design critic and two independent local peers on 2026-10-01 with no material blockers. Owner approved this revision on 2026-10-01.
specs/hiatus-end-date/tasks.md Modified
diff --git a/specs/hiatus-end-date/tasks.md b/specs/hiatus-end-date/tasks.mdnew file mode 100644index 00000000..500a1fbd--- /dev/null+++ b/specs/hiatus-end-date/tasks.md@@ -0,0 +1,211 @@+---+references:+    - requirements.md+    - design.md+    - decision_log.md+---+# Hiatus End Date — Implementation Tasks++## Core and persistence++- [x] 1. Red: Test V19 migration and readiness contracts <!-- id:shpgwo9 -->+  - Extend ModelContractTests and recorded-store/marker suites for the new optional Work.publicationStateData attribute, raw nil defaults, and unchanged existing fields including NoEpisodeAction and external thumbnail storage.+  - Cover V16, V17 and V18 stores upgrading to V19, app acceptance of markers 16–19, extension refusal before marker 19, and failed validation leaving readiness unchanged. Keep fixture containers sequential to avoid frozen-model registry collisions.+  - Use focused make test-core CORE_TEST=…; this red/green pair verifies the migration risk before later work depends on it.+  - Stream: 1+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2)+  - References: design.md, ../../Packages/AsterismCore/Tests/AsterismCoreTests++- [x] 2. Green: Add V19 models and retain the supported migration chain <!-- id:shpgwoa -->+  - Freeze every V18 model, then add nested V19 models/typealiases with publicationStateData: Data? = nil and append the lightweight V18→V19 stage. Preserve V16/V17 stages and frozen attribute/relationship shapes.+  - Update live-schema construction, bootstrap readiness constants/classification and test fixture references together. Enumerate remaining frozen-schema references; do not retire supported markers.+  - Advance the backup envelope constants to 18/19 and its live-schema pin here so the package stays consistent; full publication-state archive support is tasks 11–12. Pass task 1 tests before moving on.+  - Blocked-by: shpgwo9 (Red: Test V19 migration and readiness contracts)+  - Stream: 1+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/Models.swift, ../../Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV18.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift++- [x] 3. Red: Specify publication-state decoding and pause arithmetic <!-- id:shpgwob -->+  - Add WorkPublicationStateTests covering legacy nil state, unknown-start pauses, before/on/after return, indefinite hiatus, pending-date clearing, repeated pauses, invalid payloads and canonical encoding.+  - Use seeded Swift Testing cases to compare optimized counts with a bounded day-by-day oracle. Cover all weekday sets, leap dates, DST, interval coalescing, empty pauses and overlap with no-episode marks; dates must retain identity across zones.+  - Assert deterministic read-only resolution and encode/decode round trips. Native Date conversion must not alter the strict existing no-episode date spelling.+  - Blocked-by: shpgwoa (Green: Add V19 models and retain the supported migration chain)+  - Stream: 1+  - Requirements: [1.4](requirements.md#1.4), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [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.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [4.7](requirements.md#4.7), [5.4](requirements.md#5.4)+  - References: design.md, ../../Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift, ../../Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift++- [x] 4. Green: Implement publication state and shared civil-date counting <!-- id:shpgwoc -->+  - Implement WorkPublicationState.swift with versioned status/currentPause/closedPauses, canonical validation, explicit-day status and pendingReturn, and interval-aware release counting.+  - Extract the strict civil-date parser from NoEpisodeHistory.Action without changing accepted inputs. Use whole-week arithmetic plus interval intersections; subtract no-episode dates only outside pauses.+  - Wire the pure value into Work decoding with nil-only legacy fallback; malformed non-nil payloads are errors. Keep CatchUpConfirmation and its election format unchanged. Pass task 3 tests.+  - Blocked-by: shpgwob (Red: Specify publication-state decoding and pause arithmetic)+  - Stream: 1+  - Requirements: [1.4](requirements.md#1.4), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [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.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [4.7](requirements.md#4.7), [5.4](requirements.md#5.4)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/Models.swift, ../../Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift, ../../Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift++- [x] 5. Red: Test authored-state preservation through snapshots and merges <!-- id:shpgwod -->+  - Extend snapshot, WorkContent/fingerprint, duplicate reconciliation, merge preview/commit and redirect tests with differing, elapsed and unknown-start publication states.+  - Assert the selected carrier supplies one complete value; no cross-variant interval union or effective-status writeback. Include pristine detection, discarded-state preview and unchanged edit bases across midnight.+  - Test every authored-copy path in the design audit and preservation of the independently elected catch-up record. These contract tests precede repository/UI consumers and address the copy-path risk.+  - Blocked-by: shpgwoc (Green: Implement publication state and shared civil-date counting)+  - Stream: 1+  - Requirements: [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [4.4](requirements.md#4.4), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3)+  - References: design.md, ../../Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift, ../../Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift++- [x] 6. Green: Carry authored publication state through repository projections <!-- id:shpgwoe -->+  - Extend WorkSnapshot, both repository snapshot paths, WorkContent, bases and canonical fingerprints with the carrier envelope and an explicit-day effective-status resolver.+  - Update DuplicateReconciler/Resolution, WorkVariantUnion, WorkMergePlanner, ProjectionContract and repository duplicate/merge/redirect paths to preserve chosen state and disclose discarded differing state.+  - Keep the existing snapshot status spelling until the presentation migration in task 16; no newly wired consumer may use it as effective status. Update copy constructors/fixtures and pass task 5 tests.+  - Blocked-by: shpgwod (Red: Test authored-state preservation through snapshots and merges)+  - Stream: 1+  - Requirements: [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [4.4](requirements.md#4.4), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift, ../../Packages/AsterismCore/Sources/AsterismCore/WorkVariantUnion.swift++## Release behaviour++- [x] 7. Red: Test pause-aware progress and original confirmation bounds <!-- id:shpgwof -->+  - Extend both CatchUpProgress.build overload tests and rebase tests for known/unknown starts, multiple pauses, selected future days, count-up off, unknown latest and no-episode overlap.+  - Pin same-day examples: yesterday confirmed 100 plus today release becomes 101 after same-day pause/return; today note/override 105 stays 105; today confirmed 100 stays 100. Include future-dated notes and repeated reads.+  - Prove pre-pause accrual is retained while paused and no original confirmation/read boundary is rewritten merely to pause or resume.+  - Blocked-by: shpgwoe (Green: Carry authored publication state through repository projections)+  - Stream: 1+  - Requirements: [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [4.7](requirements.md#4.7), [5.3](requirements.md#5.3)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swift++- [x] 8. Green: Apply pause intervals to progress and releases-since counts <!-- id:shpgwog -->+  - Update both CatchUpProgress builders and rebased to consume publication state. Envelope ongoing/hiatus counts eligible days outside pauses; finished and legacy undated hiatus keep their zero-accrual rules.+  - Preserve the two existing confirmation/read branches, cap, estimate flags and count-up switch. Wire Set latest reads and TodayDayPlan.row releasesSince to the shared helper, keeping releasesSince existing count-up semantics.+  - Pass task 7 regressions without adding confirmation fields or read-time writes.+  - Blocked-by: shpgwof (Red: Test pause-aware progress and original confirmation bounds)+  - Stream: 1+  - Requirements: [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [4.7](requirements.md#4.7), [5.3](requirements.md#5.3)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift, ../../Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+CatchUpProgress.swift++- [x] 9. Red: Test atomic publication edits and transition boundaries <!-- id:shpgwoh -->+  - Extend repository work-edit tests for set/change/remove date, new/repeated hiatus, legacy manual resume, today return, finished transition and combined weekday/status edits.+  - Assert status/date-only edits preserve CatchUpRecord byte-for-byte, while schedule/finished edits rebase exactly once under the approved table. Cover unchanged edits across midnight, stale bases, newly selected dates expiring before save, and save failure rollback.+  - Keep publication edits atomic across duplicate rows and catch-up changes; cancellation is exercised at model level in task 15.+  - Blocked-by: shpgwog (Green: Apply pause intervals to progress and releases-since counts)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [4.1](requirements.md#4.1), [4.3](requirements.md#4.3), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [5.3](requirements.md#5.3)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift++- [x] 10. Green: Integrate explicit publication edits into the work writer <!-- id:shpgwoi -->+  - Add WorkPublicationWriter and required WorkPublicationEdit to WorkMetadataDraft, replacing its separate writable workStatus. Update every caller, fixture and forwarding test double to explicitly preserve or set state.+  - Implement the approved transition table inside updateWork existing exclusive transaction, using one captured clock/calendar. Write envelope and authored compatibility mirror together; retain catch-up values for status/date-only hiatus changes.+  - Validate only newly selected dates, preserve elapsed unchanged evidence, normalize empty pauses and retain closed periods. Wire existing WorkDetailModel save construction with unchanged intent until task 16 adds controls. Pass task 9 tests.+  - Blocked-by: shpgwoh (Red: Test atomic publication edits and transition boundaries)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [4.1](requirements.md#4.1), [4.3](requirements.md#4.3), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [5.3](requirements.md#5.3)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift, ../../Asterism/Asterism/ViewModels/WorkDetailModel.swift++- [x] 11. Red: Test publication-state backup round trips and import refusal <!-- id:shpgwoj -->+  - Extend archive/export/import tests for pending and elapsed returns, repeated and unknown-start pauses, missing optional state, raw-status consistency, and independently elected catch-up values.+  - Assert malformed state is rejected before mutation, older unsupported envelope refusal, repeated import stability and preservation through authored-content recency guards.+  - Cover golden export and model-envelope version pin without changing no-episode action history semantics.+  - Blocked-by: shpgwoi (Green: Integrate explicit publication edits into the work writer)+  - Stream: 1+  - Requirements: [1.4](requirements.md#1.4), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/BackupV17Types.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift++- [x] 12. Green: Complete the 18/19 archive codec and state import/export <!-- id:shpgwok -->+  - Complete the successor backup types/codec/exporter, optional structured publication state, ArchiveRecordBuilders, BackupArchiveProjection and import preview/commit paths.+  - Export authored values and all pause evidence; default missing state to legacy nil and validate before writes. Include state in authored equality/recency, not the catch-up election.+  - Record the golden through the existing test recording mechanism using Makefile targets; pass task 11 tests and the envelope schema pin.+  - Blocked-by: shpgwoj (Red: Test publication-state backup round trips and import refusal)+  - Stream: 1+  - Requirements: [1.4](requirements.md#1.4), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/BackupV17Codec.swift, ../../Packages/AsterismCore/Sources/AsterismCore/ArchiveRecordBuilders.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift++- [x] 13. Red: Test selected-day schedules, shortcuts and no-episode eligibility <!-- id:shpgwol -->+  - Test candidate/build/prefilter parity, every reading status, ordinary weekdays, no weekdays and selected dates before/on/after return; future browsing must not mutate stored status.+  - Extend cold intent and WorkSummary tests so return eligibility works without main-app launch. Verify future no-episode marking while currently on hiatus and no double subtraction.+  - Cover release rows, catching-up rows, shortcut omission and metadata containing authored hiatus after its effective return.+  - Blocked-by: shpgwok (Green: Complete the 18/19 archive codec and state import/export)+  - Stream: 1+  - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.4](requirements.md#2.4), [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.7](requirements.md#4.7)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift, ../../Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swift++- [x] 14. Green: Wire return-date candidates into Today and intent answers <!-- id:shpgwom -->+  - Change TodaySchedule.admits/build and the repository prefilter to the same future-return candidate predicate; carry state through ScheduledWork and filter actual rows by selected day plus weekday.+  - Resolve current-day status in repository intent summaries/WorkEntity and selected-day releases in IntentAnswers; update AddPageToReadFlow to preserve authored state.+  - Use the same selected-day eligibility in markNoEpisode, leaving undo and note reconciliation unchanged. Pass task 13 tests.+  - Blocked-by: shpgwol (Red: Test selected-day schedules, shortcuts and no-episode eligibility)+  - Stream: 1+  - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.4](requirements.md#2.4), [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.7](requirements.md#4.7)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift, ../../Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+NoEpisode.swift++## Interface and verification++- [x] 15. Red: Test editor drafts, current-day presentation and rollover <!-- id:shpgwon -->+  - Extend WorkDetailModel tests for draft creation, cancel, failed save, removal, today return, renewed hiatus and publication controls changing independently of title/notes.+  - Cover active-editor midnight rollover without lost input or synthetic conflict; persisted elapsed dates may remain unchanged, newly picked past dates must fail visibly.+  - Add Works groups/filter/count and AppLibraryModel refresh tests ensuring today status changes after return, while future candidates do not leak into current releases. Cover time-zone/calendar changes with an injected clock.+  - Blocked-by: shpgwom (Green: Wire return-date candidates into Today and intent 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), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.4](requirements.md#5.4)+  - References: ../../Asterism/Asterism/ViewModels/WorkDetailModel.swift, ../../Asterism/Asterism/ViewModels/WorksListOptions.swift, ../../Asterism/Asterism/ViewModels/AppLibraryModel.swift++- [x] 16. Green: Implement editor state and migrate status presentation consumers <!-- id:shpgwoo -->+  - Implement civil-date draft state, dirty tracking and publication intent in WorkDetailModel; seed effective status and pending return on edit entry, and preserve drafts through refresh.+  - Rename snapshot workStatus to authoredWorkStatus and audit all callers. UI/filter/group consumers use explicit current day, Today uses selected day, and copy/basis/merge code retains authored state. Update WorksView, DuplicateResolutionView, TodaySections and fixtures.+  - Use AppLifecycle existing refresh path with a consistent published day/calendar; do not synthesize saves on rollover. Update releaseDaysNote and pass task 15 tests, including Mac compilation.+  - Blocked-by: shpgwon (Red: Test editor drafts, current-day presentation and rollover)+  - 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), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [5.4](requirements.md#5.4)+  - References: ../../Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift, ../../Asterism/Asterism/ViewModels/WorkDetailModel.swift, ../../Asterism/Asterism/ViewModels/WorksListOptions.swift, ../../Asterism/Asterism/ViewModels/AppLibraryModel.swift++- [x] 17. Red: Add automated return-date editor journeys <!-- id:shpgwop -->+  - Add deterministic UI fixtures and WorkDetail status UI tests for selecting/changing/removing dates, cancel/save, today return and choosing another hiatus without reusing the old date.+  - Cover compact iPhone and wide iPad layouts, VoiceOver labels/identifiers and accessibility text size. Reuse existing platform test helpers; keep Mac behavior covered by model/platform tests and build.+  - Test that return-date controls live inside the Status editor and view mode displays Returns {date} only while pending.+  - Blocked-by: shpgwoo (Green: Implement editor state and migrate status presentation consumers)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.3](requirements.md#2.3), [3.1](requirements.md#3.1)+  - References: ../../Asterism/Asterism/Views/WorkDetailView.swift, ../../Asterism/Asterism/ViewModels/AppLibraryModel.swift, ../../Asterism/AsterismUITests++- [x] 18. Green: Build the native return-date controls and wire the journeys <!-- id:shpgwoq -->+  - Add Set date, date value, Remove date and pending Returns text to the existing Status card, using the approved field pattern and StatsView date-only picker/sheet conventions.+  - Convert civil dates only at the native DatePicker binding boundary, bound selection from today, and place platform differences in the existing support layer. Provide stable accessibility labels and identifiers.+  - Wire controls to task 16 draft state; pass task 17 focused UI journeys and retain Mac compilation.+  - Blocked-by: shpgwop (Red: Add automated return-date editor journeys)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.3](requirements.md#2.3), [3.1](requirements.md#3.1)+  - References: ../../Asterism/Asterism/Views/WorkDetailView.swift, ../../Asterism/Asterism/Views/StatsView.swift, ../../Asterism/Asterism/Support/PlatformModifiers.swift++- [x] 19. Verify integrated regressions and required build gates <!-- id:shpgwor -->+  - Run make test-core and make test-quick including its Mac build, then affected iPhone/iPad UI suites through Makefile targets. Use run_silent where available, keep full logs on disk and assign one owner per run.+  - Confirm the design integration audit has no raw-status presentation leftovers, all authored copy/import paths preserve state, migration/marker tests pass and all property/regression tests are included.+  - Run focused tests after feature fixes; do not repeat unaffected suites or the long performance suite without evidence. Report inherited failures separately. The two-device Development check remains a before-merge prerequisite, not an automated task.+  - Blocked-by: shpgwoq (Green: Build the native return-date controls and wire the journeys)+  - 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), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [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), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [4.7](requirements.md#4.7), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+  - References: design.md, prerequisites.md, ../../Makefile++## Save-day eligibility correction++- [x] 20. Red: Specify save-day and historical release eligibility <!-- id:shpgwos -->+  - Extend publication-state/schedule tests for before/on/after known starts, dated and undated hiatus, closed/repeated pauses and visible gaps. Preserve unknown-start legacy and finished policies; compare selected-day eligibility with a seeded interval/weekday oracle.+  - Add repository regressions: read yesterday, save hiatus today and read yesterday again; date changes/removal and early return preserve earlier eligibility. Cover candidate/prefilter parity, cold shortcuts, past-date no-episode marks and read-only browsing.+  - Test Save capturing D and completing on D+1 (success uses D; failure changes nothing), and an editor opened on D but saved on D+1. Assert preserved catch-up bounds and archive round trips. Run focused Makefile tests and verify historical eligibility is red.+  - Stream: 1+  - Requirements: [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [1.7](requirements.md#1.7), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.5](requirements.md#4.5), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+  - References: requirements.md, design.md, decision_log.md, ../../Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift, ../../Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift, ../../Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swift, ../../Packages/AsterismCore/Tests/AsterismCoreTests, ../../Asterism/AsterismUITests/TodayUITests.swift, ../../Asterism/AsterismUITests/PublicationReturnDateUITests.swift++- [x] 21. Green: Resolve release eligibility within saved hiatus intervals <!-- id:shpgwot -->+  - Update WorkPublicationState.status(on:) to resolve ongoing/hiatus from current and closed intervals; retain authored finished and nil/unknown-start legacy behavior.+  - Update TodaySchedule.admits to retain known-start undated hiatus candidates; ensure TodayDayPlan, repository prefilter, intents, no-episode validation and Works presentation share the approved selected/current-day rules.+  - Retain the writer single captured Save clock/calendar and start-preserving date edits; modify writer code only where task 20 exposes a gap. Reuse V19/envelope v1 and archive 18/19 without new history or election fields. Pass task 20 tests.+  - Blocked-by: shpgwos (Red: Specify save-day and historical release eligibility)+  - Stream: 1+  - Requirements: [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [1.7](requirements.md#1.7), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.5](requirements.md#4.5), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)+  - References: requirements.md, design.md, decision_log.md, ../../Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift, ../../Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift, ../../Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swift, ../../Packages/AsterismCore/Tests/AsterismCoreTests, ../../Asterism/AsterismUITests/TodayUITests.swift, ../../Asterism/AsterismUITests/PublicationReturnDateUITests.swift++- [x] 22. Verify historical releases across Today and required build gates <!-- id:shpgwou -->+  - Add an automated Today/editor journey: browse yesterday, save hiatus today, confirm yesterday remains while paused days disappear. Cover dated and undated variants with existing phone/iPad drivers and model tests.+  - Run full make test-core, simulator make test-quick SKIP_MAC=1, signed native Mac build via Xcode MCP and embedded-extension check, and affected focused phone/iPad journeys. Reuse valid evidence and rerun only affected failures after fixes.+  - Use run_silent, disk logs and one test owner. Audit eligibility parity, captured boundaries, stable fingerprints and read-only browsing. Report inherited failures separately; no performance or Personal run. Two-Development-device check remains before merge.+  - Blocked-by: shpgwot (Green: Resolve release eligibility within saved hiatus intervals)+  - Stream: 1+  - Requirements: [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [1.7](requirements.md#1.7), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.5](requirements.md#4.5), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [2.3](requirements.md#2.3), [5.1](requirements.md#5.1)+  - References: requirements.md, design.md, decision_log.md, ../../Packages/AsterismCore/Sources/AsterismCore/WorkPublicationState.swift, ../../Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift, ../../Packages/AsterismCore/Sources/AsterismCore/WorkPublicationWriter.swift, ../../Packages/AsterismCore/Tests/AsterismCoreTests, ../../Asterism/AsterismUITests/TodayUITests.swift, ../../Asterism/AsterismUITests/PublicationReturnDateUITests.swift
specs/hiatus-end-date/verification-run.md Modified
diff --git a/specs/hiatus-end-date/verification-run.md b/specs/hiatus-end-date/verification-run.mdnew file mode 100644index 00000000..c75ac56a--- /dev/null+++ b/specs/hiatus-end-date/verification-run.md@@ -0,0 +1,95 @@+# Hiatus End Date — Verification++Date: 2026-10-01. Branch: `T-2375/hiatus-end-date`.++## Automated gates++| Gate | Result | Evidence |+| --- | --- | --- |+| Full `make test-core` | 3,116 Core tests in 291 suites passed; the other package run passed 229 tests in 13 suites with two known issues | `/tmp/hiatus-final-core.log` |+| `make test-quick SKIP_MAC=1` | 1,973 simulator unit tests in 138 suites passed | `/tmp/hiatus-final-simulator.log` |+| Signed native Mac build | Xcode MCP, Asterism Development / My Mac, `buildForTesting: false`: passed in 12.455 seconds, no errors; embedded Mac extension verified | `BuildProject-Log-20261001-000325.txt` in Xcode ActionArtifacts |+| Existing status/list UI regressions | WorkDetailStatusUITests: 9 passed; WorksListOptionsUITests: 5 passed | `/tmp/hiatus-final-status-ui.log` |+| Return-date phone journeys | All 3 passed, including largest accessibility text size | `/tmp/hiatus-return-ui-phone.log` |+| Return-date iPad journeys | All 3 verified across the wide roundtrip and focused today-return/accessibility runs | `/tmp/hiatus-return-ui-ipad.log`, `/tmp/hiatus-return-ui-ipad-today.log`, `/tmp/hiatus-return-ui-ipad-ax.log` |+| Identity and whitespace validators | `make verify-identity` and `git diff --check` passed | Phase verification commands |++The iPad full run contained navigation-driver failures before the corresponding+controls could be exercised. Tests were corrected to follow existing wide-layout+column tap/scroll and collapsed-sidebar patterns. The roundtrip passed in the+full run; the remaining two journeys passed isolated reruns. Production controls+were unchanged by those corrections. Passed phone cases were not repeated.++The Mac gate uses Xcode MCP under the owner's instruction. It replaces the CLI+Mac dependency skipped by the simulator command and retains the embedded-extension+check. No Mac app was launched. The long performance suite was not run.++## Integration checks++- `WorkSnapshot` exposes `authoredWorkStatus`; presentation resolves a supplied+  day. Groups, filters, row/variant labels and the editor receive the published+  day/calendar; Today rows resolve their selected day.+- Editor baseline and authored fingerprints remain stable across return and+  refresh. Active drafts survive reload; only explicit publication edits stage+  authored state. Return expiry performs no write.+- Snapshot, duplicate, merge and archive paths preserve one complete carrier+  envelope. Catch-up confirmation/override election remains independent.+- Full Core coverage includes retained V16/V17/V18 migration support, marker 19+  readiness, nil legacy values, malformed-envelope refusal, pause arithmetic,+  writer transitions, archive round trips and cold intent/no-episode eligibility.++## Before merge++The two-Development-device check in `prerequisites.md` remains pending: verify+offline return, date-edit synchronization and matching results after reconciliation.+It is a manual before-merge prerequisite, not a missing automated implementation+step. No Personal device run or merge was performed.++## Phase 4: Save-day eligibility correction++The approved October 1 revision is now verified. `status(on:)` resolves known+current and closed pause intervals, preserving earlier releases and gaps.+Known-start undated hiatus remains a schedule candidate. Finished and unknown-start+legacy policies are unchanged; the writer, V19 envelope v1 and archive 18/19+remain unchanged.++| Gate | Result | Evidence |+| --- | --- | --- |+| Red historical regressions | Failed before production edits on before-start status, closed intervals, undated candidates and yesterday → Save today → yesterday eligibility | `/tmp/hiatus-phase4-red.log` |+| Focused publication Core tests | Passed, including seeded weekday/interval oracle, repository/prefilter/cold-intent parity, no-episode marks, catch-up preservation, archive tests and midnight Save success/failure | `/tmp/hiatus-phase4-green.log` |+| Full `make test-core` | Passed, exit 0; formatter omitted aggregate totals | `/tmp/hiatus-phase4-core.log` |+| Full simulator units | 1,973 tests in 138 suites passed, 31.975 seconds | `/tmp/hiatus-phase4-simulator-final.log` |+| Focused Today fixture units | 2 tests passed | `/tmp/hiatus-phase4-fixture-units.log` |+| History phone journeys | Dated and undated: 2 tests passed, 100.291 seconds | `/tmp/hiatus-phase4-phone-final.log` |+| History iPad journeys | Undated passed, 49.803 seconds; dated passed, 71.168 seconds | `/tmp/hiatus-phase4-ipad-fixture-one.log`, `/tmp/hiatus-phase4-ipad-fixture-dated.log` |+| Existing Today past-day journey | Passed with both pre-hiatus releases retained | `/tmp/hiatus-phase4-today-past.log` |+| Signed native Mac build | Xcode MCP Development / My Mac, `buildForTesting: false`: passed, 31.3 seconds, no errors; embedded Mac extension verified | `BuildProject-Log-20261001-114645.txt` in Xcode ActionArtifacts |+| Validators | `make verify-identity` and `git diff --check` passed | Phase final validation commands |++The first dated-phone command hit `run_silent`'s default five-minute timeout;+its retry stalled in Xcode test finalization. Neither is passing evidence.+Using the documented `-collect-test-diagnostics never` Makefile flag with raw+disk logs produced verified results. Subsequent commands used explicit timeouts.++Initial iPad failures occurred while locating the unrelated weekday setup row.+The final isolated `seeded-hiatus-history` fixture starts with one ongoing daily+work; each journey still browses yesterday, saves a new hiatus through the real+editor, verifies yesterday remains, and verifies the Save day disappears. The+existing return-date fixture and its previous verified journeys are retained.++The first full simulator gate found one feature-related stale assertion: a+newly saved hiatus was excluded from the entire candidate schedule. The fixture+test now includes its historical candidate and separately verifies past/current+eligibility. Its focused suite and the full gate passed after correction. The+existing past-day UI assertion was updated and verified for the same behavior.++Save captures day D once even when persistence completes on D+1; injected failure+changes neither publication eligibility nor catch-up bounds. An edit basis opened+on D and saved on D+1 starts the new hiatus on D+1. Read-only browsing preserves+authored edit bases. A clock moving back inside retained closed pause evidence+retains the existing authoring refusal; no interval truncation or new history+policy was introduced.++Unchanged initial migration, archive, status-control and accessibility evidence+above remains valid. The two-Development-device before-merge check is still+pending. No performance suite, Personal device run, Mac launch or merge occurred.
specs/hiatus-end-date/implementation.md Added
diff --git a/specs/hiatus-end-date/implementation.md b/specs/hiatus-end-date/implementation.mdnew file mode 100644index 00000000..bb1569db--- /dev/null+++ b/specs/hiatus-end-date/implementation.md@@ -0,0 +1,46 @@+# Hiatus End Date — Implementation++## Beginner Level++### What Changed+A work on hiatus can have an announced return date. The Status editor saves, changes or removes it with the other work edits. Cancel and failed Save retain the existing behavior.++### Why It Matters+Today can show expected releases after the return, and chapter estimates omit paused days. Saving a new hiatus today preserves yesterday's releases. Return follows the normal weekdays and never creates an extra release.++### Key Concepts+The authored status records the reader's choice. Effective status answers whether the work is ongoing on a particular calendar day. Pause intervals retain the days excluded from estimates, even after the visible return date disappears.++---++## Intermediate Level++### Changes Overview+`WorkPublicationState` stores authored status, closed pauses and an optional current pause. V19 adds one optional Work attribute; archive 18/19 preserves the complete value. Existing V16–V18 upgrades remain supported.++### Implementation Approach+`WorkPublicationWriter` stages explicit publication edits inside `LibraryRepository.updateWork`'s existing transaction with one captured clock/calendar. `WorkMetadataDraft.publicationEdit` distinguishes unchanged metadata saves from publication edits. Current and selected days flow explicitly to status, Today, shortcuts and catch-up calculations. Work Detail retains an editor basis and drafts across refresh.++### Trade-offs+Read-only expiry works without background execution or main-app launch. The whole envelope follows the selected authored carrier through copies and merges. Completed pauses consume growing per-work history but preserve estimates across repeated hiatuses; the reader does not edit that history.++---++## Expert Level++### Technical Deep Dive+Pauses use half-open civil-day intervals [start, return); a successfully saved new hiatus captures its start once. Canonical Gregorian date strings preserve calendar identity across zones. Whole-week release counting subtracts disjoint pause intersections, then no-episode marks outside pauses; membership uses binary search over closed intervals. Same-day pause/return contributes no excluded interval. Unknown-start legacy pauses preserve their paused baseline.++### Architecture Impact+Authored fingerprints remain stable across midnight. Snapshot presentation resolves effective status while persistence, duplicate selection, merge and backup retain the authored envelope. Status/date-only edits preserve independently elected catch-up confirmation and override bytes. Schedule and finished-status changes retain explicit rebasing rules.++### Potential Issues+Concurrent offline schedule rebases retain the existing independent-confirmation limitation (Q13). Backward-clock authoring inside retained closed pause evidence retains its documented refusal. The two-Development-device offline-return/date-sync check remains a before-merge prerequisite; automated and phone-only evidence cannot establish it.++## Completeness Assessment++All 22 implementation tasks are complete. Automated coverage includes publication decoding, interval arithmetic, Save-day/midnight boundaries, snapshots/copies/merges, archives/migrations, Today/shortcuts, editor drafts and current-day presentation. Existing verification records passing simulator units, focused phone/iPad journeys and the signed native Mac build.++The pre-push Core Make run passed with 3,393 JUnit cases: 3,338 non-skipped, 55 skipped and no failures/errors. LCOV was exported from the actual Xcode-backed test bundle. The ecosystem detector expects a root Package.swift; this repository's package is nested, so verification used the project's supported Makefile flags rather than claiming literal automatic detection.++Manual two-Development-device reconciliation verification remains pending in prerequisites.md. No missing automated implementation or unexplained design divergence was identified. No device run, Mac launch or performance suite was performed during review.

Things to double-check

Before-merge device gate

prerequisites.md requires two Development devices to verify offline return, date edit synchronization and reconciled agreement. Remains pending.

Review limits

Substantive production hunks received four review lenses. Mechanical archive renames and minified golden fixtures were not inspected exhaustively. No profiling was performed.

Structured runner selection

Root-only ecosystem detection does not match the nested package. Used make test-core with supported SWIFT_TEST_FLAGS for xUnit and coverage; actual Xcode-backed binary required a different export path. Prior simulator/UI/signed-Mac evidence is retained because no production fixes were applied.