URL-optional works, manual notes and chapter identity across shared pages.
Needs fixes before final acceptance
Fresh full Core and signed Mac/native gates pass, and full iPad passes all 30 expected declarations. Original full phone executed all 210 expected declarations: 203 passed, five failed, two skipped. The two actionable backup failures were fixed with genuine red/green tests; all five failed identifiers passed one focused confirmation. Three AX setup failures did not reproduce, but the original full gate remains failed. Incoming share-extension, saved-combine conflict and Mac form rendering remain unverified; tasks 11/13 stay open. This is an authorised draft PR, not merge approval.
577d14db T-2416: record final verification and remaining rendering gaps 5a2788a2 T-2416: changelog for implementation phase 3bac16c5 T-2416: cover rating-only notes in wide work detail 00728454 T-2416: preserve actionable backup refusals 0fa4a073 T-2416: Record verified Core and native implementation 7973a56b T-2416: verify chapter capture identity and draft safeguards d72087e1 T-2416: document checkpoint validation and ordinary capture flow 1adc835a T-2416: WIP checkpoint URL-optional chapter notes bee4b903 T-2416: record spec approval and start implementation 198b65ab docs: complete T-2416 peer review and preserve late combined-entry edits f4811047 docs: specify T-2416 URL-optional chapter notes ### What changed A work can be saved without a website. Its optional URL can point to a source or a purchase page. Inside the work, Add note accepts a note, a rating, or both. A title and source link are optional. Two untitled notes remain two independent entries. The share sheet distinguishes the chapter being discussed from the page where it was found. A page can contain many chapters, and one chapter can appear on several pages. Existing taught URL/title rules supply chapter evidence first. When that evidence is insufficient or contradictory, the reader chooses an existing chapter or confirms a new one. Clearly detected chapters keep the ordinary create/update flow and offer a correction path. ### Why it matters Notes about a paper book work alongside notes captured from a website. Switching a serial between individual chapter pages and a whole-work page preserves chapter identity and existing notes. Choosing an existing chapter preserves its saved content unless the reader deliberately chooses conflicting draft content. ### Key concepts An entry is the saved note/rating target. A source is a link associated with that entry. A work's page-layout setting changes the initial suggestion; it remains editable and never restricts capture. Combining two entries keeps their source links and records where the old entry now points.
### Changes overview Core adds authored Note/Chapter metadata, a per-work capture default, and relationship-free `EntrySource` records. `ChapterCaptureResolver` projects work-scoped evidence and immutable save intent. Manual capture and correction use repository operations behind one Save boundary. App and share-extension forms bind value drafts, with cancellation and refused saves preserving input. ### Implementation approach Explicit authored targets use entry UUID identity rather than URL identity. Legacy records keep their existing evidence and matching rules. Source associations preserve verbatim URLs, taught-rule provenance, and superseded evidence. Exact chapter labels are compared within a work and compatible rule scope; titles or site-wide ordering do not invent equivalence. Save re-derives the projection under repository exclusion and rejects stale identity, authored content, rule, or default assumptions. Pending captures use the same conservative resolver, setting ambiguous captures aside for interactive review rather than guessing. Source-only replay cannot overwrite notes or ratings. The additive V20 schema freezes V19 and preserves the reachable migration chain. The new backup format carries authored fields, sources, redirects and resolution baselines; bounded predecessor conversion preserves old archives. Markdown uses optional links and the same authored presentation as the app. Generic notes are excluded from chapter-progress calculations. ### Trade-offs No new work type, reader, content importer, site-wide layout policy or confidence API is introduced. Some chapter matches need deliberate selection. Keeping explicit identity and old capture evidence separate adds small records and conservative refusal paths, but preserves data across mixed layouts and reordered sync arrivals.
### Technical deep dive Relationship-free UUID references keep the additive model compatible with CloudKit mirroring. Source convergence is content-based, preserves orphans, and routes late associations through durable entry redirects. Cycles, missing targets, torn ownership and contradictory authored copies remain unresolved rather than being repaired by elapsed time or destructive guessing. Combining entries stores an accepted loser-content baseline. The loser is hidden only while current authored content matches that baseline. Late offline note/rating changes become visible as Changes after combine, preserve both contents, and block automatic targeting and backup export until reviewed. Markdown can still represent the addressed reviewable content. Non-content routing retains late source links and excludes superseded chapter evidence. Failure paths roll back and re-fault affected models rather than assuming in-memory values were restored. ### Architecture impact Authored identity participates in duplicate handling, moves, work combination/deletion, exports/imports, extraction, Today presentation and share context. Raw capture evidence remains immutable. Work-level defaults are learned only on a successful deliberate second-chapter save on the same page; generic notes, corrections and cancellation do not teach that default. ### Potential issues Simulator and host tests exercise storage contracts and reordered arrival fixtures, not live CloudKit delivery. Hardware sync verification remains a separate device-run activity. As specified in the approved rollout plan, preserve an archive and upgrade all writing app/extension installations together before actual rollout; older writers cannot enforce authored chapter identity. Published books joining an existing series remain deferred to T-2417. Full gate failures and any unexecuted checks must stay visible in the final verification record.
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ChapterCapture.swift
Why it matters. Preserves ordinary capture and deliberately distinct chapters on shared pages.
What to look at. applyChapterCapture
Packages/AsterismCore/Sources/AsterismCore/EntrySources.swift
Why it matters. Delayed offline changes cannot disappear behind a combined entry.
What to look at. EntrySourceIndex and combine
Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20.swift
Why it matters. Preserves populated stores and reachable predecessor migrations.
What to look at. AsterismSchemaV20; BackupV19Codec
Asterism/Asterism/ViewModels/ManualEntryFormModel.swift
Why it matters. Supports untitled/rating-only notes and retains drafts through refusals.
What to look at. ManualEntryFormModel
Packages/AsterismCore/Sources/AsterismCore/BackupV19Exporter.swift
Why it matters. Settings keeps the blocker count and Check Library route rather than a generic retry.
What to look at. backupV19Snapshot
Decision 1 preserves distinct chapters sharing a page and multiple links for one chapter. Generic untitled notes remain independent UUID targets.
Decision 2 uses exact work/rule-scoped evidence and explicit selection for ambiguity. Corrections supersede rejected evidence and retain durable redirects with accepted-content baselines.
Decision 3 freezes V19, retains V16–V19 migration stages and adds V20 without backfill. Current format 19/schema 20 archives support bounded conversion of format 18/schema 19.
Decision 4 stages learning with a deliberate newChapter save and explains it before Save. Automatic detected chapters, corrections, generic notes and cancellation do not teach the default.
Decision 5 resolves overlapping design wording in favor of Requirement 3.1: clear comparable evidence keeps the ordinary create/update flow, derived writes and legacy identity; ambiguous cases require review.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Detected chapter drafts | Retain detected labels on confirmation and keep correction reachable in every evidence state. | Preserve agreeing detected fields, leave conflicting designation blank, and keep correction reachable. Source rechecks passed; incoming extension rendering remains unverified. |
| major | Manual selection | Preserve edited drafts and saved content when selecting an existing chapter. | Preserve edited drafts and require content review; focused native suite includes all seven manual form declarations and passes. |
| major | Legacy promotion | Retain taught bindings before switching legacy targets to UUID identity. | Preserve v2/v3 and cited title-only evidence before UUID promotion. Genuine title-only regressions and fresh full Core pass; source recheck confirms namespace parity. |
| major | Standalone export | Follow clean retained redirects and use authored note labels. | Follow clean redirects, retain addressed unresolved content and use authored note labels. Full Core and source recheck pass. |
| major | Correction history | Record no-episode note transitions within the correction transaction. | Record no-episode note transitions within the correction transaction and re-fault on rollback. Full Core passes; correction form focused coverage passes. |
| suggestion | Capture efficiency | Reuse reviewed projections for authored-only edits; batch source associations; skip singleton convergence. | Reuse immutable projections for authored-only edits; batch associations with transaction-local indexing; skip singleton convergence. Source inspection and full Core pass; no runtime benchmark claimed. |
| suggestion | Optional reuse cleanups | HTTP link validation and chapter-content selection contain small repeated predicates. | Deferred the two P3 consolidations to keep this compatibility change focused; existing behavior and validation remain explicit. Frozen schema/archive copies are intentional compatibility boundaries. |
| major | Late source arrival | Ordinary-new fallback can miss an EntrySource arrival without a changed Work/rule basis. | Compare a fresh chapter projection before ordinary-new fallback. Genuine arrival-race regression passes and source recheck confirms draft-preserving review. |
| major | Title-only legacy promotion | Promotion preserves v2/v3 bindings but drops cited chapter-title designation evidence on raw-URL identity. | Centralize cited nonblank chapter-title designation in legacyBindings using its existing rule namespace. Both manual and combine cases reproduced red and pass with the fix. |
| suggestion | Default-learning disclosure | Automatic same-page detected chapter creation can learn the work default without showing its explanation. | Only deliberate newChapter saves learn the default; automatic detected chapters and corrections leave it unchanged. Focused/full Core and source recheck confirm disclosure parity. |
| major | BackupV19Exporter typed error transport | A typed actionable export refusal thrown inside the repository lock was wrapped as libraryUnavailable, causing Settings to show generic retry instead of blocker count and Check Library. | Reuse predecessor Result<BackupV19Payload, BackupV18ExportError> transport: catch only typed refusals inside the lock and .get() outside. Two real snapshot/export variants reproduced red and passed green, preserving notes and staging no archive. Fresh full Core/native gates and both affected phone assertions pass. |
Source: local run at 2026-10-10T19:09:46.034466+00:00 · snapshot 0fa4a073461bf13016e6a8f047fe3665c3c8ceb9 (dirty working tree)
Baseline: none
Execution: passed · JUnit: 1 file · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 3773 passed · 0 failed · 55 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 6997feed.
150 files: 140 code · 10 docs. Click to expand.
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex c38abcde..02ee88f7 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -340,8 +340,8 @@ public final class AppLibraryModel { /// Only unfinished editors, including destinations beneath a pushed work. /// Read-only models remain view-owned; cancel and Save release each session. @ObservationIgnored private var activeWorkEditors: [WorkEditorRoute: WorkDetailModel] = [:]- /// Retains the concrete repository for backup export (conforms to BackupV18SnapshotProviding).- private var backupRepository: (any BackupV18SnapshotProviding)?+ /// Retains the concrete repository for backup export (conforms to BackupV19SnapshotProviding).+ private var backupRepository: (any BackupV19SnapshotProviding)? /// 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.@@ -2935,11 +2935,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() -> BackupV18Exporter? {+ private func backupExporter() -> BackupV19Exporter? { guard let repo = backupRepository, let config = resolvedConfiguration else { return nil } let stagingDir = config.rootDirectory .appending(path: "Library/Caches/BackupExports")- return BackupV18Exporter(repository: repo, stagingDirectory: stagingDir)+ return BackupV19Exporter(repository: repo, stagingDirectory: stagingDir) } /// The per-entry markdown export model (Req 1.5), staged beside the backup
diff --git a/Asterism/Asterism/ViewModels/ConflictRecentPresentation.swift b/Asterism/Asterism/ViewModels/ConflictRecentPresentation.swiftindex 112f9c0f..11bce3e9 100644--- a/Asterism/Asterism/ViewModels/ConflictRecentPresentation.swift+++ b/Asterism/Asterism/ViewModels/ConflictRecentPresentation.swift@@ -84,6 +84,7 @@ public enum EntryDetailRulePresentation { public static func identityBasisLabel(for basis: EntryIdentityBasis) -> String { switch basis {+ case .authoredUUID: "Reader-selected entry" case .conservative: "Conservative (raw URL)" case .urlRule: "URL rule–derived" }
diff --git a/Asterism/Asterism/ViewModels/EntryCorrectionFormModel.swift b/Asterism/Asterism/ViewModels/EntryCorrectionFormModel.swiftnew file mode 100644index 00000000..684efc84--- /dev/null+++ b/Asterism/Asterism/ViewModels/EntryCorrectionFormModel.swift@@ -0,0 +1,60 @@+import AsterismCore+import Foundation++@MainActor @Observable+final class EntryCorrectionFormModel {+ var kind: AuthoredEntryTarget.Kind+ var title: String+ var designation: String+ var destinationID: UUID? { didSet { contract = nil } }+ var contentChoice: EntryCorrectionContentChoice?+ private(set) var contract: EntryCorrectionContract?+ private(set) var choices: [ChapterCaptureEntry] = []+ private(set) var errorMessage: String?+ private(set) var isSaving = false+ private(set) var didSave = false+ private var destinationRevision = 0+ private let entry: EntrySnapshot+ private let library: any LibraryProviding+ private let onMutation: @Sendable () async -> Void+ init(entry: EntrySnapshot, library: any LibraryProviding, onMutation: @escaping @Sendable () async -> Void) {+ self.entry = entry; self.library = library; self.onMutation = onMutation+ kind = entry.authoredTarget?.kind ?? .chapter+ title = entry.authoredTarget?.title ?? entry.chapterTitle ?? ""+ designation = entry.authoredTarget?.designation ?? entry.chapterSequence ?? ""+ }+ func load() async {+ do {+ if let workID = entry.workID {+ choices = try await library.projectManualEntry(workID: workID).entries.filter {+ $0.id != entry.id && $0.target?.kind != .note && !$0.requiresReview+ }+ }+ await reviewDestination(destinationID)+ } catch { errorMessage = error.localizedDescription }+ }+ func reviewDestination(_ id: UUID?) async {+ destinationRevision += 1+ let revision = destinationRevision+ destinationID = id; contentChoice = nil+ do {+ let next = try await library.projectEntryCorrection(entryID: entry.id, destinationID: id)+ guard revision == destinationRevision && destinationID == id else { return }+ contract = next; errorMessage = nil+ } catch {+ guard revision == destinationRevision && destinationID == id else { return }+ errorMessage = error.localizedDescription+ }+ }+ var canSave: Bool { !didSave && !isSaving && contract != nil && (contract?.needsContentChoice != true || contentChoice != nil) }+ func save() async {+ guard canSave, let contract else { return }+ isSaving = true; defer { isSaving = false }+ do {+ switch try await library.commitEntryCorrection(contract, target: .init(kind: kind, title: title, designation: designation), contentChoice: contentChoice) {+ case .committed: didSave = true; await onMutation()+ case .reviewRequired(let reason): errorMessage = reason+ }+ } catch { errorMessage = error.localizedDescription }+ }+}
diff --git a/Asterism/Asterism/ViewModels/EntryDetailModel.swift b/Asterism/Asterism/ViewModels/EntryDetailModel.swiftindex 8ad8539d..202b09e3 100644--- a/Asterism/Asterism/ViewModels/EntryDetailModel.swift+++ b/Asterism/Asterism/ViewModels/EntryDetailModel.swift@@ -120,6 +120,11 @@ public final class EntryDetailModel { /// (`ipad-and-mac-layouts` Q57), and a marker keyed on the argument cannot /// see that. public let entryID: UUID+ func correctionForm() -> EntryCorrectionFormModel? {+ entry.map { EntryCorrectionFormModel(entry: $0, library: library, onMutation: { [weak self] in+ await self?.load(); await self?.onMutation()+ }) }+ } private let library: any LibraryProviding public let capabilities: AsterismCapabilities private let onMutation: @Sendable () async -> Void@@ -199,7 +204,8 @@ public final class EntryDetailModel { /// parsed chapter. public var titleCardHeading: String { guard let entry else { return "" }- return entry.chapterTitle+ return entry.authoredNoteTitle+ ?? entry.chapterTitle ?? entry.chapterSequence ?? teachingDetail?.displayTitle ?? entry.captureTitle
diff --git a/Asterism/Asterism/ViewModels/ManualEntryFormModel.swift b/Asterism/Asterism/ViewModels/ManualEntryFormModel.swiftnew file mode 100644index 00000000..25c4af5d--- /dev/null+++ b/Asterism/Asterism/ViewModels/ManualEntryFormModel.swift@@ -0,0 +1,78 @@+import AsterismCore+import Foundation++/// One value draft; loading and refused saves never replace reader input.+@MainActor @Observable+final class ManualEntryFormModel {+ var kind: AuthoredEntryTarget.Kind = .note {+ didSet {+ if let id = existingEntryID, !choices.contains(where: { $0.id == id }) {+ existingEntryID = nil; needsContentChoice = false+ }+ confirmedNewChapter = false+ }+ }+ var title = ""+ var designation = ""+ var sourceURL = ""+ var note = "" { didSet { if !isPrefilling { hasEditedContent = true } } }+ var rating: Rating? { didSet { if !isPrefilling { hasEditedContent = true } } }+ private var isPrefilling = false+ private var hasEditedContent = false+ private(set) var needsContentChoice = false+ var selectedEntry: ChapterCaptureEntry? { choices.first { $0.id == existingEntryID } }+ var existingEntryID: UUID?+ var confirmedNewChapter = false+ private(set) var projection: ChapterCaptureProjection?+ private(set) var errorMessage: String?+ private(set) var isSaving = false+ private(set) var savedEntryID: UUID?+ let workID: UUID+ private let library: any LibraryProviding+ private let onMutation: @Sendable () async -> Void++ init(workID: UUID, library: any LibraryProviding, onMutation: @escaping @Sendable () async -> Void) {+ self.workID = workID; self.library = library; self.onMutation = onMutation+ }+ var canSave: Bool { savedEntryID == nil && projection != nil && !isSaving && !needsContentChoice && (!note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || rating != nil) }+ var choices: [ChapterCaptureEntry] {+ projection?.entries.filter { !$0.requiresReview && ($0.target?.kind == kind || ($0.target == nil && kind == .chapter)) } ?? []+ }+ func load() async {+ do { projection = try await library.projectManualEntry(workID: workID) }+ catch { errorMessage = error.localizedDescription }+ }+ func choose(_ id: UUID?) {+ existingEntryID = id; needsContentChoice = false+ guard let entry = selectedEntry else { return }+ if !hasEditedContent { prefill(entry) }+ else { needsContentChoice = note != entry.note || rating != entry.rating }+ }+ func chooseContent(_ choice: EntryCorrectionContentChoice) {+ if choice == .destination, let entry = selectedEntry { prefill(entry) }+ needsContentChoice = false+ }+ private func prefill(_ entry: ChapterCaptureEntry) {+ isPrefilling = true; defer { isPrefilling = false }+ note = entry.note; rating = entry.rating; hasEditedContent = false+ }+ func save() async {+ guard canSave, let projection else { return }+ isSaving = true+ defer { isSaving = false }+ errorMessage = nil+ let draft = ManualEntryDraft(target: .init(kind: kind, title: title, designation: designation),+ sourceURL: sourceURL, note: note, rating: rating, existingEntryID: existingEntryID,+ confirmedNewChapter: confirmedNewChapter)+ do {+ switch try await library.commitManualEntry(projection: projection, draft: draft) {+ case .committed(let entry): savedEntryID = entry.id; await onMutation()+ case .reviewRequired(let fresh, let reason):+ self.projection = fresh; errorMessage = reason+ if let selected = selectedEntry {+ needsContentChoice = note != selected.note || rating != selected.rating+ }+ }+ } catch { errorMessage = error.localizedDescription }+ }+}
diff --git a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift b/Asterism/Asterism/ViewModels/SettingsBackupModel.swiftindex e79aafe8..23bac07a 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 `BackupV18Exporter` to this protocol via extension below.+/// surface. Conforms `BackupV19Exporter` 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@@ -18,7 +18,7 @@ public protocol BackupExporting: Sendable { func scavengeStaleFiles() } -extension BackupV18Exporter: BackupExporting {}+extension BackupV19Exporter: BackupExporting {} // MARK: - Export Stage
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel.swift b/Asterism/Asterism/ViewModels/WorkDetailModel.swiftindex 734d9309..6d90105e 100644--- a/Asterism/Asterism/ViewModels/WorkDetailModel.swift+++ b/Asterism/Asterism/ViewModels/WorkDetailModel.swift@@ -213,6 +213,7 @@ public final class WorkDetailModel { /// because the transitions carry rules — the finished-reading prompt on one /// side and Req 3.3's auto-revert on the other. A raw property write from a /// control would step past both.+ public var draftChapterCaptureDefault: ChapterCaptureDefault = .ordinary public private(set) var draftWorkStatus: WorkStatus = .ongoing public private(set) var draftReturnDate: CivilDay? private var baselinePublicationStatus: WorkStatus = .ongoing@@ -444,6 +445,12 @@ public final class WorkDetailModel { /// `.stored` cover through the shared loader, which is keyed by work id /// (`work-thumbnails` Req 7.2). let workID: UUID+ func manualEntryForm() -> ManualEntryFormModel {+ ManualEntryFormModel(workID: workID, library: library, onMutation: { [weak self] in+ await self?.load(); await self?.onMutation()+ })+ }+ private let library: any LibraryProviding /// The locale a position is read and written in (Reqs 2.2, 2.7). Taken at /// construction, as `SeriesDetailModel` and `MarkdownExportModel` take@@ -515,6 +522,7 @@ public final class WorkDetailModel { typeOptions = await pickerOptions(carrying: snapshot.typeDisplay) draftTags = snapshot.genreTags draftNotes = snapshot.genericNotes+ draftChapterCaptureDefault = snapshot.chapterCaptureDefault seedPublicationDraft(from: snapshot) draftReadingStatus = snapshot.readingStatus draftVerdict = snapshot.verdict@@ -1733,8 +1741,8 @@ public final class WorkDetailModel { /// a screen showing site B while sending site A is refused at best and /// writes B's address onto A's membership at worst. ///- /// A Work with no membership at all (Req 8.1's tolerated state) has no site- /// to confirm a URL for, and the repository refuses it by name.+ /// A Work without a membership starts with no selected site. A validated+ /// optional URL supplies the first membership in the guarded URL commit. public private(set) var selectedWorkURLHostname: String = "" /// Every site the Work is on, in membership order (Req 1.2).@@ -2051,6 +2059,7 @@ public final class WorkDetailModel { || draftAssignment != work.typeDisplay.assignment || draftTags != work.genreTags || draftNotes != work.genericNotes+ || draftChapterCaptureDefault != work.chapterCaptureDefault || publicationEdit != .unchanged || draftReadingStatus != work.readingStatus // Compared whatever the reading status is (Req 2.5): a verdict the@@ -2254,6 +2263,7 @@ public final class WorkDetailModel { draftAssignment = work.typeDisplay.assignment draftTags = work.genreTags draftNotes = work.genericNotes+ draftChapterCaptureDefault = work.chapterCaptureDefault seedPublicationDraft(from: work) draftReadingStatus = work.readingStatus draftVerdict = work.verdict@@ -2789,7 +2799,8 @@ public final class WorkDetailModel { // Req 2.2: the cover rides this commit like every other field. // `.keep` on a save that did not touch it, which is what keeps // an ordinary save from reading a byte of cover (Q37, Q49).- thumbnail: thumbnailWrite+ thumbnail: thumbnailWrite,+ chapterCaptureDefault: draftChapterCaptureDefault ) let basis = editorWorkBasis ?? work.map(WorkEditBasis.init(work:)) ?? WorkEditBasis(@@ -3141,6 +3152,9 @@ public final class WorkDetailModel { let outcome = try await library.commitWorkURL(contract) switch outcome { case .committed:+ if contract.basis.membershipID == nil {+ editorWorkBasis = editorWorkBasis?.addingSiteFreeMembership(hostname: contract.basis.siteHostname.value)+ } applyProjection(contract, replaceDraft: true) await onMutation() return true
diff --git a/Asterism/Asterism/Views/EntryCorrectionView.swift b/Asterism/Asterism/Views/EntryCorrectionView.swiftnew file mode 100644index 00000000..d2c96abd--- /dev/null+++ b/Asterism/Asterism/Views/EntryCorrectionView.swift@@ -0,0 +1,58 @@+import AsterismCore+import SwiftUI++struct EntryCorrectionView: View {+ @State var model: EntryCorrectionFormModel+ @Environment(\.dismiss) private var dismiss+ var body: some View {+ NavigationStack {+ Form {+ Picker("Entry kind", selection: $model.kind) {+ Text("Note").tag(AuthoredEntryTarget.Kind.note)+ Text("Chapter").tag(AuthoredEntryTarget.Kind.chapter)+ }.accessibilityIdentifier("entry-correction-kind")+ TextField("Title (optional)", text: $model.title).accessibilityIdentifier("entry-correction-title")+ if model.kind == .chapter {+ TextField("Chapter designation (optional)", text: $model.designation)+ .accessibilityIdentifier("entry-correction-designation")+ }+ Picker("Use existing chapter", selection: Binding(get: { model.destinationID }, set: { id in Task { await model.reviewDestination(id) } })) {+ Text("Keep separate").tag(UUID?.none)+ ForEach(model.choices, id: \.id) { entry in+ Text(entry.displayLabel.isEmpty ? "Chapter" : entry.displayLabel).tag(Optional(entry.id))+ }+ }.accessibilityIdentifier("entry-correction-destination")+ if let contract = model.contract, contract.needsContentChoice {+ Section("Choose the note and rating to keep") {+ Text("This entry") .font(.headline)+ Text(contract.source.note.isEmpty ? "No note" : contract.source.note)+ Text("Rating: \(contract.source.rating?.rawValue ?? "No rating")")+ Text("Existing chapter") .font(.headline)+ Text(contract.destination?.note.isEmpty == false ? contract.destination!.note : "No note")+ Text("Rating: \(contract.destination?.rating?.rawValue ?? "No rating")")+ Picker("Keep content", selection: $model.contentChoice) {+ Text("Choose…").tag(EntryCorrectionContentChoice?.none)+ Text("This entry").tag(Optional(EntryCorrectionContentChoice.source))+ Text("Existing chapter").tag(Optional(EntryCorrectionContentChoice.destination))+ }.accessibilityIdentifier("entry-correction-content")+ }+ }+ if let error = model.errorMessage {+ Text(error).foregroundStyle(.red).accessibilityIdentifier("entry-correction-error")+ Button("Review again") { Task { await model.reviewDestination(model.destinationID) } }+ .disabled(model.isSaving).accessibilityIdentifier("entry-correction-review")+ }+ }+ .navigationTitle("Correct entry")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button(role: .close) { dismiss() }.disabled(model.isSaving).accessibilityLabel("Cancel")+ }+ ToolbarItem(placement: .confirmationAction) {+ Button(role: .confirm) { Task { await model.save(); if model.didSave { dismiss() } } }+ .disabled(!model.canSave).accessibilityLabel("Save").accessibilityIdentifier("entry-correction-save")+ }+ }+ }.task { await model.load() }+ }+}
diff --git a/Asterism/Asterism/Views/EntryDetailView.swift b/Asterism/Asterism/Views/EntryDetailView.swiftindex 8454705d..6699a819 100644--- a/Asterism/Asterism/Views/EntryDetailView.swift+++ b/Asterism/Asterism/Views/EntryDetailView.swift@@ -23,6 +23,7 @@ struct EntryDetailView: View { @Environment(\.siteNames) private var siteNames @State private var showingComposedTeaching = false @State private var showingReparse = false+ @State private var showingCorrection = false /// Q49: collapsed by default. Capture evidence and the recovery actions are /// the screen's error-handling surface, not part of reading a note. @State private var showingCaptureDetails = false@@ -119,6 +120,14 @@ struct EntryDetailView: View { @ViewBuilder private func entryContent(_ entry: EntrySnapshot) -> some View { Form {+ if entry.changesAfterCombine {+ Section("Changes after combine") {+ Text("This entry received changes after it was combined. Review its note and rating before using it as a chapter.")+ Button("Review changes") { showingCorrection = true }+ .disabled(model.state == .submitting || model.hasUnsavedChanges)+ .accessibilityIdentifier("entry-detail-review-combined-changes")+ }+ } exportFailureNotice titleSection(entry)@@ -225,6 +234,11 @@ struct EntryDetailView: View { .accessibilityLabel("Export this note as markdown") } }+ ToolbarItem(placement: .trailingBar) {+ Button { showingCorrection = true } label: { Label("Correct entry", systemImage: "pencil.circle") }+ .disabled(model.hasUnsavedChanges || model.isReadOnly || model.state == .submitting)+ .accessibilityIdentifier("entry-detail-correct")+ } ToolbarItem(placement: .confirmationAction) { // Q55: the *label-less* `Button(role:action:)`, which is what // draws the role's own glyph and nothing else. `Button("Update",@@ -306,6 +320,9 @@ struct EntryDetailView: View { } message: { disclosure in Text(disclosureMessage(disclosure)) }+ .sheet(isPresented: $showingCorrection) {+ if let form = model.correctionForm() { EntryCorrectionView(model: form) }+ } .sheet(isPresented: $showingComposedTeaching) { if let teachModel = model.composedTeachingModel() { ComposedTeachingContainerView(model: teachModel)@@ -371,7 +388,7 @@ struct EntryDetailView: View { // own hit area rather than being swallowed by the name's. Spacer(minLength: 0) - if let url = URL(string: entry.rawURLString) {+ if let url = entry.primarySourceURL { // Q51: the glyph iOS already uses for "this goes to a // page", in place of a row that spelled it out. Keeps // `entry-detail-link`: same action, same destination.@@ -387,6 +404,14 @@ struct EntryDetailView: View { } } + ForEach(Array(entry.sourceURLs.enumerated()), id: \.offset) { _, source in+ if (entry.primarySourceURL.map { ExactScalarString(source) != ExactScalarString($0.absoluteString) } ?? true), let url = URL(string: source), ["http", "https"].contains(url.scheme?.lowercased() ?? ""), url.host != nil {+ Link(source, destination: url)+ .font(.caption)+ .accessibilityIdentifier("entry-detail-additional-source")+ }+ }+ HStack(spacing: 12) { ratingButton(.up) ratingButton(.down)
diff --git a/Asterism/Asterism/Views/ManualEntryView.swift b/Asterism/Asterism/Views/ManualEntryView.swiftnew file mode 100644index 00000000..7c5315c8--- /dev/null+++ b/Asterism/Asterism/Views/ManualEntryView.swift@@ -0,0 +1,79 @@+import AsterismCore+import SwiftUI++struct ManualEntryView: View {+ @State var model: ManualEntryFormModel+ @Environment(\.dismiss) private var dismiss+ var body: some View {+ NavigationStack {+ Form {+ Picker("Entry", selection: $model.kind) {+ Text("Note").tag(AuthoredEntryTarget.Kind.note)+ Text("Chapter").tag(AuthoredEntryTarget.Kind.chapter)+ }+ .accessibilityIdentifier("manual-entry-kind")+ if !model.choices.isEmpty || model.existingEntryID != nil {+ Picker("Use existing entry", selection: Binding(get: { model.existingEntryID }, set: { model.choose($0) })) {+ Text("New entry").tag(UUID?.none)+ if let id = model.existingEntryID, !model.choices.contains(where: { $0.id == id }) {+ Text("Selected entry unavailable — choose again").tag(Optional(id))+ }+ ForEach(model.choices, id: \.id) { entry in+ Text(entry.displayLabel.isEmpty ? (entry.target?.kind == .note ? "Note" : "Chapter") : entry.displayLabel)+ .tag(Optional(entry.id))+ }+ }+ .accessibilityIdentifier("manual-entry-existing")+ }+ if model.needsContentChoice, let selected = model.selectedEntry {+ Section("Choose the note and rating to keep") {+ Text("Selected entry: \(selected.note.isEmpty ? "No note" : selected.note)")+ Text("Rating: \(selected.rating?.rawValue ?? "No rating")")+ Button("Keep my draft") { model.chooseContent(.source) }+ .accessibilityIdentifier("manual-entry-keep-draft")+ Button("Keep selected entry content") { model.chooseContent(.destination) }+ .accessibilityIdentifier("manual-entry-keep-existing")+ }+ }+ if model.existingEntryID == nil {+ TextField("Title (optional)", text: $model.title)+ .accessibilityIdentifier("manual-entry-title")+ if model.kind == .chapter {+ TextField("Chapter designation (optional)", text: $model.designation)+ .accessibilityIdentifier("manual-entry-designation")+ if !model.choices.isEmpty {+ Toggle("Create a separate chapter", isOn: $model.confirmedNewChapter)+ .accessibilityIdentifier("manual-entry-confirm-new")+ }+ }+ }+ TextField("Source URL (optional)", text: $model.sourceURL)+ .urlKeyboard().autocorrectionDisabled()+ .accessibilityIdentifier("manual-entry-source")+ TextField("Note", text: $model.note, axis: .vertical)+ .lineLimit(4...12).accessibilityIdentifier("manual-entry-note")+ HStack {+ Button { model.rating = model.rating == .up ? nil : .up } label: { Label("Liked", systemImage: "hand.thumbsup") }+ .tint(model.rating == .up ? .accentColor : .secondary)+ .accessibilityIdentifier("manual-entry-rating-up")+ Button { model.rating = model.rating == .down ? nil : .down } label: { Label("Disliked", systemImage: "hand.thumbsdown") }+ .tint(model.rating == .down ? .accentColor : .secondary)+ .accessibilityIdentifier("manual-entry-rating-down")+ }+ if let error = model.errorMessage { Text(error).foregroundStyle(.red).accessibilityIdentifier("manual-entry-error") }+ }+ .navigationTitle("Add note")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button(role: .close) { dismiss() }.disabled(model.isSaving)+ .accessibilityLabel("Cancel").accessibilityIdentifier("manual-entry-cancel")+ }+ ToolbarItem(placement: .confirmationAction) {+ Button(role: .confirm) { Task { await model.save(); if model.savedEntryID != nil { dismiss() } } }+ .disabled(!model.canSave).accessibilityLabel("Save").accessibilityIdentifier("manual-entry-save")+ }+ }+ }+ .task { await model.load() }+ }+}
diff --git a/Asterism/Asterism/Views/NewWorkView.swift b/Asterism/Asterism/Views/NewWorkView.swiftindex 439d530d..5d4128c4 100644--- a/Asterism/Asterism/Views/NewWorkView.swift+++ b/Asterism/Asterism/Views/NewWorkView.swift@@ -25,7 +25,7 @@ struct NewWorkView: View { // detail's Work URL field's, and the identifier does not // move. TextField(- "Site or URL", text: $model.draftHostname,+ "Site or URL (optional)", text: $model.draftHostname, prompt: Text("example.com or example.com/story")) .urlKeyboard() .autocorrectionDisabled()
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex fd034f37..ac41ef92 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -30,6 +30,7 @@ struct WorkDetailView: View { @State private var detailWidth: CGFloat = 0 @State private var model: WorkDetailModel @State private var pendingLatestRefresh = false+ @State private var showingManualEntry = false @State private var isPickingReturnDate = false @State private var pickedReturnDate = Date.distantPast @Environment(\.dismiss) private var dismiss@@ -265,6 +266,9 @@ struct WorkDetailView: View { } // A tall Status card can scroll its Form section out of view at // accessibility sizes; keep the date sheet's presenter on this root.+ .sheet(isPresented: $showingManualEntry) {+ ManualEntryView(model: model.manualEntryForm())+ } .sheet(isPresented: $isPickingReturnDate) { returnDatePicker } } @@ -1775,6 +1779,12 @@ struct WorkDetailView: View { private var editNotesSection: some View { Section {+ Picker("Pages usually contain", selection: $model.draftChapterCaptureDefault) {+ Text("One chapter").tag(ChapterCaptureDefault.ordinary)+ Text("Multiple chapters").tag(ChapterCaptureDefault.multipleChaptersPerPage)+ }+ .pickerStyle(.menu)+ .accessibilityIdentifier("work-detail-chapter-capture-default") TextField("Notes", text: $model.draftNotes, axis: .vertical) .lineLimit(3...6) .accessibilityIdentifier("work-detail-notes-field")@@ -2028,6 +2038,11 @@ struct WorkDetailView: View { .accessibilityLabel("Save") } } else {+ ToolbarItem(placement: .trailingBar) {+ Button { showingManualEntry = true } label: { Label("Add note", systemImage: "square.and.pencil") }+ .disabled(model.isReadOnly)+ .accessibilityIdentifier("work-detail-add-note")+ } if exportModel != nil { ToolbarItem(placement: .trailingBar) { // Q48's glyph, as on entry detail: export is a read action,
diff --git a/Asterism/AsterismShareExtension/CaptureView.swift b/Asterism/AsterismShareExtension/CaptureView.swiftindex e43709ca..cafd3c93 100644--- a/Asterism/AsterismShareExtension/CaptureView.swift+++ b/Asterism/AsterismShareExtension/CaptureView.swift@@ -129,6 +129,9 @@ struct CaptureView: View { if let reviewMessage { reviewBanner(message: reviewMessage) }+ if let projection = viewModel.chapterProjection {+ ChapterCaptureChoicesView(projection: projection, choose: viewModel.chooseChapterIntent)+ } ratingSection noteSection // Under the editor, never above it (Decision 1). Nothing renders for a@@ -518,6 +521,12 @@ final class ObservableCaptureViewModel: ObservableObject { } var canSave: Bool { viewModel.canSave }+ var chapterProjection: ChapterCaptureProjection? { viewModel.chapterProjection }+ func chooseChapterIntent(_ intent: ChapterCaptureIntent) {+ viewModel.chooseChapterIntent(intent)+ refreshState()+ }+ var isSaved: Bool { if case .saved = state { return true } return false
diff --git a/Asterism/AsterismShareExtension/ChapterCaptureChoicesView.swift b/Asterism/AsterismShareExtension/ChapterCaptureChoicesView.swiftnew file mode 100644index 00000000..0514cd17--- /dev/null+++ b/Asterism/AsterismShareExtension/ChapterCaptureChoicesView.swift@@ -0,0 +1,85 @@+import AsterismCore+import SwiftUI++/// Uses the same immutable projection on the new and saved-page branches.+struct ChapterCaptureChoicesView: View {+ let projection: ChapterCaptureProjection+ let choose: (ChapterCaptureIntent) -> Void+ @State private var isCorrecting = false+ @State private var title = ""+ @State private var designation = ""+ @State private var choiceMessage: String?+ @State private var choseNewChapter = false+ @State private var correctingExisting: UUID?+ @State private var selectedExisting: UUID?+ init(projection: ChapterCaptureProjection, choose: @escaping (ChapterCaptureIntent) -> Void) {+ self.projection = projection; self.choose = choose+ _title = State(initialValue: projection.evidence.first { $0.binding.origin == .designation }?.binding.key ?? "")+ let sequences = Set(projection.evidence.filter { $0.binding.origin != .designation }.compactMap(\.chapterFact))+ _designation = State(initialValue: sequences.count == 1 ? (sequences.first?.value ?? "") : "")+ }+ private var needsChoice: Bool {+ switch projection.resolution {+ case .chooseChapter: true+ case .newChapter(let requiresConfirmation): requiresConfirmation+ default: false+ }+ }+ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ if case .chooseChapter(_, let reason) = projection.resolution { Text(reason) }+ if projection.offersAnotherChapter || needsChoice || isCorrecting {+ ForEach(projection.entries.filter { !$0.requiresReview && (projection.evidence.isEmpty || $0.target?.kind != .note) }, id: \.id) { entry in+ Button(entry.displayLabel.isEmpty ? "Use this entry" : "Use \(entry.displayLabel)") {+ choseNewChapter = false; selectedExisting = entry.id+ if isCorrecting {+ correctingExisting = entry.id+ choose(.correctedExisting(entry.id, contentChoice: nil))+ } else { correctingExisting = nil; choose(.existing(entry.id)) }+ choiceMessage = "Updating the selected entry"+ }+ .accessibilityIdentifier("capture.chapter-existing-\(entry.id.uuidString.lowercased())")+ }+ TextField("Chapter title (optional)", text: $title)+ .accessibilityIdentifier("capture.chapter-title")+ TextField("Chapter designation (optional)", text: $designation)+ .accessibilityIdentifier("capture.chapter-designation")+ Button(isCorrecting ? "Use corrected chapter" : (projection.evidence.isEmpty ? "Add another chapter" : "Confirm new chapter")) {+ choseNewChapter = true; correctingExisting = nil; selectedExisting = nil+ updateNewChapter()+ choiceMessage = "Saving a separate chapter"+ }+ .accessibilityIdentifier(isCorrecting ? "capture.use-corrected-chapter" : (projection.evidence.isEmpty ? "capture.add-another-chapter" : "capture.confirm-new-chapter"))+ Button("Save a separate note") { choseNewChapter = false; selectedExisting = nil; correctingExisting = nil; choose(.genericNote); choiceMessage = "Saving a separate note" }+ .accessibilityIdentifier("capture.generic-note")+ if choseNewChapter && !isCorrecting && projection.captureDefault == .ordinary,+ projection.entries.contains(where: { $0.target?.kind != .note && $0.sourceURLs.contains(ExactScalarString(projection.rawURL)) }) {+ Text("Saving a second chapter from this page will default this work to multiple chapters per page. You can change that in Edit Work.")+ .font(.caption)+ }+ }+ if !projection.evidence.isEmpty && !isCorrecting {+ Button("Correct detected chapter") { isCorrecting = true }+ .accessibilityIdentifier("capture.correct-chapter")+ }+ if let id = selectedExisting, let entry = projection.entries.first(where: { $0.id == id }) {+ Text("Existing chapter: \(entry.note)")+ Text("Rating: \(entry.rating?.rawValue ?? "No rating")")+ Button("Keep my draft note and rating") { choose(correctingExisting == nil ? .existing(id, contentChoice: .source) : .correctedExisting(id, contentChoice: .source)) }+ .accessibilityIdentifier("capture.correction-keep-draft")+ Button("Keep existing chapter note and rating") { choose(correctingExisting == nil ? .existing(id, contentChoice: .destination) : .correctedExisting(id, contentChoice: .destination)) }+ .accessibilityIdentifier("capture.correction-keep-existing")+ }+ if let choiceMessage { Text(choiceMessage).font(.caption).accessibilityIdentifier("capture.chapter-choice") }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .onChange(of: title) { _, _ in updateNewChapter() }+ .onChange(of: designation) { _, _ in updateNewChapter() }+ }+ private func updateNewChapter() {+ if choseNewChapter {+ let target = AuthoredEntryTarget(kind: .chapter, title: title, designation: designation)+ choose(isCorrecting ? .correctedNewChapter(target) : .newChapter(target, confirmedNew: true))+ }+ }+}
diff --git a/Asterism/AsterismShareExtension/ReShareCaptureView.swift b/Asterism/AsterismShareExtension/ReShareCaptureView.swiftindex af681047..8e62d677 100644--- a/Asterism/AsterismShareExtension/ReShareCaptureView.swift+++ b/Asterism/AsterismShareExtension/ReShareCaptureView.swift@@ -45,7 +45,7 @@ struct ReShareCaptureView: View { if case .readyEdit = viewModel.state { ToolbarItem(placement: .confirmationAction) { Button(role: .confirm) { viewModel.submitUpdate() }- .disabled(viewModel.isSaving)+ .disabled(!viewModel.canSaveUpdate) .accessibilityLabel( ReShareActionLabels.primaryActionAccessibilityLabel(for: viewModel.state)) .accessibilityIdentifier("reshare.update")@@ -142,6 +142,10 @@ struct ReShareCaptureView: View { errorBanner(message: errorMessage) } + if let projection = viewModel.chapterProjection {+ ChapterCaptureChoicesView(projection: projection, choose: viewModel.chooseChapterIntent)+ }+ // Rating section ratingSection @@ -303,11 +307,19 @@ final class ObservableReShareViewModel: ObservableObject { } @Published var draftRating: Rating? + var chapterProjection: ChapterCaptureProjection? { viewModel.chapterProjection }+ func chooseChapterIntent(_ intent: ChapterCaptureIntent) {+ viewModel.chooseChapterIntent(intent)+ refreshState()+ }+ var isSaved: Bool { if case .saved = state { return true } return false } + var canSaveUpdate: Bool { viewModel.canSaveUpdate }+ var isSaving: Bool { if case .saving = state { return true } return false
diff --git a/Asterism/AsterismTests/EntryCorrectionFormModelTests.swift b/Asterism/AsterismTests/EntryCorrectionFormModelTests.swiftnew file mode 100644index 00000000..b8552ace--- /dev/null+++ b/Asterism/AsterismTests/EntryCorrectionFormModelTests.swift@@ -0,0 +1,80 @@+import AsterismTestSupport+@testable import AsterismCore+import Foundation+import Testing+@testable import Asterism++@Suite("Correction form drafts") @MainActor+struct EntryCorrectionFormModelTests {+ @Test("Combining conflicting notes and ratings requires an explicit content review")+ func combineContentReview() async {+ let mock = MockLibraryProvider(), entry = TestFixtures.makeEntry(note: "Draft source", rating: .up), destination = UUID()+ mock.correctionProjectionHandler = { id, dest in+ .init(entryID: id, destinationID: dest, source: .init(note: "Draft source", rating: .up),+ destination: .init(note: "Saved destination", rating: .down), sourceModifiedAt: .distantPast,+ destinationModifiedAt: .distantPast)+ }+ mock.correctionCommitResult = .success(.reviewRequired(reason: "Destination changed"))+ let model = EntryCorrectionFormModel(entry: entry, library: mock, onMutation: {})+ await model.reviewDestination(destination)+ #expect(model.contract?.source.note == "Draft source" && model.contract?.destination?.note == "Saved destination")+ #expect(!model.canSave)+ await model.save()+ #expect(mock.correctionCommitCount == 0)+ model.contentChoice = .destination; model.title = "Corrected chapter"; model.designation = "13"+ await model.save()+ #expect(mock.correctionCommitCount == 1 && model.contentChoice == .destination && !model.didSave)+ #expect(model.title == "Corrected chapter" && model.designation == "13")+ }+ @Test("Rating-only conflicts require review; refusal preserves labels and permits reviewing again")+ func ratingOnlyRefusal() async {+ let mock = MockLibraryProvider(), entry = TestFixtures.makeEntry(rating: .up), destination = UUID()+ mock.correctionProjectionHandler = { id, dest in+ .init(entryID: id, destinationID: dest, source: .init(rating: .up),+ destination: dest == nil ? nil : .init(rating: .down), sourceModifiedAt: .distantPast,+ destinationModifiedAt: dest == nil ? nil : .distantPast)+ }+ mock.correctionCommitResult = .success(.reviewRequired(reason: "Changed"))+ let model = EntryCorrectionFormModel(entry: entry, library: mock, onMutation: {})+ await model.reviewDestination(destination)+ #expect(model.contract?.needsContentChoice == true && !model.canSave)+ model.title = "Reader title"; model.designation = "012"; model.contentChoice = .source+ await model.save()+ #expect(model.kind == .chapter && model.title == "Reader title" && model.designation == "012" && !model.didSave)+ #expect(model.contentChoice == .source)+ await model.reviewDestination(destination)+ #expect(model.title == "Reader title" && model.designation == "012")+ #expect(mock.correctionCommitCount == 1)+ }+ @Test("A successful correction commits and publishes the mutation exactly once")+ func successfulSaveOnce() async {+ let mock = MockLibraryProvider(), entry = TestFixtures.makeEntry(), tracker = CallbackTracker()+ mock.correctionProjectionHandler = { id, dest in+ .init(entryID: id, destinationID: dest, source: .bare, destination: nil,+ sourceModifiedAt: .distantPast, destinationModifiedAt: nil)+ }+ mock.correctionCommitResult = .success(.committed(entryID: entry.id))+ let model = EntryCorrectionFormModel(entry: entry, library: mock,+ onMutation: { tracker.mutationCount += 1 })+ await model.reviewDestination(nil)+ model.kind = .note; model.title = "Reaction"+ await model.save(); await model.save()+ #expect(model.didSave && !model.canSave)+ #expect(mock.correctionCommitCount == 1 && tracker.mutationCount == 1)+ }+ @Test("A slower former destination cannot replace the currently selected review")+ func selectionRace() async {+ let mock = MockLibraryProvider(), entry = TestFixtures.makeEntry(), first = UUID(), second = UUID()+ mock.correctionProjectionHandler = { id, dest in+ if dest == first { try await Task.sleep(for: .milliseconds(40)) }+ return .init(entryID: id, destinationID: dest, source: .bare, destination: .bare,+ sourceModifiedAt: .distantPast, destinationModifiedAt: .distantPast)+ }+ let model = EntryCorrectionFormModel(entry: entry, library: mock, onMutation: {})+ let slow = Task { await model.reviewDestination(first) }+ await Task.yield()+ await model.reviewDestination(second)+ await slow.value+ #expect(model.destinationID == second && model.contract?.destinationID == second)+ }+}
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex 21feda1d..1b271c7a 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -4,6 +4,28 @@ import Foundation /// Test double for LibraryProviding that records calls and returns preset results. final class MockLibraryProvider: LibraryProviding, @unchecked Sendable {+ var manualProjectionResult: Result<ChapterCaptureProjection, Error> = .failure(MockError.notConfigured)+ var manualCommitResult: Result<ChapterCaptureCommitOutcome, Error> = .failure(MockError.notConfigured)+ var manualCommitDrafts: [ManualEntryDraft] = []+ func projectManualEntry(workID: UUID) async throws -> ChapterCaptureProjection { try manualProjectionResult.get() }+ func commitManualEntry(projection: ChapterCaptureProjection, draft: ManualEntryDraft) async throws -> ChapterCaptureCommitOutcome {+ manualCommitDrafts.append(draft)+ return try manualCommitResult.get()+ }++ var correctionProjectionHandler: (@Sendable (UUID, UUID?) async throws -> EntryCorrectionContract)?+ var correctionCommitResult: Result<EntryCorrectionOutcome, Error> = .failure(MockError.notConfigured)+ var correctionCommitCount = 0+ func projectEntryCorrection(entryID: UUID, destinationID: UUID?) async throws -> EntryCorrectionContract {+ guard let handler = correctionProjectionHandler else { throw MockError.notConfigured }+ return try await handler(entryID, destinationID)+ }+ func commitEntryCorrection(_ contract: EntryCorrectionContract, target: AuthoredEntryTarget,+ contentChoice: EntryCorrectionContentChoice?) async throws -> EntryCorrectionOutcome {+ correctionCommitCount += 1+ return try correctionCommitResult.get()+ }+ // MARK: - Call tracking /// The order calls arrived in, for the assertions counts cannot make — the
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex f1cad6ee..dfff7599 100644--- a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift+++ b/Asterism/AsterismTests/IntegrationSafetyNetTests.swift@@ -241,13 +241,13 @@ struct IntegrationSafetyNetTests { Issue.record("Expected Backup export for \(environment) \(capabilities.gate.rawValue)") continue }- // Settings writes 12/13 now (Req 13.1): the archive has to carry+ // Settings writes 19/20 now: the archive has to carry // a Work's site memberships, the reader's dismissed pairs, // version-free citations and the Work's two statuses and // verdict, so the round-trip is reachable from the surface the // reader uses. The gate the file declares is still the running // one.- let document = try BackupV18Codec.decode(Data(contentsOf: backupURL))+ let document = try BackupV19Codec.decode(Data(contentsOf: backupURL)) #expect(document.capabilityGate == AsterismCapabilities.current.gate.rawValue) backup.shareDismissed() backup.handleShareOutcome(.cancelled)
diff --git a/Asterism/AsterismTests/ManualEntryFormModelTests.swift b/Asterism/AsterismTests/ManualEntryFormModelTests.swiftnew file mode 100644index 00000000..8a9f5a56--- /dev/null+++ b/Asterism/AsterismTests/ManualEntryFormModelTests.swift@@ -0,0 +1,118 @@+import AsterismCore+import AsterismTestSupport+import Foundation+import Testing+@testable import Asterism++@Suite("Manual entry form drafts") @MainActor+struct ManualEntryFormModelTests {+ @Test("A successful manual save commits and publishes the mutation exactly once")+ func successfulSaveOnce() async {+ let mock = MockLibraryProvider(), work = UUID(), saved = TestFixtures.makeEntry(), tracker = CallbackTracker()+ mock.manualProjectionResult = .success(projection(work))+ mock.manualCommitResult = .success(.committed(saved))+ let model = ManualEntryFormModel(workID: work, library: mock,+ onMutation: { tracker.mutationCount += 1 })+ await model.load(); model.rating = .up+ await model.save(); await model.save()+ #expect(model.savedEntryID == saved.id && !model.canSave)+ #expect(mock.manualCommitDrafts.count == 1 && tracker.mutationCount == 1)+ }+ private func projection(_ id: UUID) -> ChapterCaptureProjection {+ ChapterCaptureResolver.project(workID: id, rawURL: "", evidence: [], entries: [], captureDefault: .ordinary)+ }+ @Test("A stale selected-content refresh requires a new choice and preserves the draft")+ func staleSelectedContent() async {+ let mock = MockLibraryProvider(), work = UUID(), selected = UUID()+ let initial = ChapterCaptureResolver.project(workID: work, rawURL: "", evidence: [], entries: [+ .init(id: selected, workID: work, target: .init(kind: .note), note: "Saved", rating: .up)+ ], captureDefault: .ordinary)+ let fresh = ChapterCaptureResolver.project(workID: work, rawURL: "", evidence: [], entries: [+ .init(id: selected, workID: work, target: .init(kind: .note), note: "Remote", rating: .down)+ ], captureDefault: .ordinary)+ mock.manualProjectionResult = .success(initial)+ mock.manualCommitResult = .success(.reviewRequired(fresh, reason: "Changed"))+ let model = ManualEntryFormModel(workID: work, library: mock, onMutation: {})+ await model.load(); model.choose(selected); model.note = "Draft"+ await model.save()+ #expect(model.note == "Draft" && model.rating == .up && model.needsContentChoice && !model.canSave)+ model.chooseContent(.destination)+ #expect(model.note == "Remote" && model.rating == .down && model.canSave)+ }++ @Test("Pristine selection switches prefill; edited and deliberately cleared drafts need a content choice")+ func switchingSelection() async {+ let mock = MockLibraryProvider(), work = UUID(), first = UUID(), second = UUID()+ mock.manualProjectionResult = .success(ChapterCaptureResolver.project(workID: work, rawURL: "", evidence: [], entries: [+ .init(id: first, workID: work, target: .init(kind: .note), note: "First", rating: .up),+ .init(id: second, workID: work, target: .init(kind: .note), note: "Second", rating: .down)+ ], captureDefault: .ordinary))+ let model = ManualEntryFormModel(workID: work, library: mock, onMutation: {})+ await model.load(); model.choose(first); model.choose(second)+ #expect(model.note == "Second" && model.rating == .down && !model.needsContentChoice)+ model.note = "Draft"; model.choose(first)+ #expect(model.note == "Draft" && model.rating == .down && model.needsContentChoice && !model.canSave)+ model.chooseContent(.source)+ #expect(model.note == "Draft" && model.canSave)+ model.note = ""; model.rating = nil; model.choose(second)+ #expect(model.note.isEmpty && model.rating == nil && model.needsContentChoice)+ model.chooseContent(.destination)+ #expect(model.note == "Second" && model.rating == .down && model.canSave)+ }++ @Test("A removed selected entry retains the draft and permits choosing a new entry")+ func staleSelectedEntry() async {+ let mock = MockLibraryProvider(), work = UUID(), selected = UUID()+ let initial = ChapterCaptureResolver.project(workID: work, rawURL: "", evidence: [],+ entries: [.init(id: selected, workID: work, target: .init(kind: .note), note: "Saved", rating: .up)],+ captureDefault: .ordinary)+ mock.manualProjectionResult = .success(initial)+ mock.manualCommitResult = .success(.reviewRequired(projection(work), reason: "Entry removed"))+ let model = ManualEntryFormModel(workID: work, library: mock, onMutation: {})+ await model.load(); model.choose(selected); model.note = "Draft"+ await model.save()+ #expect(model.choices.isEmpty && model.existingEntryID == selected && model.note == "Draft")+ model.choose(nil)+ #expect(model.existingEntryID == nil && model.note == "Draft" && model.rating == .up && model.canSave)+ }++ @Test("Opening and cancelling never writes; blank title permits a rating-only draft")+ func optionalFields() async {+ let mock = MockLibraryProvider(), id = UUID()+ mock.manualProjectionResult = .success(projection(id))+ let model = ManualEntryFormModel(workID: id, library: mock, onMutation: {})+ await model.load()+ #expect(!model.canSave && mock.manualCommitDrafts.isEmpty)+ model.rating = .up+ #expect(model.canSave)+ #expect(model.title.isEmpty && model.sourceURL.isEmpty)+ #expect(mock.manualCommitDrafts.isEmpty)+ }+ @Test("Save failure preserves the complete reader draft")+ func failedSave() async {+ let mock = MockLibraryProvider(), id = UUID()+ mock.manualProjectionResult = .success(projection(id))+ let model = ManualEntryFormModel(workID: id, library: mock, onMutation: {})+ await model.load()+ model.kind = .chapter; model.title = "Arrival"; model.designation = "012"+ model.sourceURL = "https://example.com/book"; model.note = "Keep this"; model.rating = .down+ model.confirmedNewChapter = true+ await model.save()+ #expect(model.errorMessage != nil && model.savedEntryID == nil && !model.isSaving)+ #expect(model.note == "Keep this" && model.rating == .down)+ #expect(model.title == "Arrival" && model.designation == "012" && model.confirmedNewChapter)+ #expect(mock.manualCommitDrafts.count == 1)+ }+ @Test("A stale refusal refreshes choices without replacing authored values")+ func staleSave() async {+ let mock = MockLibraryProvider(), id = UUID()+ let initial = projection(id)+ mock.manualProjectionResult = .success(initial)+ mock.manualCommitResult = .success(.reviewRequired(initial, reason: "Review again"))+ let model = ManualEntryFormModel(workID: id, library: mock, onMutation: {})+ await model.load(); model.note = "Draft"; model.title = "Optional"+ await model.save()+ #expect(model.note == "Draft" && model.title == "Optional")+ #expect(model.errorMessage == "Review again" && model.savedEntryID == nil)+ }+}
diff --git a/Asterism/AsterismTests/WorkDetailModelTests.swift b/Asterism/AsterismTests/WorkDetailModelTests.swiftindex 9a838027..564a81a0 100644--- a/Asterism/AsterismTests/WorkDetailModelTests.swift+++ b/Asterism/AsterismTests/WorkDetailModelTests.swift@@ -20,6 +20,44 @@ nonisolated func standInTypeID(_ name: String) -> UUID { @Suite("WorkDetailModel") struct WorkDetailModelTests {+ @Test("The chapter default override is staged, cancelled, and sent only on metadata Save")+ @MainActor func chapterDefaultSaveAndCancel() async {+ let (model, mock, _) = makeSUT()+ await model.load(); model.beginEditing()+ model.draftChapterCaptureDefault = .multipleChaptersPerPage+ #expect(model.hasUnsavedChanges && mock.lastUpdateWorkDraft == nil)+ model.cancelEditing()+ #expect(model.draftChapterCaptureDefault == .ordinary && mock.lastUpdateWorkDraft == nil)+ model.beginEditing(); model.draftChapterCaptureDefault = .multipleChaptersPerPage+ await model.commitEditing()+ #expect(mock.lastUpdateWorkDraft?.chapterCaptureDefault == .multipleChaptersPerPage)+ #expect(mock.lastUpdateWorkBasis?.chapterCaptureDefault == .ordinary)+ }++ @Test("Adding a first source membership preserves the metadata editor's original guard")+ @MainActor func firstMembershipPreservesMetadataBasis() async throws {+ let work = TestFixtures.makeWork(displayTitle: "Original book", memberships: [])+ let (model, mock, _) = makeSUT(work: work)+ let basis = try WorkURLBasis(workID: work.id, membershipID: nil,+ siteHostname: ExactScalarString("www.amazon.com"),+ identity: WorkIdentitySnapshot(value: nil, state: .none, ruleReference: nil),+ currentRule: nil, entries: [], priorWorkURL: nil)+ mock.projectWorkURLResult = .success(WorkURLContract(basis: basis,+ request: .clear,+ outcome: WorkURLOutcome(candidate: .unavailable(.noRelevantEntries), resultingURL: nil)))+ await model.load(); model.beginEditing()+ mock.projectWorkURLResult = .success(WorkURLContract(basis: basis,+ request: .replaceManual("https://www.amazon.com/dp/book"),+ outcome: WorkURLOutcome(candidate: .unavailable(.noRelevantEntries),+ resultingURL: "https://www.amazon.com/dp/book")))+ mock.commitWorkURLResult = .success(.committed(workID: work.id))+ model.draftTitle = "Reader's title"+ model.draftWorkURL = "https://www.amazon.com/dp/book"+ await model.commitEditing()+ #expect(mock.commitWorkURLCallCount == 1)+ #expect(mock.lastUpdateWorkBasis == WorkEditBasis(work: work).addingSiteFreeMembership(hostname: "www.amazon.com"))+ #expect(mock.lastUpdateWorkDraft?.displayTitle == "Reader's title")+ } @MainActor private func makeSUT( work: WorkSnapshot? = nil,
diff --git a/Asterism/AsterismUITests/ChapterNotesUITests.swift b/Asterism/AsterismUITests/ChapterNotesUITests.swiftnew file mode 100644index 00000000..82aefc59--- /dev/null+++ b/Asterism/AsterismUITests/ChapterNotesUITests.swift@@ -0,0 +1,72 @@+import XCTest++/// Four bounded journeys; every launch uses the test-only isolated library.+final class ChapterNotesUITests: XCTestCase {+ let app = XCUIApplication()+ override func setUp() {+ continueAfterFailure = false+ XCUIDevice.shared.orientation = .portrait+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-composed"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launch()+ waitFor(app.collectionViews["recent-list"], "Isolated library opens", timeout: 60)+ }+ override func tearDown() { terminateAndWaitForExit(app) }+ private func openWork() {+ openAllWorks(in: app)+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch, "Work is listed").tap()+ waitFor(app.buttons["work-detail-add-note"], "Work offers manual capture")+ }+ func testUntitledRatingOnlyNoteSavesWithoutASourceURL() {+ openWork()+ app.buttons["work-detail-add-note"].tap()+ let save = waitFor(app.buttons["manual-entry-save"], "Manual form opens")+ XCTAssertFalse(save.isEnabled)+ XCTAssertEqual(app.textFields["manual-entry-title"].value as? String, "Title (optional)")+ app.buttons["manual-entry-rating-up"].tap()+ XCTAssertTrue(save.isEnabled)+ save.tap()+ waitFor(app.buttons["work-detail-add-note"], "Saved note closes the sheet")+ let note = app.buttons.matching(NSPredicate(format: "identifier == 'work-detail-entry' AND label CONTAINS 'Note'")).firstMatch+ waitFor(note, "Untitled reaction is readable").tap()+ waitFor(app.anyElement("entry-detail-note-editor"), "Reaction opens")+ XCTAssertFalse(app.buttons["entry-detail-link"].exists, "No empty source link is drawn")+ }+ func testManualCancelDoesNotCreateAnEntry() {+ openWork()+ let before = app.buttons.matching(identifier: "work-detail-entry").count+ app.buttons["work-detail-add-note"].tap()+ waitFor(app.buttons["manual-entry-rating-down"], "Draft rating is available").tap()+ app.buttons["manual-entry-cancel"].tap()+ waitFor(app.buttons["work-detail-add-note"], "Cancel returns to the work")+ XCTAssertEqual(app.buttons.matching(identifier: "work-detail-entry").count, before)+ }+ func testSavedChapterCanBeCorrectedIntoAnUntitledGenericNote() {+ openWork()+ waitFor(app.anyElement("work-detail-entry"), "A chapter is listed").tap()+ waitFor(app.buttons["entry-detail-correct"], "Correction is available").tap()+ waitFor(app.anyElement("entry-correction-kind"), "Correction form opens").tap()+ app.buttons["Note"].tap()+ let title = app.textFields["entry-correction-title"]+ let prior = title.value as? String ?? ""+ title.tap(); title.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: prior.count + 2))+ app.buttons["entry-correction-save"].tap()+ waitFor(app.buttons["entry-detail-correct"], "Saved correction returns to detail")+ XCTAssertTrue(app.navigationBars["Note"].exists)+ }+ func testURLFreeWorkCanLaterReceiveAPurchaseLink() {+ openAllWorks(in: app)+ waitFor(app.buttons["works-new-work-button"], "Create work is available").tap()+ waitFor(app.textFields["new-work-title-field"], "New work opens").tap()+ app.textFields["new-work-title-field"].typeText("Paper Book")+ app.buttons["new-work-create-button"].tap()+ let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'work-row-' AND label CONTAINS 'Paper Book'")).firstMatch+ waitFor(row, "Site-free work is listed").tap()+ app.buttons["work-detail-edit-button"].tap()+ let url = waitFor(app.textFields["work-detail-url-field"], "Optional URL field opens")+ url.tap(); url.typeText("https://www.amazon.com/dp/book")+ app.buttons["work-detail-save-button"].tap()+ waitFor(app.buttons["work-detail-edit-button"], "Purchase URL saves without chapter content")+ }+}
diff --git a/Asterism/AsterismUITests/WideLayoutUITests.swift b/Asterism/AsterismUITests/WideLayoutUITests.swiftindex 4dcd1f35..a90dcde5 100644--- a/Asterism/AsterismUITests/WideLayoutUITests.swift+++ b/Asterism/AsterismUITests/WideLayoutUITests.swift@@ -54,6 +54,24 @@ final class WideLayoutUITests: XCTestCase { app.elements(withIdentifierPrefix: "recent-entry-") } + func testRatingOnlyManualNoteInTheWideWorkDetail() {+ launch("seeded-composed", orientation: .landscapeLeft)+ waitForLibrary()+ openAllWorks(in: app)+ waitFor(app.elements(withIdentifierPrefix: "work-row-").firstMatch, "A work is listed").tap()+ waitFor(app.buttons["work-detail-add-note"], "The wide work offers a manual note").tap()+ let save = waitFor(app.buttons["manual-entry-save"], "The manual sheet opens")+ XCTAssertFalse(save.isEnabled)+ waitFor(app.buttons["manual-entry-rating-up"], "A rating needs no URL or title").tap()+ XCTAssertTrue(save.isEnabled)+ save.tap()+ waitFor(app.buttons["work-detail-add-note"], "The saved sheet closes")+ let note = app.buttons.matching(NSPredicate(format: "identifier == 'work-detail-entry' AND label CONTAINS 'Note'")).firstMatch+ waitFor(note, "The wide detail lists the untitled reaction").tap()+ waitFor(app.anyElement("entry-detail-note-editor"), "The saved reaction opens")+ XCTAssertFalse(app.buttons["entry-detail-link"].exists)+ }+ // MARK: - Req 1.1, 1.3, 1.4 — the sidebar /// The three destinations, the Settings row and the toggle, and *only*
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swiftindex c11dfe03..b7e30d2b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19.swift@@ -1,7 +1,7 @@ import Foundation import SwiftData -/// The live schema. V19 adds one optional authored publication-state blob to Work.+/// Frozen V19 schema, including authored publication state. public enum AsterismSchemaV19: VersionedSchema { public static let versionIdentifier = Schema.Version(19, 0, 0) @@ -25,18 +25,3 @@ public enum AsterismV19MigrationPlan: SchemaMigrationPlan { .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- }- }-}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19Models.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19Models.swiftnew file mode 100644index 00000000..3bde2bf2--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV19Models.swift@@ -0,0 +1,296 @@+import Foundation+import SwiftData++/// Frozen V19 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 AsterismSchemaV19 {++@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 publicationStateData: Data? = nil+ public var catchUpConfirmationData: Data? = nil+ public var lastChapterOverrideData: Data? = nil+ @Attribute(.externalStorage)+ public var thumbnailData: Data?+ public var thumbnailShapeRaw: String?+ public var thumbnailDigest: String?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var genericNotesExtractionFingerprint: String?+ @Relationship(deleteRule: .nullify, inverse: \Entry.work)+ public var entries: [Entry]?+ @Relationship(deleteRule: .nullify, inverse: \Character.work)+ public var characters: [Character]?+ @Relationship(deleteRule: .nullify, inverse: \CharacterSuppression.work)+ public var characterSuppressions: [CharacterSuppression]?+ @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.work)+ public var siteMemberships: [WorkSiteMembership]? = []++ public init() {}+}++@Model+public final class Site {+ public var hostname: String = ""+ public var displayName: String = ""+ public var modeRaw: String = SiteMode.untaught.rawValue+ @Relationship(deleteRule: .cascade, inverse: \TitlePattern.site)+ public var patterns: [TitlePattern]?+ @Relationship(deleteRule: .cascade, inverse: \URLRulePattern.site)+ public var urlRules: [URLRulePattern]?+ @Relationship(deleteRule: .nullify, inverse: \Entry.site)+ var entries: [Entry]?+ @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.site)+ var workMemberships: [WorkSiteMembership]?++ public init() {}+}++@Model+public final class TitlePattern {+ public var id: UUID = UUID()+ public var version: Int = 1+ public var isActive: Bool = false+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var definitionData: Data?+ public var site: Site?++ public init() {}+}++@Model+public final class URLRulePattern {+ public var id: UUID = UUID()+ public var version: Int = 1+ public var isCurrent: Bool = false+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var originRaw: String = URLRuleOrigin.readerTaught.rawValue+ public var definitionData: Data = Data()+ public var site: Site?++ public init() {}+}++@Model+public final class WorkTypeEntity {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = WorkTypeState.active.rawValue+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class Character {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameKey: String = ""+ public var aliases: [String] = []+ public var note: String = ""+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var work: Work?++ public init() {}+}++@Model+public final class CharacterSuppression {+ public var id: UUID = UUID()+ public var work: Work?+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ public var sourceKindRaw: String?+ public var sourceEntryID: UUID?+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class WorkSiteMembership {+ public var id: UUID = UUID()+ public var hostname: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var urlIdentity: String?+ public var urlIdentityStateRaw: String = WorkURLIdentityState.none.rawValue+ public var urlIdentityRuleID: UUID?+ public var workURLString: String?+ public var workID: UUID?+ public var work: Work?+ public var site: Site?++ public init() {}+}++@Model+public final class WorkDistinctPair {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ public var recordedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class Series {+ public var id: UUID = UUID()+ public var name: String = ""+ public var notes: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class WorkLink {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ public var linkType: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class Creator {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var notes: String = ""+ public var notesModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class CreatorRole {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var position: Int = 0+ public var positionModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class WorkCredit {+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var creatorID: UUID = UUID()+ public var roleIDs: [String] = []+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class Place {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameKey: String = ""+ public var aliases: [String] = []+ public var note: String = ""+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var workID: UUID = UUID()++ public init() {}+}++@Model+public final class PlaceSuppression {+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ public var sourceKindRaw: String?+ public var sourceEntryID: UUID?+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class NoEpisodeAction {+ public var workID: UUID = UUID()+ public var key: String = ""+ public var payloadData: Data = Data()++ public init() {}+}++}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20.swiftnew file mode 100644index 00000000..0631eb82--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20.swift@@ -0,0 +1,54 @@+import Foundation+import SwiftData++/// The live schema. V20 adds authored chapter metadata, durable redirects and source associations.+public enum AsterismSchemaV20: VersionedSchema {+ public static let versionIdentifier = Schema.Version(20, 0, 0)++ public static var models: [any PersistentModel.Type] {+ [Entry.self, Work.self, Site.self, TitlePattern.self, URLRulePattern.self,+ WorkTypeEntity.self, Character.self, CharacterSuppression.self,+ WorkSiteMembership.self, WorkDistinctPair.self, Series.self, WorkLink.self,+ Creator.self, CreatorRole.self, WorkCredit.self, Place.self,+ PlaceSuppression.self, NoEpisodeAction.self, EntrySource.self]+ }+}++public enum AsterismV20MigrationPlan: SchemaMigrationPlan {+ public static var schemas: [any VersionedSchema.Type] {+ [AsterismSchemaV16.self, AsterismSchemaV17.self, AsterismSchemaV18.self, AsterismSchemaV19.self, AsterismSchemaV20.self]+ }++ public static var stages: [MigrationStage] {+ [.lightweight(fromVersion: AsterismSchemaV16.self, toVersion: AsterismSchemaV17.self),+ .lightweight(fromVersion: AsterismSchemaV17.self, toVersion: AsterismSchemaV18.self),+ .lightweight(fromVersion: AsterismSchemaV18.self, toVersion: AsterismSchemaV19.self),+ .lightweight(fromVersion: AsterismSchemaV19.self, toVersion: AsterismSchemaV20.self)]+ }+}++extension AsterismSchemaV20 {+ @Model public final class NoEpisodeAction {+ public var workID: UUID = UUID()+ public var key: String = ""+ public var payloadData: Data = Data()+ public init(workID: UUID, key: String, payloadData: Data) {+ self.workID = workID; self.key = key; self.payloadData = payloadData+ }+ }+ @Model public final class EntrySource {+ public var id: UUID = UUID()+ public var entryID: UUID = UUID()+ public var urlString: String = ""+ public var hostname: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var evidenceData: Data?+ public init(id: UUID = UUID(), entryID: UUID, urlString: String, hostname: String,+ timestamp: Date, evidenceData: Data? = nil) {+ self.id = id; self.entryID = entryID; self.urlString = urlString+ self.hostname = hostname; self.createdAt = timestamp; self.modifiedAt = timestamp+ self.evidenceData = evidenceData+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AuthoredEntryTarget.swift b/Packages/AsterismCore/Sources/AsterismCore/AuthoredEntryTarget.swiftnew file mode 100644index 00000000..b5e72087--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AuthoredEntryTarget.swift@@ -0,0 +1,108 @@+import Foundation++/// Reader choices are independent of immutable capture evidence and web rules.+public struct AuthoredEntryTarget: Codable, Equatable, Sendable {+ public enum Kind: String, Codable, CaseIterable, Sendable { case note, chapter }+ public let kind: Kind+ public let title: String?+ public let designation: String?+ public init(kind: Kind, title: String? = nil, designation: String? = nil) {+ self.kind = kind+ self.title = Self.nonblank(title)+ self.designation = kind == .chapter ? Self.nonblank(designation) : nil+ }+ public static func == (lhs: Self, rhs: Self) -> Bool {+ lhs.kind == rhs.kind && lhs.title.map(ExactScalarString.init) == rhs.title.map(ExactScalarString.init)+ && lhs.designation.map(ExactScalarString.init) == rhs.designation.map(ExactScalarString.init)+ }+ public func encoded() throws -> Data {+ try JSONBlob.encode(self)+ }+ public static func decode(_ data: Data) throws -> Self {+ let value = try JSONBlob.decode(Self.self, from: data)+ guard value.kind != .note || value.designation == nil else {+ throw ModelInvariantError.invalidCombination(field: "generic note designation")+ }+ return Self(kind: value.kind, title: value.title, designation: value.designation)+ }+ internal static func canonicalData(_ data: Data?) -> Data? {+ guard let data else { return nil }+ return (try? decode(data).encoded()) ?? data+ }+ private static func nonblank(_ value: String?) -> String? {+ guard let value else { return nil }+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed.isEmpty ? nil : trimmed+ }+}++public enum ChapterCaptureDefault: String, Codable, CaseIterable, Sendable {+ case ordinary, multipleChaptersPerPage+}++/// Values accepted by the reader when combining a loser into another entry.+/// Redirect metadata itself is deliberately excluded from the baseline.+public struct EntryMergeResolution: Codable, Equatable, Sendable {+ public let note: String+ public let ratingRaw: String?+ public let authoredTargetData: Data?+ public let workID: UUID?+ public let chapterTitle: String?+ public let intentionallyUnattached: Bool+ public init(entry: Entry) {+ note = entry.note; ratingRaw = entry.ratingRaw+ authoredTargetData = AuthoredEntryTarget.canonicalData(entry.authoredTargetData); workID = entry.work?.id+ chapterTitle = entry.citationValues.chapterTitle.kind == .manual ? entry.chapterTitle : nil+ intentionallyUnattached = entry.intentionallyUnattached+ }+ public func encoded() throws -> Data {+ try JSONBlob.encode(self)+ }+}++extension Entry {+ public var authoredTarget: AuthoredEntryTarget? {+ get { authoredTargetData.flatMap { try? AuthoredEntryTarget.decode($0) } }+ }+ public var effectiveChapterTitle: String? {+ guard authoredTargetData != nil else { return chapterTitle }+ guard let target = authoredTarget, target.kind == .chapter else { return nil }+ return target.title ?? target.designation+ }+ public var effectiveChapterSequence: String? {+ authoredTargetData == nil ? chapterSequence : authoredTarget?.designation+ }+ public var isResolvedRedirect: Bool {+ guard mergedIntoEntryID != nil, let mergeResolutionData,+ let accepted = try? JSONBlob.decode(EntryMergeResolution.self, from: mergeResolutionData) else { return false }+ guard authoredTargetData == nil || authoredTarget != nil else { return false }+ return accepted.note == note && accepted.ratingRaw == ratingRaw+ && AuthoredEntryTarget.canonicalData(accepted.authoredTargetData) == AuthoredEntryTarget.canonicalData(authoredTargetData)+ && accepted.workID == work?.id && accepted.chapterTitle == (citationValues.chapterTitle.kind == .manual ? chapterTitle : nil)+ && accepted.intentionallyUnattached == intentionallyUnattached+ }+ /// A reviewed work move may change the assignment of a clean retained+ /// loser. Do not accept any already-divergent offline content as a side+ /// effect of that administrative move.+ internal func refreshAcceptedMergeAssignment(wasResolved: Bool) {+ guard wasResolved else { return }+ if let data = try? EntryMergeResolution(entry: self).encoded() {+ mergeResolutionData = data+ }+ }++ internal func authorTarget(_ target: AuthoredEntryTarget) throws {+ authoredTargetData = try target.encoded()+ entryIdentityKey = "entry/\(id.uuidString.lowercased())"+ conservativeIdentityKey = ""+ identityBasis = .authoredUUID+ editCitations { $0.identity = .authoredEntryID(id) }+ }+}++extension Work {+ public var chapterCaptureDefault: ChapterCaptureDefault {+ get { ToleratedEnum.read(chapterCaptureDefaultRaw, default: .ordinary) }+ set { chapterCaptureDefaultRaw = newValue.rawValue }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swiftindex 501da659..128dd8b9 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveReferenceChecks.swift@@ -416,7 +416,9 @@ internal enum BackupArchiveReferenceChecks { rulesByID: [UUID: BackupV18URLRule] ) throws { let id = entry.id.uuidString- guard siteHostnames.contains(entry.hostname) else {+ let siteFree = entry.identityBasis == .authoredUUID && entry.hostname.isEmpty+ && entry.rawURL.isEmpty && entry.canonicalURL == nil+ guard siteFree || siteHostnames.contains(entry.hostname) else { throw unresolved("Entry", id, "Site \(entry.hostname)") } if let workID = entry.workID {@@ -426,14 +428,14 @@ internal enum BackupArchiveReferenceChecks { // Req 9.5 and 1.4: a Work the archive carries must hold a membership // for its Entry's hostname, or the restored library starts in the // state reconciliation exists to heal.- guard hostnamesByWork[workID]?.contains(entry.hostname) == true else {+ guard siteFree || hostnamesByWork[workID]?.contains(entry.hostname) == true else { throw unresolved( "Entry", id, "a membership of Work \(workID) on \(entry.hostname)") } } // The conservative-key alias is always the immutable raw URL (Q21).- guard entry.conservativeIdentityKey == entry.rawURL else {+ guard entry.conservativeIdentityKey == (entry.identityBasis == .authoredUUID ? "" : entry.rawURL) else { throw invalid("Entry", id, "conservative identity alias must equal the raw URL") } @@ -451,6 +453,11 @@ internal enum BackupArchiveReferenceChecks { // integer `identityKeyVersion` is a **case** now (Q26), so the switch the // check used to open on the column opens on the case instead. switch entry.identityBasis {+ case .authoredUUID:+ guard citations.identity == .authoredEntryID(entry.id),+ entry.entryIdentityKey == "entry/\(entry.id.uuidString.lowercased())" else {+ throw invalid("Entry", id, "authored identity mismatch")+ } case .conservative: guard case .rawURL = citations.identity else { throw invalid(@@ -461,7 +468,7 @@ internal enum BackupArchiveReferenceChecks { } case .urlRule: switch citations.identity {- case .rawURL:+ case .rawURL, .authoredEntryID: throw invalid("Entry", id, "URL-rule basis requires key version 2 or 3") case .rule(let url, let nameTitle): try requireSameSiteRule(url, entry: entry, rulesByID: rulesByID)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swiftindex a4144612..7694d93b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupGroupProjection.swift@@ -96,7 +96,7 @@ enum BackupGroupProjection { of: works, types: types, distinctPairs: distinctPairs) let canonicalWorkIDs = DuplicateScan.canonicalWorkIDs(workSets) let entryGroups = LibraryRepository.entryGroups(- entries, canonicalWorkIDs: canonicalWorkIDs)+ entries, canonicalWorkIDs: canonicalWorkIDs, includeResolvedRedirects: true) let workGroups = LibraryRepository.workGroups(works, types: types) let characterGroups = LibraryRepository.recordGroups(characters) let placeGroups = LibraryRepository.recordGroups(places)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportChapterRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportChapterRecords.swiftnew file mode 100644index 00000000..b7df8dc4--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImportChapterRecords.swift@@ -0,0 +1,43 @@+import Foundation+import SwiftData++extension LibraryRepository {+ internal static func applyChapterArchive(_ record: BackupV19Entry, to entry: Entry) {+ if entry.authoredTargetData != record.authoredTargetData { entry.authoredTargetData = record.authoredTargetData }+ if entry.mergedIntoEntryID != record.mergedIntoEntryID { entry.mergedIntoEntryID = record.mergedIntoEntryID }+ if entry.mergeResolutionData != record.mergeResolutionData { entry.mergeResolutionData = record.mergeResolutionData }+ }++ internal static func mergeImportedEntrySources(_ records: [BackupV19EntrySource], context: ModelContext) throws {+ var byID = Dictionary(grouping: try context.fetch(FetchDescriptor<EntrySource>()), by: \.id)+ let index = try EntrySourceIndex(context: context)+ for record in records {+ // A delayed source still names its original UUID. Ownership follows+ // the durable chain even when that archived owner clock is newer.+ let cleanDestination = index.destination(of: record.entryID, requireResolvedContent: true)+ let owner = cleanDestination.flatMap { index.hasUnresolvedContent(for: $0) ? nil : $0 } ?? record.entryID+ if let rows = byID[record.id], !rows.isEmpty {+ guard rows.allSatisfy({ ExactScalarString($0.urlString) == ExactScalarString(record.urlString) && $0.hostname == record.hostname+ && index.destination(of: $0.entryID, requireResolvedContent: true) == owner }),+ record.modifiedAt >= rows.map(\.modifiedAt).max()! else { continue }+ let incoming = try record.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ let evidence = try rows.compactMap { row in+ try row.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ } + (incoming.map { [$0] } ?? [])+ let data = evidence.isEmpty ? nil : try EntrySourceEvidence.union(evidence).encoded()+ for row in rows {+ if row.entryID != owner { row.entryID = owner }+ if row.evidenceData != data { row.evidenceData = data }+ if row.createdAt > record.createdAt { row.createdAt = record.createdAt }+ if row.modifiedAt < record.modifiedAt { row.modifiedAt = record.modifiedAt }+ }+ } else {+ let row = EntrySource(id: record.id, entryID: owner, urlString: record.urlString,+ hostname: record.hostname, timestamp: record.createdAt, evidenceData: record.evidenceData)+ row.modifiedAt = record.modifiedAt+ context.insert(row); byID[record.id] = [row]+ }+ }+ _ = try EntrySources.converge(context: context)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swiftindex e2f4fe37..67513988 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift@@ -16,6 +16,9 @@ import OSLog /// keeping them separate is what lets a future generation arrive without the /// upsert learning its envelope. public struct BackupImportPayload: Sendable, Equatable {+ public let chapterEntries: [UUID: BackupV19Entry]+ public let workCaptureDefaults: [UUID: ChapterCaptureDefault]+ public let entrySources: [BackupV19EntrySource] public let entries: [BackupV18Entry] public let works: [BackupV18Work] public let sites: [BackupV18Site]@@ -53,8 +56,14 @@ public struct BackupImportPayload: Sendable, Equatable { creators: [BackupV18Creator] = [], creatorRoles: [BackupV18CreatorRole] = [], credits: [BackupV18Credit] = [],- noEpisodeActions: [BackupV18NoEpisodeAction] = []+ noEpisodeActions: [BackupV18NoEpisodeAction] = [],+ chapterEntries: [UUID: BackupV19Entry] = [:],+ workCaptureDefaults: [UUID: ChapterCaptureDefault] = [:],+ entrySources: [BackupV19EntrySource] = [] ) {+ self.chapterEntries = chapterEntries+ self.workCaptureDefaults = workCaptureDefaults+ self.entrySources = entrySources self.entries = entries self.works = works self.sites = sites@@ -99,6 +108,19 @@ public struct BackupImportPayload: Sendable, Equatable { noEpisodeActions: payload.noEpisodeActions) } + public init(_ payload: BackupV19Payload) {+ self.init(entries: payload.entries.map(\.predecessorRecord), works: payload.works.map(\.predecessorRecord),+ sites: payload.sites, titlePatterns: payload.titlePatterns, urlRules: payload.urlRules,+ workTypes: payload.workTypes, memberships: payload.memberships, distinctPairs: payload.distinctPairs,+ characters: payload.characters, suppressions: payload.suppressions, places: payload.places,+ placeSuppressions: payload.placeSuppressions, series: payload.series, links: payload.links,+ creators: payload.creators, creatorRoles: payload.creatorRoles, credits: payload.credits,+ noEpisodeActions: payload.noEpisodeActions,+ chapterEntries: Dictionary(uniqueKeysWithValues: payload.entries.map { ($0.id, $0) }),+ workCaptureDefaults: Dictionary(uniqueKeysWithValues: payload.works.map { ($0.id, $0.chapterCaptureDefault) }),+ entrySources: payload.entrySources)+ }+ /// Whether any record carries a character-extraction coverage fingerprint. /// The 6/7 payload had a coverage array to test for emptiness; every /// generation since carries the fingerprints on the records that own them,@@ -256,7 +278,7 @@ public enum BackupImporter { /// constants, so the accepted pair moves with the generation rather than /// being restated here. private static let supportedVersions = (- format: BackupV18Document.formatVersion, schema: BackupV18Document.schemaVersion+ format: BackupV19Document.formatVersion, schema: BackupV19Document.schemaVersion ) // MARK: - Plan Dispatch (Req 5.1, 5.2, Decision 2)@@ -269,7 +291,7 @@ public enum BackupImporter { let (formatVersion, schemaVersion) = try detectVersions(data) logger.debug("Detected format=\(formatVersion) schema=\(schemaVersion)") - guard (formatVersion, schemaVersion) == supportedVersions else {+ guard (formatVersion, schemaVersion) == supportedVersions || (formatVersion, schemaVersion) == (18, 19) else { // The pair is named, always. An older archive was restorable until // its read path was retired, so a reader meeting this has done // nothing wrong and is owed the version rather than a shrug.@@ -287,23 +309,28 @@ public enum BackupImporter { } private static func planFromArchive(_ data: Data) throws -> BackupImportPlan {- let document: BackupV18Document- do {- document = try BackupV18Codec.decode(data)- } catch {- throw BackupImportError.decodingFailed(reason: String(describing: error))+ let compatible: CompatibleBackupDocument+ do { compatible = try BackupV19Codec.decodeCompatible(data) }+ catch { throw BackupImportError.decodingFailed(reason: String(describing: error)) }+ let payload: BackupImportPayload+ let metadata: BackupImportMetadata+ switch compatible {+ case .current(let document):+ payload = BackupImportPayload(document.payload)+ metadata = BackupImportMetadata(formatVersion: document.backupFormatVersion,+ schemaVersion: document.databaseSchemaVersion, appBuild: document.appBuild,+ exportedAt: document.exportedAt, capabilityGate: document.capabilityGate,+ entryCount: document.entryCount, workCount: document.workCount)+ case .predecessor(let document):+ // Keep absence distinct: importing an old archive may not reset a+ // newer work default or authored target it could not represent.+ payload = BackupImportPayload(document.payload)+ metadata = BackupImportMetadata(formatVersion: document.backupFormatVersion,+ schemaVersion: document.databaseSchemaVersion, appBuild: document.appBuild,+ exportedAt: document.exportedAt, capabilityGate: document.capabilityGate,+ entryCount: document.entryCount, workCount: document.workCount) }- let payload = BackupImportPayload(document.payload) let counts = try validate(payload)- let metadata = BackupImportMetadata(- formatVersion: document.backupFormatVersion,- schemaVersion: document.databaseSchemaVersion,- appBuild: document.appBuild,- exportedAt: document.exportedAt,- capabilityGate: document.capabilityGate,- entryCount: document.entryCount,- workCount: document.workCount- ) return BackupImportPlan( metadata: metadata, payload: payload, counts: counts) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swiftindex ef9b06cd..ff323612 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Codec.swift@@ -216,6 +216,16 @@ internal enum BackupArchiveShapeValidator { /// — the `validateEntry` `workID` pattern — so an orphan passes. internal enum BackupV18ReferenceValidator { static func validate(payload: BackupV18Payload) throws {+ for entry in payload.entries {+ if entry.identityBasis == .authoredUUID {+ throw BackupCodecError.invalidStateTuple(type: "Entry", id: entry.id.uuidString,+ reason: "18/19 cannot represent authored UUID identity")+ }+ if case .authoredEntryID = entry.citations.identity {+ throw BackupCodecError.invalidStateTuple(type: "Entry", id: entry.id.uuidString,+ reason: "18/19 cannot represent authored UUID citations")+ }+ } for work in payload.works { guard work.publicationState.map({ $0.authoredStatus == work.workStatus }) ?? true else { throw BackupCodecError.invalidStateTuple(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV19Codec.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV19Codec.swiftnew file mode 100644index 00000000..89bfd10e--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV19Codec.swift@@ -0,0 +1,317 @@+import Foundation++/// Current archive codec. The previous-generation codec stays frozen.+public enum BackupV19Codec {+ /// 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 = "V19"++ // 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 `BackupV19Document.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: BackupV19Payload,+ metadata: BackupV19Metadata+ ) throws -> Data {+ let encoder = BackupCanonicalJSON.encoder()++ let payloadData = try encoder.encode(payload)+ let checksum = BackupCanonicalJSON.sha256Hex(payloadData)++ let head = try encoder.encode(EnvelopeHead(+ appBuild: metadata.appBuild,+ backupFormatVersion: BackupV19Document.formatVersion,+ capabilityGate: Self.gate,+ checksum: checksum,+ databaseSchemaVersion: BackupV19Document.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 -> BackupV19Document {+ do {+ let rootKeys = try DuplicateJSONKeyValidator.validate(data)+ try BackupArchiveShapeValidator.validate(rootKeys: rootKeys)++ let document = try BackupCanonicalJSON.decoder()+ .decode(BackupV19Document.self, from: data)++ guard document.backupFormatVersion == BackupV19Document.formatVersion else {+ throw BackupCodecError.invalidFormatVersion(document.backupFormatVersion)+ }+ guard document.databaseSchemaVersion == BackupV19Document.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 BackupV19ReferenceValidator.validate(payload: document.payload)++ return document+ } catch let error as BackupCodecError { throw error }+ catch {+ throw BackupCodecError.decodingFailed(reason: String(describing: error))+ }+ }+}+++public typealias BackupV19Metadata = BackupV18Metadata++internal enum BackupV19ReferenceValidator {+ static func validate(payload: BackupV19Payload) throws {+ try validateChapterRecords(payload)+ 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: BackupV19Codec.label,+ reason: String(describing: error))+ }+ do {+ try BackupArchiveReferenceChecks.validate(+ entries: payload.entries.map(\.predecessorRecord),+ works: payload.works.map(\.predecessorRecord),+ 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: BackupV19Codec.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: BackupV19Codec.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: BackupV19Codec.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: BackupV19Codec.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: BackupV19Codec.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: BackupV19Codec.label,+ reason: "duplicate PlaceSuppression ID")+ }+ }+ }+}++extension BackupV19ReferenceValidator {+ private static func validateChapterRecords(_ payload: BackupV19Payload) throws {+ let entries = Dictionary(grouping: payload.entries, by: \.id)+ func invalid(_ type: String, _ id: UUID, _ reason: String) throws -> Never {+ throw BackupCodecError.invalidStateTuple(type: type, id: id.uuidString, reason: reason)+ }+ for entry in payload.entries {+ if let data = entry.authoredTargetData {+ guard (try? AuthoredEntryTarget.decode(data)) != nil,+ entry.identityBasis == .authoredUUID,+ entry.entryIdentityKey == "entry/\(entry.id.uuidString.lowercased())",+ entry.conservativeIdentityKey.isEmpty,+ entry.citations.identity == .authoredEntryID(entry.id) else {+ try invalid("Entry", entry.id, "Authored target or UUID identity needs review")+ }+ } else if entry.identityBasis == .authoredUUID {+ try invalid("Entry", entry.id, "UUID identity has no authored target")+ }+ if let destination = entry.mergedIntoEntryID {+ guard let data = entry.mergeResolutionData,+ let accepted = try? JSONBlob.decode(EntryMergeResolution.self, from: data),+ accepted.note == entry.note, accepted.ratingRaw == entry.rating?.rawValue,+ AuthoredEntryTarget.canonicalData(accepted.authoredTargetData) == AuthoredEntryTarget.canonicalData(entry.authoredTargetData),+ accepted.workID == entry.workID,+ accepted.chapterTitle == (entry.citations.chapterTitle.kind == .manual ? entry.chapterTitle : nil),+ accepted.intentionallyUnattached == entry.intentionallyUnattached else {+ try invalid("Entry", entry.id, "Changes after combine need review")+ }+ var visited: Set<UUID> = [entry.id]+ var next: UUID? = destination+ while let id = next {+ guard visited.insert(id).inserted, let group = entries[id], group.count == 1 else {+ try invalid("Entry", entry.id, "Combination target is missing, duplicated or cyclic")+ }+ next = group[0].mergedIntoEntryID+ }+ } else if entry.mergeResolutionData != nil {+ try invalid("Entry", entry.id, "Accepted combination baseline has no redirect")+ }+ }+ var sourceIDs: Set<UUID> = []+ for source in payload.entrySources {+ guard sourceIDs.insert(source.id).inserted else { try invalid("EntrySource", source.id, "Duplicate source identity") }+ guard entries[source.entryID]?.count == 1 else { try invalid("EntrySource", source.id, "Source target has not arrived") }+ guard (try? HostnameNormalizer.fromRawURL(source.urlString)) == source.hostname else {+ try invalid("EntrySource", source.id, "Source URL does not match its hostname")+ }+ if let data = source.evidenceData, (try? JSONBlob.decode(EntrySourceEvidence.self, from: data)) == nil {+ try invalid("EntrySource", source.id, "Source evidence cannot be read")+ }+ }+ }+}++public enum CompatibleBackupDocument: Sendable {+ case current(BackupV19Document)+ case predecessor(BackupV18Document)+ public var payload: BackupV19Payload {+ switch self {+ case .current(let document): document.payload+ case .predecessor(let document): .init(predecessor: document.payload)+ }+ }+}++extension BackupV19Codec {+ /// Only the immediate released predecessor is supported. Each codec checks+ /// its own checksum and exact envelope before any conversion takes place.+ public static func decodeCompatible(_ data: Data) throws -> CompatibleBackupDocument {+ struct Versions: Decodable { let backupFormatVersion: Int; let databaseSchemaVersion: Int }+ let versions = try BackupCanonicalJSON.decoder().decode(Versions.self, from: data)+ switch (versions.backupFormatVersion, versions.databaseSchemaVersion) {+ case (19, 20): return .current(try decode(data))+ case (18, 19): return .predecessor(try BackupV18Codec.decode(data))+ default: throw BackupCodecError.invalidFormatVersion(versions.backupFormatVersion)+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV19Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV19Exporter.swiftnew file mode 100644index 00000000..27f5fc18--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV19Exporter.swift@@ -0,0 +1,150 @@+import Foundation+import SwiftData++public protocol BackupV19SnapshotProviding: Sendable {+ func backupV19Snapshot() async throws -> BackupV19Payload+}++extension LibraryRepository: BackupV19SnapshotProviding {+ public func backupV19Snapshot() async throws -> BackupV19Payload {+ let outcome: Result<BackupV19Payload, BackupV18ExportError> =+ try await withLockedBackupContext { context in+ do {+ let predecessor = try Self.projectV18Payload(context: context)+ let entryRows = try context.fetch(FetchDescriptor<Entry>())+ let groups = Self.entryGroups(entryRows,+ canonicalWorkIDs: try Self.canonicalWorkIDs(normalising: entryRows, context: context),+ includeResolvedRedirects: true)+ let workRows = try context.fetch(FetchDescriptor<Work>())+ for row in workRows where ChapterCaptureDefault(rawValue: row.chapterCaptureDefaultRaw) == nil {+ throw BackupV18ExportError.unrepresentableValue(record: "Work \(row.id)",+ field: "chapterCaptureDefault", value: row.chapterCaptureDefaultRaw)+ }+ let works = Self.workGroups(workRows, types: try Self.workTypeDirectory(context: context))+ let sources = try context.fetch(FetchDescriptor<EntrySource>())+ let bySourceID = Dictionary(grouping: sources, by: \.id)+ let index = try EntrySourceIndex(context: context)+ let sourceCopies = try bySourceID.keys.sorted { $0.uuidString < $1.uuidString }.map { id in+ let rows = bySourceID[id]!+ guard Set(rows.compactMap { index.destination(of: $0.entryID) }).count == 1,+ rows.allSatisfy({ index.destination(of: $0.entryID) != nil }), Set(rows.map { ExactScalarString($0.urlString) }).count == 1,+ Set(rows.map(\.hostname)).count == 1 else {+ throw BackupV18ExportError.unrepresentableValue(record: "EntrySource \(id)", field: "ownership", value: "differing copies")+ }+ let evidence = try rows.compactMap { row in+ try row.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ }+ let first = rows[0]+ return BackupV19EntrySource(id: id, entryID: index.destination(of: first.entryID)!, urlString: first.urlString,+ hostname: first.hostname, createdAt: rows.map(\.createdAt).min()!,+ modifiedAt: rows.map(\.modifiedAt).max()!,+ evidenceData: evidence.isEmpty ? nil : try EntrySourceEvidence.union(evidence).encoded())+ }+ let pairs = Dictionary(grouping: sourceCopies) {+ ExactScalarString("\($0.entryID.uuidString)/\($0.urlString)")+ }+ let sourceRecords = try pairs.values.map { copies in+ let winner = copies.min { $0.id.uuidString < $1.id.uuidString }!+ let evidence = try copies.compactMap { copy in+ try copy.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ }+ return BackupV19EntrySource(id: winner.id, entryID: winner.entryID, urlString: winner.urlString,+ hostname: winner.hostname, createdAt: copies.map(\.createdAt).min()!,+ modifiedAt: copies.map(\.modifiedAt).max()!,+ evidenceData: evidence.isEmpty ? nil : try EntrySourceEvidence.union(evidence).encoded())+ }.sorted { $0.id.uuidString < $1.id.uuidString }+ let payload = BackupV19Payload(entries: predecessor.entries.map { record in+ let carrier = groups[record.id]!.carrier+ return BackupV19Entry(predecessor: record, authoredTargetData: carrier.authoredTargetData,+ mergedIntoEntryID: carrier.mergedIntoEntryID, mergeResolutionData: carrier.mergeResolutionData)+ }, works: predecessor.works.map { record in+ BackupV19Work(predecessor: record, chapterCaptureDefault: works[record.id]!.carrier.chapterCaptureDefault)+ }, sites: predecessor.sites, titlePatterns: predecessor.titlePatterns, urlRules: predecessor.urlRules,+ workTypes: predecessor.workTypes, memberships: predecessor.memberships,+ distinctPairs: predecessor.distinctPairs, characters: predecessor.characters,+ suppressions: predecessor.suppressions, places: predecessor.places,+ placeSuppressions: predecessor.placeSuppressions, series: predecessor.series,+ links: predecessor.links, creators: predecessor.creators, creatorRoles: predecessor.creatorRoles,+ credits: predecessor.credits, noEpisodeActions: predecessor.noEpisodeActions, entrySources: sourceRecords)+ try BackupV19ReferenceValidator.validate(payload: payload)+ return .success(payload)+ } catch let error as BackupV18ExportError {+ return .failure(error)+ }+ }+ return try outcome.get()+ }+}++public final class BackupV19Exporter: Sendable {+ private let repository: any BackupV19SnapshotProviding+ private let stagingDirectory: URL++ public init(+ repository: any BackupV19SnapshotProviding,+ stagingDirectory: URL+ ) {+ self.repository = repository+ self.stagingDirectory = stagingDirectory+ }++ public func export(metadata: BackupV19Metadata) async throws -> BackupExportResult {+ let payload: BackupV19Payload+ do {+ payload = try await repository.backupV19Snapshot()+ } catch let error as BackupV18ExportError {+ throw error+ } catch {+ throw BackupV18ExportError.snapshotFailed(reason: String(describing: error))+ }++ let encoded: Data+ do {+ encoded = try BackupV19Codec.encode(payload: payload, metadata: metadata)+ } catch {+ throw BackupV18ExportError.encodingFailed(reason: String(describing: error))+ }++ do {+ let decoded = try BackupV19Codec.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\(BackupV19Document.formatVersion)",+ exportedAt: metadata.exportedAt))+ do {+ try ExportStaging.write(encoded, to: fileURL)+ } catch {+ throw BackupV18ExportError.stagingFailed(reason: String(describing: error))+ }+ return BackupExportResult(fileURL: fileURL)+ } catch let error as BackupV18ExportError {+ throw error+ } catch {+ throw BackupV18ExportError.stagingFailed(+ reason: "preparing staging directory failed: \(error)")+ }+ }++ public func cleanup(_ result: BackupExportResult) {+ try? FileManager.default.removeItem(at: result.fileURL)+ }++ /// Removes abandoned backup files older than 24 hours from the staging area,+ /// which still covers the files a previous build staged at an earlier+ /// generation.+ public func scavengeStaleFiles() {+ ExportStaging.scavengeBackups(in: stagingDirectory)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV19Types.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV19Types.swiftnew file mode 100644index 00000000..37f2683e--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV19Types.swift@@ -0,0 +1,529 @@+import Foundation++// Archive 19/20 adds authored targets, durable combinations and independent sources.+// The released 18/19 wire types and codec remain unchanged.++public struct BackupV19Document: Codable, Equatable, Sendable {+ public static let formatVersion = 19+ public static let schemaVersion = 20++ 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: BackupV19Payload++ public init(+ appBuild: String,+ exportedAt: Date,+ capabilityGate: String,+ entryCount: Int,+ workCount: Int,+ checksum: String,+ payload: BackupV19Payload+ ) {+ backupFormatVersion = Self.formatVersion+ databaseSchemaVersion = Self.schemaVersion+ self.appBuild = appBuild+ self.exportedAt = exportedAt+ self.capabilityGate = capabilityGate+ self.entryCount = entryCount+ self.workCount = workCount+ self.checksum = checksum+ self.payload = payload+ }+}++public struct BackupV19Payload: Codable, Equatable, Sendable {+ public let entrySources: [BackupV19EntrySource]+ public let entries: [BackupV19Entry]+ public let works: [BackupV19Work]+ 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: [BackupV19Entry],+ works: [BackupV19Work],+ 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] = [],+ entrySources: [BackupV19EntrySource] = []+ ) {+ self.entrySources = entrySources+ 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 BackupV19Work: Codable, Equatable, Sendable {+ public let chapterCaptureDefault: ChapterCaptureDefault+ 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 `BackupV19WorkType`, 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,+ chapterCaptureDefault: ChapterCaptureDefault = .ordinary+ ) {+ self.chapterCaptureDefault = chapterCaptureDefault+ 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+ }+}++public struct BackupV19Entry: Codable, Equatable, Sendable {+ public let authoredTargetData: Data?+ public let mergedIntoEntryID: UUID?+ public let mergeResolutionData: Data?+ 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,+ authoredTargetData: Data? = nil, mergedIntoEntryID: UUID? = nil, mergeResolutionData: Data? = nil+ ) {+ self.authoredTargetData = authoredTargetData+ self.mergedIntoEntryID = mergedIntoEntryID+ self.mergeResolutionData = mergeResolutionData+ 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+ }+}++extension BackupV19Work {+ public init(predecessor: BackupV18Work, chapterCaptureDefault: ChapterCaptureDefault = .ordinary) {+ self.init(id: predecessor.id,+ displayTitle: predecessor.displayTitle,+ lastParsedTitle: predecessor.lastParsedTitle,+ genericNotes: predecessor.genericNotes,+ genreTags: predecessor.genreTags,+ titleProvenance: predecessor.titleProvenance,+ workStatus: predecessor.workStatus,+ readingStatus: predecessor.readingStatus,+ verdict: predecessor.verdict,+ releaseDays: predecessor.releaseDays,+ workTypeID: predecessor.workTypeID,+ typeName: predecessor.typeName,+ createdAt: predecessor.createdAt,+ modifiedAt: predecessor.modifiedAt,+ genericNotesExtractionFingerprint: predecessor.genericNotesExtractionFingerprint,+ seriesID: predecessor.seriesID,+ seriesPosition: predecessor.seriesPosition,+ thumbnailShape: predecessor.thumbnailShape,+ thumbnail: predecessor.thumbnail,+ latestReleasedChapter: predecessor.latestReleasedChapter,+ latestConfirmedAt: predecessor.latestConfirmedAt,+ countsUpOnReleaseDays: predecessor.countsUpOnReleaseDays,+ latestIsEstimate: predecessor.latestIsEstimate,+ lastChapterOverride: predecessor.lastChapterOverride,+ lastChapterOverrideAt: predecessor.lastChapterOverrideAt,+ publicationState: predecessor.publicationState,+ chapterCaptureDefault: chapterCaptureDefault)+ }+ internal var predecessorRecord: BackupV18Work {+ .init(id: id,+ displayTitle: displayTitle,+ lastParsedTitle: lastParsedTitle,+ genericNotes: genericNotes,+ genreTags: genreTags,+ titleProvenance: titleProvenance,+ workStatus: workStatus,+ readingStatus: readingStatus,+ verdict: verdict,+ releaseDays: releaseDays,+ workTypeID: workTypeID,+ typeName: typeName,+ createdAt: createdAt,+ modifiedAt: modifiedAt,+ genericNotesExtractionFingerprint: genericNotesExtractionFingerprint,+ seriesID: seriesID,+ seriesPosition: seriesPosition,+ thumbnailShape: thumbnailShape,+ thumbnail: thumbnail,+ latestReleasedChapter: latestReleasedChapter,+ latestConfirmedAt: latestConfirmedAt,+ countsUpOnReleaseDays: countsUpOnReleaseDays,+ latestIsEstimate: latestIsEstimate,+ lastChapterOverride: lastChapterOverride,+ lastChapterOverrideAt: lastChapterOverrideAt,+ publicationState: publicationState)+ }+}++extension BackupV19Entry {+ public init(predecessor: BackupV18Entry, authoredTargetData: Data? = nil, mergedIntoEntryID: UUID? = nil, mergeResolutionData: Data? = nil) {+ self.init(id: predecessor.id,+ captureTitle: predecessor.captureTitle,+ captureTitleSource: predecessor.captureTitleSource,+ rawURL: predecessor.rawURL,+ canonicalURL: predecessor.canonicalURL,+ hostname: predecessor.hostname,+ entryIdentityKey: predecessor.entryIdentityKey,+ conservativeIdentityKey: predecessor.conservativeIdentityKey,+ identityBasis: predecessor.identityBasis,+ urlWorkIdentity: predecessor.urlWorkIdentity,+ chapterSequence: predecessor.chapterSequence,+ chapterTitle: predecessor.chapterTitle,+ note: predecessor.note,+ rating: predecessor.rating,+ firstCapturedAt: predecessor.firstCapturedAt,+ lastSharedAt: predecessor.lastSharedAt,+ modifiedAt: predecessor.modifiedAt,+ workID: predecessor.workID,+ intentionallyUnattached: predecessor.intentionallyUnattached,+ citations: predecessor.citations,+ characterExtractionFingerprint: predecessor.characterExtractionFingerprint,+ authoredTargetData: authoredTargetData, mergedIntoEntryID: mergedIntoEntryID, mergeResolutionData: mergeResolutionData)+ }+ internal var predecessorRecord: BackupV18Entry {+ .init(id: id,+ captureTitle: captureTitle,+ captureTitleSource: captureTitleSource,+ rawURL: rawURL,+ canonicalURL: canonicalURL,+ hostname: hostname,+ entryIdentityKey: entryIdentityKey,+ conservativeIdentityKey: conservativeIdentityKey,+ identityBasis: identityBasis,+ urlWorkIdentity: urlWorkIdentity,+ chapterSequence: chapterSequence,+ chapterTitle: chapterTitle,+ note: note,+ rating: rating,+ firstCapturedAt: firstCapturedAt,+ lastSharedAt: lastSharedAt,+ modifiedAt: modifiedAt,+ workID: workID,+ intentionallyUnattached: intentionallyUnattached,+ citations: citations,+ characterExtractionFingerprint: characterExtractionFingerprint)+ }+}++extension BackupV19Payload {+ public init(predecessor: BackupV18Payload) {+ self.init(entries: predecessor.entries.map { BackupV19Entry(predecessor: $0) },+ works: predecessor.works.map { BackupV19Work(predecessor: $0) },+ sites: predecessor.sites,+ titlePatterns: predecessor.titlePatterns,+ urlRules: predecessor.urlRules,+ workTypes: predecessor.workTypes,+ memberships: predecessor.memberships,+ distinctPairs: predecessor.distinctPairs,+ characters: predecessor.characters,+ suppressions: predecessor.suppressions,+ places: predecessor.places,+ placeSuppressions: predecessor.placeSuppressions,+ series: predecessor.series,+ links: predecessor.links,+ creators: predecessor.creators,+ creatorRoles: predecessor.creatorRoles,+ credits: predecessor.credits,+ noEpisodeActions: predecessor.noEpisodeActions)+ }+}++public struct BackupV19EntrySource: Codable, Equatable, Sendable {+ public let id: UUID+ public let entryID: UUID+ public let urlString: String+ public let hostname: String+ public let createdAt: Date+ public let modifiedAt: Date+ public let evidenceData: Data?+ public init(id: UUID, entryID: UUID, urlString: String, hostname: String,+ createdAt: Date, modifiedAt: Date, evidenceData: Data? = nil) {+ self.id = id; self.entryID = entryID; self.urlString = urlString; self.hostname = hostname+ self.createdAt = createdAt; self.modifiedAt = modifiedAt; self.evidenceData = evidenceData+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CaptureViewModel.swift b/Packages/AsterismCore/Sources/AsterismCore/CaptureViewModel.swiftindex 1d0eab32..031c766e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/CaptureViewModel.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/CaptureViewModel.swift@@ -118,7 +118,34 @@ internal struct WorkContextKey: Sendable, Equatable { @MainActor public final class CaptureViewModel { public private(set) var state: CaptureViewState = .loading+ public private(set) var chapterIntent: ChapterCaptureIntent = .automatic+ public var chapterProjection: ChapterCaptureProjection? { currentContract?.request.chapterProjection }+ public func chooseChapterIntent(_ intent: ChapterCaptureIntent) {+ guard let contract = currentContract else { return }+ chapterIntent = intent+ if case .existing(let id, let contentChoice) = intent,+ let selected = chapterProjection?.entries.first(where: { $0.id == id }),+ contentChoice == .destination || contentChoice == nil && !hasEditedAuthoredContent {+ note = selected.note; rating = selected.rating+ if let prep = preparation {+ let draft = buildDraft(preparation: prep)+ switch state {+ case .ready(_, _, let outcome, let message):+ state = .ready(preparation: prep, draft: draft, outcome: outcome, reviewMessage: message)+ case .saveFailed(_, _, let outcome, let message):+ state = .saveFailed(preparation: prep, draft: draft, outcome: outcome, message: message)+ default: break+ }+ }+ }+ let request = currentDraft.map { captureRequest(for: $0) }+ ?? contract.request.withChapterProjection(contract.request.chapterProjection, intent: intent)+ currentContract = CaptureContract(basis: contract.basis,+ request: request, outcome: contract.outcome)+ }+ private var preparation: CapturePreparation?+ private var hasEditedAuthoredContent = false private var note: String = "" private var rating: Rating? private var manualTitle: String = ""@@ -185,7 +212,13 @@ public final class CaptureViewModel { public var canSave: Bool { switch state { case .ready(_, let draft, let outcome, _), .saveFailed(_, let draft, let outcome, _):- return !draft.captureTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ let needsChoice: Bool+ switch chapterProjection?.resolution {+ case .chooseChapter, .newChapter(requiresConfirmation: true): needsChoice = chapterIntent == .automatic+ default: needsChoice = false+ }+ return !needsChoice && chapterProjection?.needsContentChoice(intent: chapterIntent, note: draft.note, rating: draft.rating) != true+ && !draft.captureTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && outcome != nil && currentContract?.request == captureRequest(for: draft) && projectionGeneration == generation@@ -247,7 +280,7 @@ public final class CaptureViewModel { rating: draft.rating ) guard gen == generation else { return }- currentContract = contract+ currentContract = CaptureContract(basis: contract.basis, request: contract.request.withChapterProjection(contract.request.chapterProjection, intent: chapterIntent), outcome: contract.outcome) projectionGeneration = gen state = .ready(preparation: prep, draft: draft, outcome: contract.outcome, reviewMessage: nil) } catch {@@ -270,17 +303,21 @@ public final class CaptureViewModel { /// Update note and trigger reprojection. public func setNote(_ value: String, coordinator: any CaptureCoordinating) async {+ hasEditedAuthoredContent = true note = value+ if refreshAuthoredContentOnly() { return } await reprojectIfNeeded(coordinator: coordinator) } /// Toggle rating: same value clears, different value replaces. public func setRating(_ value: Rating?, coordinator: any CaptureCoordinating) async {+ hasEditedAuthoredContent = true if let value = value, rating == value { rating = nil } else { rating = value }+ if refreshAuthoredContentOnly() { return } await reprojectIfNeeded(coordinator: coordinator) } @@ -476,6 +513,26 @@ public final class CaptureViewModel { // MARK: - Private + /// Note/rating edits cannot change chapter identity. Reuse the immutable+ /// reviewed basis; Save still reprojects the authoritative store under lock.+ private func refreshAuthoredContentOnly() -> Bool {+ guard let prep = preparation, let contract = currentContract,+ contract.request.chapterProjection != nil,+ projectionGeneration == generation else { return false }+ switch state { case .ready, .saveFailed: break; default: return false }+ generation += 1; projectionGeneration = generation+ let draft = buildDraft(preparation: prep)+ let request = captureRequest(for: draft)+ let outcome = contract.outcome+ currentContract = .init(basis: contract.basis, request: request, outcome: outcome)+ switch state {+ case .ready(_, _, _, let message): state = .ready(preparation: prep, draft: draft, outcome: outcome, reviewMessage: message)+ case .saveFailed(_, _, _, let message): state = .saveFailed(preparation: prep, draft: draft, outcome: outcome, message: message)+ default: break+ }+ return true+ }+ /// Rebuild the draft from current fields and reprojects if title is nonblank. private func reprojectIfNeeded(coordinator: any CaptureCoordinating) async { guard let prep = preparation else { return }@@ -523,7 +580,7 @@ public final class CaptureViewModel { ) // Generation guard: older projection must never overwrite newer guard gen == generation else { return }- currentContract = contract+ currentContract = CaptureContract(basis: contract.basis, request: contract.request.withChapterProjection(contract.request.chapterProjection, intent: chapterIntent), outcome: contract.outcome) projectionGeneration = gen // Refresh state with new outcome switch state {@@ -550,7 +607,12 @@ public final class CaptureViewModel { rawURLString: draft.rawURLString, canonicalURLString: draft.canonicalURLString, note: draft.note,- rating: draft.rating+ rating: draft.rating,+ raceGuardKeys: currentContract?.request.raceGuardKeys,+ entryID: currentContract?.request.entryID,+ capturedAt: currentContract?.request.capturedAt,+ chapterProjection: currentContract?.request.chapterProjection,+ chapterIntent: chapterIntent ) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift b/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swiftindex 0bf2b870..8222e54f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/CatchUpProgress.swift@@ -13,6 +13,7 @@ public struct NumberedNote: Equatable, Sendable { public static func from(_ entries: [EntrySnapshot]) -> [NumberedNote] { entries.compactMap { entry in+ guard entry.authoredTarget?.kind != .note, !entry.changesAfterCombine else { return nil } guard let number = ChapterNumber.whole( chapterSequence: entry.chapterSequence, chapterTitle: entry.chapterTitle)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ChapterCaptureResolver.swift b/Packages/AsterismCore/Sources/AsterismCore/ChapterCaptureResolver.swiftnew file mode 100644index 00000000..907215ea--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/ChapterCaptureResolver.swift@@ -0,0 +1,118 @@+import Foundation++/// A specific key retains its taught namespace. A URL association by itself is+/// never a chapter identity, and scalar designation spelling is not rewritten.+public struct ChapterCaptureEvidence: Equatable, Hashable, Sendable {+ public let binding: EntrySourceEvidence.Binding+ public let chapterFact: ExactScalarString?+ public init(origin: EntrySourceEvidence.Binding.Origin, key: String, ruleID: UUID?, chapterFact: String? = nil) {+ binding = .init(origin: origin, key: key, ruleID: ruleID)+ self.chapterFact = chapterFact.map(ExactScalarString.init)+ }+}++public struct ChapterCaptureEntry: Equatable, Sendable {+ public let id: UUID+ public let displayLabel: String+ public let workID: UUID?+ public let target: AuthoredEntryTarget?+ public let bindings: Set<EntrySourceEvidence.Binding>+ public let sourceURLs: Set<ExactScalarString>+ public let requiresReview: Bool+ public let note: String+ public let rating: Rating?+ public let modifiedAt: Date+ public let authoredContent: EntryAuthoredContent?+ public init(id: UUID, workID: UUID?, target: AuthoredEntryTarget? = nil,+ bindings: Set<EntrySourceEvidence.Binding> = [], sourceURLs: [String] = [],+ requiresReview: Bool = false, note: String = "", rating: Rating? = nil,+ modifiedAt: Date = Date(timeIntervalSince1970: 0), authoredContent: EntryAuthoredContent? = nil,+ displayLabel: String = "") {+ self.displayLabel = displayLabel+ self.id = id; self.workID = workID; self.target = target+ self.bindings = bindings; self.sourceURLs = Set(sourceURLs.map(ExactScalarString.init)); self.requiresReview = requiresReview+ self.note = note; self.rating = rating; self.modifiedAt = modifiedAt+ self.authoredContent = authoredContent+ }+}++public enum ChapterCaptureResolution: Equatable, Sendable {+ case update(entryID: UUID)+ case newEntry+ case newChapter(requiresConfirmation: Bool)+ case chooseChapter(entryIDs: [UUID], reason: String)+}++public struct ChapterCaptureProjection: Equatable, Sendable {+ public let workID: UUID?+ public let rawURL: String+ public var captureTitle: String? = nil+ public let evidence: [ChapterCaptureEvidence]+ public let entries: [ChapterCaptureEntry]+ public let resolution: ChapterCaptureResolution+ public let offersAnotherChapter: Bool+ public var workContent: WorkAuthoredContent? = nil+ public var workModifiedAt: Date? = nil+ public var ruleBasis: CaptureBasis? = nil+ public var captureDefault: ChapterCaptureDefault = .ordinary+}++/// Read-only decision logic shared by projection and the commit recheck. This+/// operates on immutable values, with no confidence scoring or placement keys.+public enum ChapterCaptureResolver {+ public static func project(workID: UUID?, rawURL: String,+ evidence: [ChapterCaptureEvidence], entries: [ChapterCaptureEntry],+ captureDefault: ChapterCaptureDefault) -> ChapterCaptureProjection {+ let scoped = entries.filter { $0.workID == workID }.sorted { $0.id.uuidString < $1.id.uuidString }+ let specific = Set(evidence.map(\.binding))+ let chapters = scoped.filter { $0.target?.kind != .note }+ let sourceMatches = scoped.filter { $0.sourceURLs.contains(ExactScalarString(rawURL)) }+ let resolution: ChapterCaptureResolution+ if !specific.isEmpty {+ let matchedEvidence = specific.map { binding in+ (binding: binding, ids: Set(chapters.filter { $0.bindings.contains(binding) }.map(\.id)))+ }+ let matchedByEvidence = matchedEvidence.map(\.ids)+ let sequenceFacts = Set(evidence.filter { $0.binding.origin != .designation }.compactMap(\.chapterFact))+ let namespaces = Dictionary(grouping: evidence) {+ "\($0.binding.origin.rawValue)/\($0.binding.ruleID?.uuidString ?? "")"+ }+ let contradictory = sequenceFacts.count > 1+ || namespaces.values.contains { Set($0.map { ExactScalarString($0.binding.key) }).count > 1 }+ let matches = matchedByEvidence.reduce(into: Set<UUID>()) { $0.formUnion($1) }+ if contradictory {+ resolution = .chooseChapter(entryIDs: chapters.map(\.id), reason: "The chapter evidence disagrees")+ } else if matches.count == 1, let id = matches.first,+ let entry = scoped.first(where: { $0.id == id }), !entry.requiresReview,+ matchedEvidence.allSatisfy({+ $0.ids == [id] || $0.binding.origin == .designation && $0.ids.isEmpty+ }) {+ resolution = .update(entryID: id)+ } else if !matches.isEmpty {+ resolution = .chooseChapter(entryIDs: Array(matches).sorted { $0.uuidString < $1.uuidString },+ reason: "The chapter evidence needs review")+ } else {+ // A zero key match does not prove novelty across layouts. A+ // chapter without a comparable namespace needs reader selection.+ let incomparable = chapters.contains { entry in+ entry.requiresReview || !entry.bindings.contains { binding in+ specific.contains { $0.origin == binding.origin && $0.ruleID == binding.ruleID }+ }+ }+ resolution = incomparable+ ? .chooseChapter(entryIDs: chapters.map(\.id), reason: "Choose an existing chapter or confirm a new one")+ : .newChapter(requiresConfirmation: false)+ }+ } else if captureDefault == .multipleChaptersPerPage {+ resolution = .newChapter(requiresConfirmation: !chapters.isEmpty)+ } else if sourceMatches.count == 1, let matched = sourceMatches.first, !matched.requiresReview {+ resolution = .update(entryID: matched.id)+ } else if !sourceMatches.isEmpty {+ resolution = .chooseChapter(entryIDs: sourceMatches.map(\.id), reason: "This page is linked to more than one chapter or needs review")+ } else {+ resolution = .newEntry+ }+ return ChapterCaptureProjection(workID: workID, rawURL: rawURL, evidence: evidence, entries: scoped,+ resolution: resolution, offersAnotherChapter: specific.isEmpty, captureDefault: captureDefault)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DomainEnums.swift b/Packages/AsterismCore/Sources/AsterismCore/DomainEnums.swiftindex 9be8e8e7..8e862d97 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DomainEnums.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DomainEnums.swift@@ -233,6 +233,7 @@ public enum URLTemplateFieldOrder: String, CaseIterable, Codable, Sendable { public enum EntryIdentityBasis: String, CaseIterable, Codable, Sendable { case conservative case urlRule+ case authoredUUID } public enum WorkURLIdentityState: String, CaseIterable, Codable, Sendable {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swiftindex f15373e4..0d7d784c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift@@ -641,7 +641,9 @@ enum DuplicateReconciler { var moved = 0 for loser in losers { for entry in loser.entryValues where entry.work !== target {+ let wasResolved = entry.isResolvedRedirect entry.work = target+ entry.refreshAcceptedMergeAssignment(wasResolved: wasResolved) moved += 1 } }@@ -1312,8 +1314,16 @@ enum DuplicateReconciler { rows: placeRows.rows(of: works), suppressions: placeRows.suppressions(of: works), survivors: survivors, timestamp: stamp)+ let sourceRows = try context.fetch(FetchDescriptor<EntrySource>())+ let retainRedirects = touched.contains { $0.authoredTargetData != nil }+ || sourceRows.contains { plan.key.memberIDs.contains($0.entryID) } for id in plan.loserIDs {- doomedEntries += rows.entries[id] ?? []+ if retainRedirects, let losing = rows.entries[id],+ let group = LibraryRepository.entryGroup(id: id, rows: losing, canonicalWorkIDs: canonicalWorkIDs) {+ try EntrySources.combine(loser: group, survivorID: plan.survivorID, timestamp: stamp, context: context)+ } else {+ doomedEntries += rows.entries[id] ?? []+ } } let survivingEntries = rows.entries[plan.survivorID] ?? [] try NoEpisodeWriter.recordNoteTransition(@@ -1519,6 +1529,8 @@ enum DuplicateReconciler { // too even though nothing verifies them. Only after a rollback: the // whole-table read is the price of the repair, not of the pass. if !workIDs.isEmpty { _ = try context.fetch(FetchDescriptor<Entry>()) }+ // Retained entry combinations also transfer source ownership.+ _ = try context.fetch(FetchDescriptor<EntrySource>()) } private mutating func reload(context: ModelContext) throws {@@ -1669,6 +1681,30 @@ enum DuplicateReconciler { row.note = carrier.note changed = true }+ if row.authoredTargetData != carrier.authoredTargetData {+ row.authoredTargetData = carrier.authoredTargetData; changed = true+ }+ // An explicit target and its UUID identity are one authored write.+ // A bare same-UUID copy must not inherit only the target blob while+ // retaining an automatic URL identity that can collapse chapters.+ if carrier.authoredTargetData != nil {+ if row.entryIdentityKey != carrier.entryIdentityKey {+ row.entryIdentityKey = carrier.entryIdentityKey; changed = true+ }+ if row.conservativeIdentityKey != carrier.conservativeIdentityKey {+ row.conservativeIdentityKey = carrier.conservativeIdentityKey; changed = true+ }+ if row.identityBasis != carrier.identityBasis {+ row.identityBasis = carrier.identityBasis; changed = true+ }+ if row.editCitations({ $0.identity = carrier.citationValues.identity }) { changed = true }+ }+ if row.mergedIntoEntryID != carrier.mergedIntoEntryID {+ row.mergedIntoEntryID = carrier.mergedIntoEntryID; changed = true+ }+ if row.mergeResolutionData != carrier.mergeResolutionData {+ row.mergeResolutionData = carrier.mergeResolutionData; changed = true+ } if row.rating != carrier.rating { row.rating = carrier.rating changed = true@@ -1782,6 +1818,9 @@ enum DuplicateReconciler { return (membership.hostname, url) } for row in rows where row !== carrier {+ if row.chapterCaptureDefaultRaw != carrier.chapterCaptureDefaultRaw {+ row.chapterCaptureDefaultRaw = carrier.chapterCaptureDefaultRaw; changed = true+ } if row.genericNotes != carrier.genericNotes { row.genericNotes = carrier.genericNotes changed = true
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateScan.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateScan.swiftindex 8bbe17ab..69036163 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateScan.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateScan.swift@@ -255,8 +255,9 @@ public enum DuplicateScan { let entryComponents = try candidateComponents( FetchDescriptor<Entry>(), context: context, id: \.id, bucketKey: {- entryBucketKey(- hostname: $0.hostname, conservativeIdentityKey: $0.conservativeIdentityKey)+ $0.authoredTargetData == nil && $0.mergedIntoEntryID == nil+ ? entryBucketKey(hostname: $0.hostname, conservativeIdentityKey: $0.conservativeIdentityKey)+ : nil }) // V8: a Work's duplicate relation is one key per membership (Req 5.1), // so the first walk reads the membership table — by `workID`, never@@ -401,8 +402,9 @@ public enum DuplicateScan { let candidates = candidateComponents( ids: entries.map(\.id), bucketKeys: entries.map {- entryBucketKey(- hostname: $0.hostname, conservativeIdentityKey: $0.conservativeIdentityKey)+ $0.authoredTargetData == nil && $0.mergedIntoEntryID == nil+ ? entryBucketKey(hostname: $0.hostname, conservativeIdentityKey: $0.conservativeIdentityKey)+ : nil }) guard !candidates.candidates.isEmpty else { return [] } let rows = entries.filter { candidates.candidates.contains($0.id) }.map(EntryRow.init)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift b/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swiftindex 2d9bced4..f4003d05 100644--- a/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift@@ -46,6 +46,7 @@ public struct EntryCitations: Codable, Equatable, Sendable { /// The conservative basis: the key is the raw URL, and nothing is cited. /// Stored as `identityKeyVersion == 1`. case rawURL+ case authoredEntryID(UUID) /// The identity+sequence (v2) basis. case rule(url: CitedRule, nameTitle: CitedRule?) /// The sequence+name (v3) basis, whose name contributor is a title rule.@@ -56,6 +57,7 @@ public struct EntryCitations: Codable, Equatable, Sendable { public var keyVersion: Int { switch self { case .rawURL: 1+ case .authoredEntryID: 0 case .rule: 2 case .composed: 3 }@@ -63,14 +65,14 @@ public struct EntryCitations: Codable, Equatable, Sendable { var urlRule: CitedRule? { switch self {- case .rawURL: nil+ case .rawURL, .authoredEntryID: nil case .rule(let url, _), .composed(let url, _): url } } var nameTitleRule: CitedRule? { switch self {- case .rawURL: nil+ case .rawURL, .authoredEntryID: nil case .rule(_, let name), .composed(_, let name): name } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/EntrySources.swift b/Packages/AsterismCore/Sources/AsterismCore/EntrySources.swiftnew file mode 100644index 00000000..f9db5950--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/EntrySources.swift@@ -0,0 +1,250 @@+import Foundation+import SwiftData++/// Only reader-confirmed associations can connect a taught key to an authored chapter.+public struct EntrySourceEvidence: Codable, Equatable, Sendable {+ public struct Binding: Codable, Equatable, Hashable, Sendable {+ public enum Origin: String, Codable, Sendable { case v2, v3, designation }+ public let origin: Origin+ public let key: String+ public let ruleID: UUID?+ public init(origin: Origin, key: String, ruleID: UUID?) {+ self.origin = origin; self.key = key; self.ruleID = ruleID+ }+ public static func == (lhs: Self, rhs: Self) -> Bool {+ lhs.origin == rhs.origin && lhs.ruleID == rhs.ruleID+ && ExactScalarString(lhs.key) == ExactScalarString(rhs.key)+ }+ public func hash(into hasher: inout Hasher) {+ hasher.combine(origin); hasher.combine(ruleID); hasher.combine(ExactScalarString(key))+ }+ internal var orderKey: String { "\(origin.rawValue)/\(ruleID?.uuidString ?? "")/\(key)" }+ }+ public var confirmed: [Binding]+ public var superseded: [Binding]+ public init(confirmed: [Binding] = [], superseded: [Binding] = []) {+ self.confirmed = confirmed; self.superseded = superseded+ }+ public var active: Set<Binding> { Set(confirmed).subtracting(superseded) }+ public func encoded() throws -> Data {+ try JSONBlob.encode(Self(confirmed: Set(confirmed).sorted { $0.orderKey.utf8.lexicographicallyPrecedes($1.orderKey.utf8) },+ superseded: Set(superseded).sorted { $0.orderKey.utf8.lexicographicallyPrecedes($1.orderKey.utf8) }))+ }+ internal static func union(_ values: [Self]) -> Self {+ Self(confirmed: Array(Set(values.flatMap(\.confirmed))),+ superseded: Array(Set(values.flatMap(\.superseded))))+ }+}++/// Durable UUID routing. Missing targets, cycles, torn groups and divergent late+/// authored changes are review states, never permission to discard a record.+internal struct EntrySourceIndex {+ let groups: [UUID: EntryGroup]+ let sources: [EntrySource]+ let sourcesByDestination: [UUID: [EntrySource]]+ private let destinations: [UUID: UUID]+ private let urlsByDestination: [UUID: Set<ExactScalarString>]+ private let unresolvedDestinations: Set<UUID>+ init(context: ModelContext) throws {+ let rows = try context.fetch(FetchDescriptor<Entry>())+ let grouped = LibraryRepository.entryGroups(rows,+ canonicalWorkIDs: try LibraryRepository.canonicalWorkIDs(normalising: rows, context: context),+ includeResolvedRedirects: true)+ let sourceRows = try context.fetch(FetchDescriptor<EntrySource>())+ groups = grouped; sources = sourceRows+ var routes: [UUID: UUID] = [:]+ for id in grouped.keys {+ if let destination = Self.destination(of: id, groups: grouped, requireResolvedContent: false) {+ routes[id] = destination+ }+ }+ destinations = routes+ var urls: [UUID: Set<ExactScalarString>] = [:]+ var unresolved: Set<UUID> = []+ for group in grouped.values {+ guard let destination = routes[group.id] else { continue }+ for row in group.rows {+ for url in [row.rawURLString, row.canonicalURLString ?? ""] where !url.isEmpty {+ urls[destination, default: []].insert(ExactScalarString(url))+ }+ }+ if group.isTorn || group.rows.contains(where: {+ $0.mergedIntoEntryID != nil && !$0.isResolvedRedirect+ || $0.authoredTargetData != nil && $0.authoredTarget == nil+ }) { unresolved.insert(destination) }+ }+ var owned: [UUID: [EntrySource]] = [:]+ for source in sourceRows {+ guard let destination = routes[source.entryID] else { continue }+ owned[destination, default: []].append(source)+ urls[destination, default: []].insert(ExactScalarString(source.urlString))+ if (try? HostnameNormalizer.fromRawURL(source.urlString)) != source.hostname+ || source.evidenceData.map({ (try? JSONBlob.decode(EntrySourceEvidence.self, from: $0)) == nil }) == true {+ unresolved.insert(destination)+ }+ }+ for copies in Dictionary(grouping: sourceRows, by: \.id).values {+ let owners = Set(copies.compactMap { routes[$0.entryID] })+ if Set(copies.map { ExactScalarString($0.urlString) }).count != 1 || owners.count != 1+ || copies.contains(where: { routes[$0.entryID] == nil }) {+ unresolved.formUnion(owners)+ }+ }+ sourcesByDestination = owned+ urlsByDestination = urls+ unresolvedDestinations = unresolved+ }+ func destination(of id: UUID, requireResolvedContent: Bool = false) -> UUID? {+ requireResolvedContent+ ? Self.destination(of: id, groups: groups, requireResolvedContent: true)+ : destinations[id]+ }+ static func destination(of id: UUID, groups: [UUID: EntryGroup], requireResolvedContent: Bool) -> UUID? {+ var seen: Set<UUID> = []+ var current = id+ while seen.insert(current).inserted {+ guard let group = groups[current], !requireResolvedContent || !group.isTorn else { return nil }+ if requireResolvedContent, group.rows.contains(where: {+ $0.authoredTargetData != nil && $0.authoredTarget == nil+ }) { return nil }+ let redirects = Set(group.rows.compactMap(\.mergedIntoEntryID))+ guard redirects.count <= 1 else { return nil }+ guard let next = redirects.first else { return current }+ guard group.rows.allSatisfy({ $0.mergedIntoEntryID == next }),+ !requireResolvedContent || group.rows.allSatisfy(\.isResolvedRedirect) else { return nil }+ current = next+ }+ return nil+ }+ func urls(for id: UUID) -> [String] {+ guard let destination = destination(of: id) else { return [] }+ return (urlsByDestination[destination] ?? []).map(\.value).sorted { $0.utf8.lexicographicallyPrecedes($1.utf8) }+ }+ func hasUnresolvedContent(for id: UUID) -> Bool {+ guard let destination = destination(of: id) else { return true }+ return unresolvedDestinations.contains(destination)+ }+}++internal enum EntrySources {+ struct Association {+ let entryID: UUID+ let url: String+ var evidence: EntrySourceEvidence? = nil+ }+ static func associate(entryID: UUID, url: String, evidence: EntrySourceEvidence? = nil,+ timestamp: Date, context: ModelContext) throws {+ try associateAll([.init(entryID: entryID, url: url, evidence: evidence)], timestamp: timestamp, context: context)+ }+ /// Transaction-local value buckets; no cross-operation cache or hidden writes.+ static func associateAll(_ associations: [Association], timestamp: Date, context: ModelContext) throws {+ guard !associations.isEmpty else { return }+ let index = try EntrySourceIndex(context: context)+ var buckets = Dictionary(grouping: index.sources) {+ ExactScalarString("\($0.entryID.uuidString)/\($0.urlString)")+ }+ for association in associations {+ let hostname = try HostnameNormalizer.fromRawURL(association.url)+ guard let destination = index.destination(of: association.entryID) else {+ throw LibraryRepositoryError.invalidInput(operation: "saving source", reason: "The chapter target needs review")+ }+ let key = ExactScalarString("\(destination.uuidString)/\(association.url)")+ let rows = buckets[key] ?? []+ if rows.isEmpty {+ let row = EntrySource(entryID: destination, urlString: association.url, hostname: hostname,+ timestamp: timestamp, evidenceData: try association.evidence?.encoded())+ context.insert(row); buckets[key] = [row]+ } else if let evidence = association.evidence {+ let previous = try rows.compactMap { row in+ try row.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ }+ let data = try EntrySourceEvidence.union(previous + [evidence]).encoded()+ for row in rows where row.evidenceData != data { row.evidenceData = data; row.modifiedAt = timestamp }+ }+ }+ }+ /// Non-destructive deterministic convergence: all rows of one association+ /// carry the same union. No orphan sweep and no clock on the silent path.+ static func converge(context: ModelContext) throws -> Bool {+ let rows = try context.fetch(FetchDescriptor<EntrySource>())+ var buckets: [ExactScalarString: [EntrySource]] = [:]+ for row in rows { buckets[ExactScalarString("\(row.entryID.uuidString)/\(row.urlString)"), default: []].append(row) }+ var wrote = false+ for bucket in buckets.values where bucket.count > 1 {+ // Unknown or unreadable evidence is retained for review/export+ // refusal, never overwritten with a partial valid union.+ guard bucket.allSatisfy({ row in+ row.evidenceData == nil || (try? JSONBlob.decode(EntrySourceEvidence.self, from: row.evidenceData!)) != nil+ }) else { continue }+ let values = try bucket.compactMap { row in+ try row.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ }+ let data = values.isEmpty ? nil : try EntrySourceEvidence.union(values).encoded()+ let created = bucket.map(\.createdAt).min()!+ let modified = bucket.map(\.modifiedAt).max()!+ for row in bucket {+ if row.evidenceData != data { row.evidenceData = data; wrote = true }+ if row.createdAt != created { row.createdAt = created; wrote = true }+ if row.modifiedAt != modified { row.modifiedAt = modified; wrote = true }+ }+ }+ return wrote+ }+ static func legacyBindings(of entry: Entry) -> [EntrySourceEvidence.Binding] {+ var bindings: [EntrySourceEvidence.Binding] = []+ switch entry.citationValues.identity {+ case .rule(let rule, _): bindings.append(.init(origin: .v2, key: entry.entryIdentityKey, ruleID: rule.id))+ case .composed(let rule, _): bindings.append(.init(origin: .v3, key: entry.entryIdentityKey, ruleID: rule.id))+ case .rawURL: break+ case .authoredEntryID: return []+ }+ if let pattern = entry.citationValues.chapterTitle.patternID,+ let title = entry.chapterTitle?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty {+ bindings.append(.init(origin: .designation, key: title, ruleID: pattern))+ }+ return bindings+ }+ static func supersedeLegacyEvidence(of group: EntryGroup, timestamp: Date, context: ModelContext) throws {+ let index = try EntrySourceIndex(context: context)+ let destination = index.destination(of: group.id)+ let restoringRedirect = group.rows.contains { $0.mergedIntoEntryID != nil }+ let capturedURLs = Set(group.rows.flatMap { [$0.rawURLString, $0.canonicalURLString ?? ""] }.map(ExactScalarString.init))+ for source in index.sources where index.destination(of: source.entryID) == destination && destination != nil+ && (!restoringRedirect || capturedURLs.contains(ExactScalarString(source.urlString))) {+ let previous = try source.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ ?? EntrySourceEvidence()+ let retired = try EntrySourceEvidence.union([previous, .init(superseded: Array(previous.active))]).encoded()+ if source.evidenceData != retired { source.evidenceData = retired; source.modifiedAt = timestamp }+ }+ for row in group.rows where !row.rawURLString.isEmpty {+ let bindings = legacyBindings(of: row)+ if !bindings.isEmpty {+ try associate(entryID: row.id, url: row.rawURLString,+ evidence: EntrySourceEvidence(superseded: bindings), timestamp: timestamp, context: context)+ }+ }+ }+ static func combine(loser: EntryGroup, survivorID: UUID, timestamp: Date,+ context: ModelContext) throws {+ // Materialise raw/canonical links in one bounded index build.+ let urls = Set(loser.rows.flatMap { [$0.rawURLString, $0.canonicalURLString ?? ""] }+ .filter { !$0.isEmpty }.map(ExactScalarString.init))+ try associateAll(urls.map { .init(entryID: survivorID, url: $0.value) }, timestamp: timestamp, context: context)+ let id = loser.id+ for source in try context.fetch(FetchDescriptor<EntrySource>(predicate: #Predicate { $0.entryID == id })) {+ source.entryID = survivorID+ source.modifiedAt = max(source.modifiedAt, timestamp)+ }+ for row in loser.rows {+ row.mergeResolutionData = try EntryMergeResolution(entry: row).encoded()+ row.mergedIntoEntryID = survivorID+ row.modifiedAt = timestamp+ }+ }+ static func delete(ownedBy ids: Set<UUID>, context: ModelContext) throws {+ let keys = Array(ids)+ for row in try context.fetch(FetchDescriptor<EntrySource>(predicate: #Predicate { keys.contains($0.entryID) })) {+ context.delete(row)+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swiftindex 32330c83..af532cfd 100644--- a/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift@@ -145,6 +145,9 @@ public struct EntryAuthoredContent: AuthoredContent { /// chapter title is a derived field (Q44). public let chapterTitle: String? public let intentionallyUnattached: Bool+ public let authoredTargetData: Data?+ public let mergedIntoEntryID: UUID?+ public let mergeResolutionData: Data? /// The assignment as *equality* sees it — a comparison key, never a value. ///@@ -164,12 +167,17 @@ public struct EntryAuthoredContent: AuthoredContent { rating: Rating? = nil, workAssignment: UUID? = nil, chapterTitle: String? = nil,- intentionallyUnattached: Bool = false+ intentionallyUnattached: Bool = false,+ authoredTargetData: Data? = nil, mergedIntoEntryID: UUID? = nil,+ mergeResolutionData: Data? = nil ) { self.note = note self.rating = rating self.workAssignment = workAssignment self.chapterTitle = chapterTitle+ self.authoredTargetData = AuthoredEntryTarget.canonicalData(authoredTargetData)+ self.mergedIntoEntryID = mergedIntoEntryID+ self.mergeResolutionData = mergeResolutionData self.intentionallyUnattached = intentionallyUnattached self.assignmentEqualityKey = workAssignment }@@ -185,13 +193,17 @@ public struct EntryAuthoredContent: AuthoredContent { && lhs.assignmentEqualityKey == rhs.assignmentEqualityKey && lhs.chapterTitle == rhs.chapterTitle && lhs.intentionallyUnattached == rhs.intentionallyUnattached+ && lhs.authoredTargetData == rhs.authoredTargetData+ && lhs.mergedIntoEntryID == rhs.mergedIntoEntryID+ && lhs.mergeResolutionData == rhs.mergeResolutionData } /// A whitespace-only note counts as authored. Absence of a rating is the /// neutral default and cannot be told from a deliberate one (Decision 1). public var isBare: Bool { note.isEmpty && rating == nil && workAssignment == nil && chapterTitle == nil- && !intentionallyUnattached+ && !intentionallyUnattached && authoredTargetData == nil+ && mergedIntoEntryID == nil && mergeResolutionData == nil } public var orderComponents: [OrderComponent] {@@ -201,6 +213,9 @@ public struct EntryAuthoredContent: AuthoredContent { .absentableString(assignmentEqualityKey.map { $0.uuidString.lowercased() }), .absentableString(chapterTitle), .flag(intentionallyUnattached),+ .absentableString(authoredTargetData?.base64EncodedString()),+ .absentableString(mergedIntoEntryID?.uuidString.lowercased()),+ .absentableString(mergeResolutionData?.base64EncodedString()), ] } @@ -244,6 +259,7 @@ public struct WorkAuthoredContent: AuthoredContent { /// 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 chapterCaptureDefaultRaw: String public var readingStatus: ReadingStatus /// Non-empty is authored — including under a `reading` status, where Q7 /// hides the text but Q14 still counts it (Q21).@@ -285,8 +301,10 @@ public struct WorkAuthoredContent: AuthoredContent { membership: SeriesMembership? = nil, thumbnail: ThumbnailIdentity? = nil, releaseDays: [ReleaseDay] = [],- publicationStateData: Data? = nil+ publicationStateData: Data? = nil,+ chapterCaptureDefaultRaw: String = "ordinary" ) {+ self.chapterCaptureDefaultRaw = chapterCaptureDefaultRaw self.releaseDays = ReleaseDay.canonical(releaseDays) self.thumbnail = thumbnail self.membership = membership@@ -318,11 +336,12 @@ 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 && publicationStateData == nil+ && releaseDays.isEmpty && publicationStateData == nil && chapterCaptureDefaultRaw == "ordinary" } public var orderComponents: [OrderComponent] { [+ .string(chapterCaptureDefaultRaw), .string(genericNotes), .absentableString(manualTitle), .absentableString(workURLString),@@ -656,7 +675,9 @@ public enum GroupOrdering { rating: entry.rating, workAssignment: citations.workAssignment == .manual ? entry.work?.id : nil, chapterTitle: citations.chapterTitle.kind == .manual ? entry.chapterTitle : nil,- intentionallyUnattached: entry.intentionallyUnattached)+ intentionallyUnattached: entry.intentionallyUnattached,+ authoredTargetData: entry.authoredTargetData, mergedIntoEntryID: entry.mergedIntoEntryID,+ mergeResolutionData: entry.mergeResolutionData) } /// `types` is not optional and not defaulted: an empty directory reads every@@ -715,7 +736,8 @@ public enum GroupOrdering { // 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,- publicationStateData: work.publicationStateData)+ publicationStateData: work.publicationStateData,+ chapterCaptureDefaultRaw: work.chapterCaptureDefaultRaw) } /// A row's series pair, or nil.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex 6ea15a35..ac9fbfbe 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift@@ -3,6 +3,13 @@ import Foundation /// Test seam for the app's view-model layer to consume repository operations /// without coupling directly to the actor or its persistence internals. public protocol LibraryProviding: Sendable {+ func projectManualEntry(workID: UUID) async throws -> ChapterCaptureProjection+ func commitManualEntry(projection: ChapterCaptureProjection, draft: ManualEntryDraft) async throws -> ChapterCaptureCommitOutcome+ func projectChapterCapture(rawURL: String, captureTitle: String?, workID: UUID) async throws -> ChapterCaptureProjection+ func commitChapterCapture(_ draft: ChapterCaptureDraft) async throws -> ChapterCaptureCommitOutcome+ func projectEntryCorrection(entryID: UUID, destinationID: UUID?) async throws -> EntryCorrectionContract+ func commitEntryCorrection(_ contract: EntryCorrectionContract, target: AuthoredEntryTarget,+ contentChoice: EntryCorrectionContentChoice?) async throws -> EntryCorrectionOutcome // MARK: - Read operations func todayPresentation(calendar: Calendar) async throws -> TodayPresentation func works() async throws -> WorksSnapshot@@ -805,3 +812,26 @@ extension LibraryProviding { try await projectMerge(sourceWorkID: sourceWorkID, targetWorkID: targetWorkID, request: .merge) } }++// Existing test doubles and hosts without these editing surfaces refuse clearly.+extension LibraryProviding {+ public func projectManualEntry(workID: UUID) async throws -> ChapterCaptureProjection {+ throw LibraryRepositoryError.invalidInput(operation: "manual note", reason: "Manual notes are unavailable")+ }+ public func commitManualEntry(projection: ChapterCaptureProjection, draft: ManualEntryDraft) async throws -> ChapterCaptureCommitOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "manual note", reason: "Manual notes are unavailable")+ }+ public func projectChapterCapture(rawURL: String, captureTitle: String?, workID: UUID) async throws -> ChapterCaptureProjection {+ throw LibraryRepositoryError.invalidInput(operation: "chapter capture", reason: "Chapter review is unavailable")+ }+ public func commitChapterCapture(_ draft: ChapterCaptureDraft) async throws -> ChapterCaptureCommitOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "chapter capture", reason: "Chapter review is unavailable")+ }+ public func projectEntryCorrection(entryID: UUID, destinationID: UUID? = nil) async throws -> EntryCorrectionContract {+ throw LibraryRepositoryError.invalidInput(operation: "chapter correction", reason: "Chapter correction is unavailable")+ }+ public func commitEntryCorrection(_ contract: EntryCorrectionContract, target: AuthoredEntryTarget,+ contentChoice: EntryCorrectionContentChoice? = nil) async throws -> EntryCorrectionOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "chapter correction", reason: "Chapter correction is unavailable")+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swiftindex ffadf5c5..0106913d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift@@ -86,6 +86,7 @@ extension LibraryRepository { var worksByID: [UUID: Work] = [:] for record in payload.works { let work = try ArchiveRecordBuilders.makeWork(record)+ if let value = payload.workCaptureDefaults[record.id] { work.chapterCaptureDefault = value } context.insert(work) worksByID[record.id] = work }@@ -131,11 +132,19 @@ extension LibraryRepository { for record in payload.entries { let entry = ArchiveRecordBuilders.makeEntry(record)+ if let value = payload.chapterEntries[record.id] { Self.applyChapterArchive(value, to: entry) } context.insert(entry) entry.site = sitesByHostname[record.hostname] entry.work = record.workID.flatMap { worksByID[$0] } } + for source in payload.entrySources {+ let row = EntrySource(id: source.id, entryID: source.entryID, urlString: source.urlString,+ hostname: source.hostname, timestamp: source.createdAt, evidenceData: source.evidenceData)+ row.modifiedAt = source.modifiedAt+ context.insert(row)+ }+ // A character whose work reference names nothing the archive carries // lands unattached — the tolerated in-flight state of Req 6.7, and the // shape the wire validator lets through as an orphan (Q78).
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swiftindex 92399502..894c0293 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swiftindex 03a04e72..150ce685 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 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+/// Opens the live V20 library after classifying the fixed-path store.+/// The app accepts markers `"16"` through `"20"`; the extension accepts only `"20"`.+/// V16 through V19 stores migrate through lightweight stages. The app validates+/// before publishing `"20"`, 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@@ -380,7 +380,7 @@ extension LibraryRepository { at storeURL: URL, mirroring cloudKitDatabase: ModelConfiguration.CloudKitDatabase = .none ) throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let storeConfiguration = ModelConfiguration( // **Frozen persisted state (Req 3.5).** This names the store // configuration *inside* the container, not the file — `url:` below is@@ -394,7 +394,7 @@ extension LibraryRepository { ) return try ModelContainer( for: schema,- migrationPlan: AsterismV19MigrationPlan.self,+ migrationPlan: AsterismV20MigrationPlan.self, configurations: [storeConfiguration] ) }@@ -547,7 +547,7 @@ extension LibraryRepository { /// convert its store anyway; the recovery is the backup archive, as for any /// unrecognised marker. static let appOpenableMarkerVersions: Set<String> = [- laggingOpenableMarkerVersion, "17", "18", extensionOpenableMarkerVersion,+ laggingOpenableMarkerVersion, "17", "18", "19", extensionOpenableMarkerVersion, ] /// The one lagging generation the app still opens: a library certified by a@@ -560,7 +560,7 @@ extension LibraryRepository { /// installed library (Req 3.5). Both generations the app opens are now /// spelled with two characters, which is why nothing anywhere may assume a /// marker is one character long.- static let extensionOpenableMarkerVersion = "19"+ static let extensionOpenableMarkerVersion = "20" // The app-side counterpart of `validateMarkerContentForExtension` stood // here. It restated the acceptance test the classifier performs, and
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swiftindex 25efeb6b..d7250823 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift@@ -24,12 +24,14 @@ public enum CaptureLookupDisposition: Sendable, Equatable { /// Basis for a new capture: the lookup proved zero matches. public struct NewLookupBasis: Sendable, Equatable {+ public let chapterProjection: ChapterCaptureProjection? /// Normalized hostname derived from the raw URL. public let hostname: String /// The identity key derived from the raw URL (conservative or URL-rule). public let identityKey: String - public init(hostname: String, identityKey: String) {+ public init(hostname: String, identityKey: String, chapterProjection: ChapterCaptureProjection? = nil) {+ self.chapterProjection = chapterProjection self.hostname = hostname self.identityKey = identityKey }@@ -38,6 +40,7 @@ public struct NewLookupBasis: Sendable, Equatable { /// Basis for editing an existing Entry on re-share (Design §8.2). /// Contains the persisted baseline needed for stale comparison on commit. public struct ReShareEditBasis: Sendable, Equatable {+ public let chapterProjection: ChapterCaptureProjection? /// Matched Entry UUID. public let entryID: UUID /// Normalized hostname.@@ -73,8 +76,10 @@ public struct ReShareEditBasis: Sendable, Equatable { persistedRating: Rating?, persistedModifiedAt: Date, firstCapturedAt: Date,- workContext: ShareWorkContext = .empty+ workContext: ShareWorkContext = .empty,+ chapterProjection: ChapterCaptureProjection? = nil ) {+ self.chapterProjection = chapterProjection self.entryID = entryID self.hostname = hostname self.identityKey = identityKey@@ -86,6 +91,13 @@ public struct ReShareEditBasis: Sendable, Equatable { self.workContext = workContext } + public func with(chapterProjection: ChapterCaptureProjection) -> ReShareEditBasis {+ ReShareEditBasis(entryID: entryID, hostname: hostname, identityKey: identityKey, title: title,+ persistedNote: persistedNote, persistedRating: persistedRating,+ persistedModifiedAt: persistedModifiedAt, firstCapturedAt: firstCapturedAt,+ workContext: workContext, chapterProjection: chapterProjection)+ }+ /// The same basis carrying a work context. The lookup builds the basis /// before it knows whether the read is wanted, so the context is attached /// rather than threaded through `reShareBasis(hostname:site:)`, which the commit@@ -100,7 +112,7 @@ public struct ReShareEditBasis: Sendable, Equatable { persistedRating: persistedRating, persistedModifiedAt: persistedModifiedAt, firstCapturedAt: firstCapturedAt,- workContext: workContext)+ workContext: workContext, chapterProjection: chapterProjection) } } @@ -118,7 +130,10 @@ public struct DrainedReShareTarget: Sendable, Equatable { /// The identity key that produced the match. public let identityKey: String - public init(entryID: UUID, hostname: String, identityKey: String) {+ public let chapterProjection: ChapterCaptureProjection?++ public init(entryID: UUID, hostname: String, identityKey: String, chapterProjection: ChapterCaptureProjection? = nil) {+ self.chapterProjection = chapterProjection self.entryID = entryID self.hostname = hostname self.identityKey = identityKey@@ -128,6 +143,7 @@ public struct DrainedReShareTarget: Sendable, Equatable { /// Outcome of recording a preserved capture against an existing entry. public enum DrainedReShareOutcome: Sendable, Equatable { case committed+ case reviewRequired /// The entry no longer exists, or no longer carries the key it was matched /// on. The caller commits the capture as a new entry (Req 4.6). case entryGone@@ -212,8 +228,26 @@ extension LibraryRepository { let canonicalWorkIDs = try Self.canonicalWorkIDs( normalising: matches, context: context) let groups = Self.entryGroups(matches, canonicalWorkIDs: canonicalWorkIDs)- let disposition = Self.lookupDisposition(- fromGroups: groups, hostname: hostname, identityKey: rawURL, site: site)+ let projected = (try? self.buildCaptureBasis(hostname: hostname, context: context)).map {+ Self.computeCaptureOutcome(basis: $0,+ request: CaptureRequest(captureTitle: captureTitle ?? "", captureTitleSource: .manual,+ rawURLString: rawURL, canonicalURLString: nil, note: "", rating: nil))+ }+ let chapterWorkID = try Self.chapterCaptureWorkID(rawURL: rawURL,+ projectedWorkID: projected?.projectedWorkID, context: context)+ let disposition: CaptureLookupDisposition+ if let chapterWorkID {+ let projection = try self.chapterCaptureProjection(rawURL: rawURL, captureTitle: captureTitle,+ hostname: hostname, workID: chapterWorkID, context: context)+ if case .update(let id) = projection.resolution {+ let group = try Self.fetchNormalisedEntryGroup(id: id, context: context)+ disposition = .edit(group.reShareBasis(hostname: hostname, site: site).with(chapterProjection: projection))+ } else {+ disposition = .new(NewLookupBasis(hostname: hostname, identityKey: rawURL, chapterProjection: projection))+ }+ } else {+ disposition = Self.lookupDisposition(fromGroups: groups, hostname: hostname, identityKey: rawURL, site: site)+ } // Still inside the same shared read: what the sheet shows comes // from the state the disposition was decided on, over the one@@ -221,7 +255,7 @@ extension LibraryRepository { // `.values.first` is the group the basis describes: `.edit` is // returned only where `groups.count == 1`. guard includeWorkContext, case .edit(let basis) = disposition,- let matched = groups.values.first,+ let matched = try? Self.fetchNormalisedEntryGroup(id: basis.entryID, context: context), let workID = matched.carrier.work?.id else { return disposition } @@ -360,6 +394,22 @@ extension LibraryRepository { rating: Rating? ) async throws -> ReShareUpdateOutcome { try await withLockedContext(mode: .exclusive, operation: "committing re-share update") { context in+ if let projection = basis.chapterProjection {+ let draft = ChapterCaptureDraft(projection: projection,+ capture: CaptureDraft(captureTitle: projection.captureTitle ?? "",+ captureTitleSource: .manual, rawURLString: projection.rawURL, note: note, rating: rating),+ intent: .automatic)+ switch try self.applyChapterCapture(draft, hostname: basis.hostname, context: context) {+ case .committed: return .committed+ case .reviewRequired(let fresh, let reason):+ guard let group = try? Self.fetchNormalisedEntryGroup(id: basis.entryID, context: context) else {+ return .invalidated(reason: reason)+ }+ return .stale(group.reShareBasis(hostname: basis.hostname,+ site: try Self.fetchSites(hostname: basis.hostname, context: context).first).with(chapterProjection: fresh))+ }+ }+ // The addressed logical record. A duplicate application UUID used to // refuse the update outright, so a re-share of a chapter that // arrived twice reported the reader's own note as unwritable; the@@ -491,18 +541,31 @@ extension LibraryRepository { return .entryGone } - // Req 4.6: the record may no longer resolve to the entry it matched- // — a re-teach can rewrite an identity key between the lookup and- // this commit. That is not a failure; the caller creates a new- // entry, exactly as a capture taken now would.- let stillMatches = group.rows.contains { row in- row.hostname == target.hostname- && (row.entryIdentityKey == target.identityKey- || row.conservativeIdentityKey == target.identityKey)- }- guard stillMatches else {- captureLogger.debug("Drained re-share: entry \(target.entryID) no longer matches")- return .entryGone+ let freshProjection: ChapterCaptureProjection?+ if let prior = target.chapterProjection, let workID = prior.workID {+ let fresh = try self.chapterCaptureProjection(rawURL: prior.rawURL,+ captureTitle: prior.captureTitle, hostname: target.hostname, workID: workID, context: context)+ guard case .update(let id) = fresh.resolution, id == group.id else { return .reviewRequired }+ // Authored edits are preserved, so their timestamps need not equal+ // the lookup. Identity, assignment, rules and sources still must.+ guard fresh.workContent == prior.workContent, fresh.ruleBasis == prior.ruleBasis,+ fresh.evidence == prior.evidence,+ let old = prior.entries.first(where: { $0.id == id }),+ let current = fresh.entries.first(where: { $0.id == id }),+ old.target == current.target,+ old.bindings.union(fresh.evidence.map(\.binding)) == current.bindings.union(fresh.evidence.map(\.binding)),+ old.sourceURLs.union([ExactScalarString(fresh.rawURL)]) == current.sourceURLs.union([ExactScalarString(fresh.rawURL)]),+ old.authoredContent?.workAssignment == current.authoredContent?.workAssignment,+ old.authoredContent?.chapterTitle == current.authoredContent?.chapterTitle,+ old.authoredContent?.intentionallyUnattached == current.authoredContent?.intentionallyUnattached+ else { return .reviewRequired }+ freshProjection = fresh+ } else {+ guard group.rows.contains(where: { row in+ row.hostname == target.hostname+ && (row.entryIdentityKey == target.identityKey || row.conservativeIdentityKey == target.identityKey)+ }) else { return .entryGone }+ freshProjection = nil } let timestamp = self.clock.now()@@ -515,20 +578,31 @@ extension LibraryRepository { wrote = true } - // Nothing to write is the whole of the replay case, and of a capture- // of an already-newer entry. Both fall out of the rule.- guard wrote else { return .committed }-- try NoEpisodeWriter.recordNoteTransition(- before: before, after: Self.noteFacts(group, calendar: calendar), context: context)-- do { try self.saveStrategy.save(context) }- catch {- // Not `libraryUnavailable`: one record whose save fails must not- // read as the library going away, or it would abort every drain- // pass forever (Req 5.7).- throw LibraryRepositoryError.captureSaveFailed(- reason: String(describing: error))+ do {+ if let projection = freshProjection {+ let existingSources = try EntrySourceIndex(context: context).sourcesByDestination[group.id] ?? []+ let desired = group.carrier.authoredTarget?.kind == .chapter+ ? EntrySourceEvidence(confirmed: projection.evidence.map(\.binding)) : nil+ let alreadyAssociated = existingSources.contains { source in+ ExactScalarString(source.urlString) == ExactScalarString(projection.rawURL) && (desired == nil || desired!.active.isSubset(of:+ source.evidenceData.flatMap { try? JSONBlob.decode(EntrySourceEvidence.self, from: $0) }?.active ?? []))+ }+ if !alreadyAssociated {+ try EntrySources.associate(entryID: group.id, url: projection.rawURL,+ evidence: desired, timestamp: timestamp, context: context)+ wrote = true+ }+ }+ guard wrote else { return .committed }+ try NoEpisodeWriter.recordNoteTransition(+ before: before, after: Self.noteFacts(group, calendar: calendar), context: context)+ try self.saveStrategy.save(context)+ } catch {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Entry>())+ _ = try? context.fetch(FetchDescriptor<EntrySource>())+ _ = try? context.fetch(FetchDescriptor<NoEpisodeAction>())+ throw LibraryRepositoryError.captureSaveFailed(reason: String(describing: error)) } captureLogger.debug("Drained re-share recorded for entry \(group.id, privacy: .public)") return .committed
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ChapterCapture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ChapterCapture.swiftnew file mode 100644index 00000000..b1460dca--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ChapterCapture.swift@@ -0,0 +1,363 @@+import Foundation+import SwiftData++extension LibraryRepository {+ public func projectChapterCapture(rawURL: String, captureTitle: String?, workID: UUID) async throws -> ChapterCaptureProjection {+ let hostname = try HostnameNormalizer.fromRawURL(rawURL)+ _ = try EntryIdentityNormalizer.key(forRawURL: rawURL)+ return try await withLockedContext(mode: .shared, operation: "reviewing chapter capture") { context in+ try self.chapterCaptureProjection(rawURL: rawURL, captureTitle: captureTitle,+ hostname: hostname, workID: workID, context: context)+ }+ }++ internal func chapterCaptureProjection(rawURL: String, captureTitle: String?, hostname: String,+ workID: UUID, context: ModelContext) throws -> ChapterCaptureProjection {+ let captureTitle = captureTitle.flatMap { $0.isEmpty ? nil : $0 }+ let work = try Self.fetchWorkGroup(id: workID, context: context)+ let index = try EntrySourceIndex(context: context)+ let derivedEvidence = try Self.chapterCaptureEvidence(rawURL: rawURL, captureTitle: captureTitle,+ hostname: hostname, context: context)+ let unscopedRejection = index.sources.contains { source in+ ExactScalarString(source.urlString) == ExactScalarString(rawURL)+ && source.evidenceData.flatMap { try? JSONBlob.decode(EntrySourceEvidence.self, from: $0) }?.superseded.isEmpty == false+ && index.destination(of: source.entryID, requireResolvedContent: false) == nil+ }+ let rejected = Set(index.sources.filter {+ ExactScalarString($0.urlString) == ExactScalarString(rawURL)+ && index.destination(of: $0.entryID, requireResolvedContent: false).flatMap { index.groups[$0]?.carrier.work?.id } == workID+ }.flatMap { source in+ source.evidenceData.flatMap { try? JSONBlob.decode(EntrySourceEvidence.self, from: $0) }?.superseded ?? []+ })+ let evidence = derivedEvidence.filter { !rejected.contains($0.binding) }+ let entries = index.groups.values.filter { group in+ group.carrier.work?.id == workID && group.rows.allSatisfy { $0.mergedIntoEntryID == nil }+ }.map { group in+ let related = index.sourcesByDestination[group.id] ?? []+ let sourceEvidence = related.compactMap { $0.evidenceData.flatMap {+ try? JSONBlob.decode(EntrySourceEvidence.self, from: $0)+ } }+ let union = EntrySourceEvidence.union(sourceEvidence)+ var bindings = union.active+ if group.carrier.authoredTargetData == nil {+ for row in group.rows {+ bindings.formUnion(EntrySources.legacyBindings(of: row))+ if let pattern = row.citationValues.chapterTitle.patternID,+ let designation = row.chapterTitle?.trimmingCharacters(in: .whitespacesAndNewlines),+ !designation.isEmpty {+ bindings.insert(.init(origin: .designation, key: designation, ruleID: pattern))+ }+ }+ }+ bindings.subtract(union.superseded)+ return ChapterCaptureEntry(id: group.id, workID: workID, target: group.carrier.authoredTarget,+ bindings: bindings, sourceURLs: index.urls(for: group.id),+ requiresReview: index.hasUnresolvedContent(for: group.id),+ note: group.presentedContent.note, rating: group.presentedContent.rating, modifiedAt: group.modifiedAt, authoredContent: group.presentedContent,+ displayLabel: group.carrier.effectiveChapterTitle ?? group.carrier.effectiveChapterSequence+ ?? group.carrier.authoredTarget?.title ?? group.carrier.captureTitle)+ }+ var projection = ChapterCaptureResolver.project(workID: workID, rawURL: rawURL, evidence: evidence,+ entries: entries, captureDefault: work.carrier.chapterCaptureDefault)+ if unscopedRejection {+ projection = ChapterCaptureProjection(workID: workID, rawURL: rawURL, evidence: evidence, entries: projection.entries,+ resolution: .chooseChapter(entryIDs: projection.entries.map(\.id), reason: "Review this page's corrected chapter ownership"),+ offersAnotherChapter: false, captureDefault: work.carrier.chapterCaptureDefault)+ }+ projection.captureTitle = captureTitle+ projection.workContent = work.presentedContent+ projection.workModifiedAt = work.modifiedAt+ projection.ruleBasis = try? self.buildCaptureBasis(hostname: hostname, context: context)+ return projection+ }++ internal static func chapterCaptureEvidence(rawURL: String, captureTitle: String?, hostname: String,+ context: ModelContext) throws -> [ChapterCaptureEvidence] {+ guard let site = try fetchSites(hostname: hostname, context: context).first,+ site.mode == .taught else { return [] }+ let urlRecord = site.currentURLRule+ let url = urlRecord.flatMap { try? $0.definition }+ var result: [ChapterCaptureEvidence] = []+ if let url, let urlRecord, url.suppliesIdentity,+ let extraction = try? URLRuleApplicator.apply(url, to: ExactScalarString(rawURL)),+ let sequence = extraction.chapterSequence,+ let identity = try? URLDerivedEntryIdentity(hostname: ExactScalarString(hostname),+ workIdentity: extraction.workIdentity, chapterSequence: sequence) {+ result.append(.init(origin: .v2, key: EntryIdentityKeyV2Codec.encode(identity),+ ruleID: urlRecord.id, chapterFact: sequence.value))+ }+ if let captureTitle, let pattern = site.activePattern,+ let definition = try? pattern.storedDefinition {+ let derived = ComposedDeriver.derive(captureTitle: captureTitle, rawURL: rawURL,+ hostname: hostname, titleRule: ComposedTitleRule(definition),+ urlRule: url.map(ComposedURLRule.init))+ if derived.identity.version == 3, let urlRecord {+ result.append(.init(origin: .v3, key: derived.identity.key, ruleID: urlRecord.id,+ chapterFact: derived.chapterSequence?.value))+ }+ if let title = derived.chapterTitle?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty {+ result.append(.init(origin: .designation, key: title, ruleID: pattern.id, chapterFact: title))+ }+ }+ return result+ }+}++public enum ChapterCaptureIntent: Equatable, Sendable {+ case automatic+ case existing(UUID, contentChoice: EntryCorrectionContentChoice? = nil)+ case newChapter(AuthoredEntryTarget, confirmedNew: Bool)+ case genericNote+ case correctedExisting(UUID, contentChoice: EntryCorrectionContentChoice?)+ case correctedNewChapter(AuthoredEntryTarget)+}++extension ChapterCaptureProjection {+ public func needsContentChoice(intent: ChapterCaptureIntent, note: String, rating: Rating?) -> Bool {+ let id: UUID+ switch intent {+ case .existing(let selected, let choice), .correctedExisting(let selected, let choice):+ guard choice == nil else { return false }; id = selected+ default: return false+ }+ guard let selected = entries.first(where: { $0.id == id }) else { return true }+ return selected.note != note || selected.rating != rating+ }+}++public struct ChapterCaptureDraft: Equatable, Sendable {+ public let projection: ChapterCaptureProjection+ public let capture: CaptureDraft+ public let intent: ChapterCaptureIntent+ public let entryID: UUID?+ public let capturedAt: Date?+ public init(projection: ChapterCaptureProjection, capture: CaptureDraft, intent: ChapterCaptureIntent,+ entryID: UUID? = nil, capturedAt: Date? = nil) {+ self.projection = projection; self.capture = capture; self.intent = intent+ self.entryID = entryID; self.capturedAt = capturedAt+ }+}++public enum ChapterCaptureCommitOutcome: Equatable, Sendable {+ case committed(EntrySnapshot)+ case reviewRequired(ChapterCaptureProjection, reason: String)+}++extension LibraryRepository {+ /// One save owns the note/rating, explicit target, source evidence and any+ /// learned work default. A refreshed projection does not replace the draft.+ public func commitChapterCapture(_ draft: ChapterCaptureDraft) async throws -> ChapterCaptureCommitOutcome {+ let capture = draft.capture+ let hostname = try HostnameNormalizer.fromRawURL(capture.rawURLString)+ _ = try EntryIdentityNormalizer.key(forRawURL: capture.rawURLString)+ guard draft.projection.workID != nil else {+ throw LibraryRepositoryError.invalidInput(operation: "saving chapter", reason: "Choose a work")+ }+ return try await withLockedContext(mode: .exclusive, operation: "saving chapter capture") { context in+ try self.applyChapterCapture(draft, hostname: hostname, context: context)+ }+ }++ internal func applyChapterCapture(_ draft: ChapterCaptureDraft, hostname: String,+ context: ModelContext) throws -> ChapterCaptureCommitOutcome {+ let capture = draft.capture+ guard let workID = draft.projection.workID else {+ throw LibraryRepositoryError.invalidInput(operation: "saving chapter", reason: "Choose a work")+ }+ let fresh = try self.chapterCaptureProjection(rawURL: capture.rawURLString, captureTitle: capture.captureTitle,+ hostname: hostname, workID: workID, context: context)+ guard fresh == draft.projection else {+ return .reviewRequired(fresh, reason: "The chapter changed. Review your choice again")+ }+ let selectedID: UUID?+ let newTarget: AuthoredEntryTarget?+ let isCorrection: Bool+ switch draft.intent {+ case .correctedExisting, .correctedNewChapter: isCorrection = true+ default: isCorrection = false+ }+ var contentNote = capture.note+ var contentRating = capture.rating+ switch draft.intent {+ case .existing(let id, let contentChoice):+ guard let selected = fresh.entries.first(where: { $0.id == id && !$0.requiresReview && (fresh.evidence.isEmpty || $0.target?.kind != .note) }) else {+ return .reviewRequired(fresh, reason: "Choose a chapter that does not need content review")+ }+ let differs = !capture.note.isEmpty && !selected.note.isEmpty && capture.note != selected.note+ || capture.rating != nil && selected.rating != nil && capture.rating != selected.rating+ guard !differs || contentChoice != nil else {+ return .reviewRequired(fresh, reason: "Choose which note and rating to keep")+ }+ if contentChoice == .destination { contentNote = selected.note; contentRating = selected.rating }+ else if contentChoice == nil {+ if contentNote.isEmpty { contentNote = selected.note }+ contentRating = contentRating ?? selected.rating+ }+ selectedID = id; newTarget = nil+ case .newChapter(let target, let confirmedNew):+ guard target.kind == .chapter,+ fresh.entries.filter({ $0.target?.kind != .note }).isEmpty || confirmedNew else {+ return .reviewRequired(fresh, reason: "Choose an existing chapter or confirm a new one")+ }+ if let designation = target.designation,+ fresh.entries.contains(where: { $0.target?.kind == .chapter && $0.target?.designation.map(ExactScalarString.init) == ExactScalarString(designation) }) {+ return .reviewRequired(fresh, reason: "A chapter already has that designation. Choose it or change the designation")+ }+ selectedID = nil; newTarget = target+ case .genericNote:+ selectedID = nil; newTarget = .init(kind: .note)+ case .correctedExisting(let id, let contentChoice):+ guard let selected = fresh.entries.first(where: { $0.id == id && !$0.requiresReview && $0.target?.kind != .note }) else {+ return .reviewRequired(fresh, reason: "Choose a chapter that does not need content review")+ }+ let differs = !capture.note.isEmpty && !selected.note.isEmpty && capture.note != selected.note+ || capture.rating != nil && selected.rating != nil && capture.rating != selected.rating+ guard !differs || contentChoice != nil else {+ return .reviewRequired(fresh, reason: "Choose which note and rating to keep")+ }+ if contentChoice == .destination { contentNote = selected.note; contentRating = selected.rating }+ else if contentChoice == nil {+ if contentNote.isEmpty { contentNote = selected.note }+ contentRating = contentRating ?? selected.rating+ }+ selectedID = id; newTarget = nil+ case .correctedNewChapter(let target):+ guard target.kind == .chapter else { return .reviewRequired(fresh, reason: "Choose a chapter") }+ if let designation = target.designation,+ fresh.entries.contains(where: { $0.target?.designation.map(ExactScalarString.init) == ExactScalarString(designation) }) {+ return .reviewRequired(fresh, reason: "A chapter already has that designation. Choose it")+ }+ selectedID = nil; newTarget = target+ case .automatic:+ switch fresh.resolution {+ case .update(let id): selectedID = id; newTarget = nil+ case .newEntry: selectedID = nil; newTarget = nil+ case .newChapter(let requiresConfirmation):+ guard !requiresConfirmation else {+ return .reviewRequired(fresh, reason: "Choose an existing chapter or confirm a new one")+ }+ selectedID = nil+ let sharesSavedSource = fresh.entries.contains {+ $0.target?.kind != .note && $0.sourceURLs.contains(ExactScalarString(capture.rawURLString))+ }+ newTarget = sharesSavedSource ? .init(kind: .chapter,+ title: fresh.evidence.first { $0.binding.origin == .designation }?.binding.key,+ designation: fresh.evidence.first { $0.binding.origin != .designation }?.chapterFact?.value) : nil+ case .chooseChapter(_, let reason): return .reviewRequired(fresh, reason: reason)+ }+ }+ let stamp = clock.now()+ do {+ let work = try Self.fetchWorkGroup(id: workID, context: context)+ let ordinaryNew = draft.intent == .automatic && selectedID == nil && newTarget == nil+ guard !work.isTorn || ordinaryNew else { return .reviewRequired(fresh, reason: "Review the work's differing copies") }+ let site = try Self.siteForWrite(hostname: hostname, context: context)+ let group: EntryGroup+ let before: Set<NoEpisodeWriter.NoteFact>+ var associations: [EntrySources.Association] = []+ if let selectedID {+ group = try Self.fetchNormalisedEntryGroup(id: selectedID, context: context)+ before = Self.noteFacts(group, calendar: noteCalendar())+ for row in group.rows {+ let authorsChapter = draft.intent != .automatic+ if row.authoredTargetData == nil && authorsChapter {+ let prior = EntrySources.legacyBindings(of: row)+ if !row.rawURLString.isEmpty {+ associations.append(.init(entryID: row.id, url: row.rawURLString, evidence: .init(confirmed: prior)))+ }+ try row.authorTarget(.init(kind: .chapter, title: row.chapterTitle, designation: row.chapterSequence))+ }+ row.note = contentNote; row.rating = contentRating+ row.lastSharedAt = draft.capturedAt ?? stamp; row.modifiedAt = stamp+ }+ } else {+ let row = Entry(id: draft.entryID ?? UUID(), captureTitle: capture.captureTitle, captureTitleSource: capture.captureTitleSource,+ rawURLString: capture.rawURLString, canonicalURLString: capture.canonicalURLString,+ hostname: hostname, entryIdentityKey: capture.rawURLString, timestamp: stamp,+ capturedAt: draft.capturedAt, note: contentNote, rating: contentRating)+ context.insert(row)+ row.site = site; row.work = work.representative+ row.conservativeIdentityKey = capture.rawURLString+ if draft.intent == .automatic, let basis = fresh.ruleBasis,+ basis.siteMode == .taught, let titleRule = basis.currentTitleRule {+ let url = basis.currentURLRule.map { (id: $0.id, definition: $0.definition) }+ let derivation = ComposedDeriver.derive(captureTitle: capture.captureTitle,+ rawURL: capture.rawURLString, hostname: hostname,+ titleRule: ComposedTitleRule(titleRule), urlRule: url.map { ComposedURLRule(definition: $0.definition) })+ let outcome = Self.computeCaptureOutcome(basis: basis,+ request: CaptureRequest(captureTitle: capture.captureTitle, captureTitleSource: capture.captureTitleSource,+ rawURLString: capture.rawURLString, canonicalURLString: capture.canonicalURLString,+ note: contentNote, rating: contentRating))+ let works = try Self.worksOn(hostname: hostname, context: context)+ let types = try Self.workTypeDirectory(context: context)+ row.editCitations { citations in+ Self.applyEntryIdentityAndChapter(to: row, citations: &citations, derivation: derivation,+ titleRuleID: titleRule.id, url: url)+ Self.applyCaptureAssignment(to: row, citations: &citations,+ assignment: outcome.composedAssignment, derivation: derivation,+ titleRuleID: titleRule.id, url: url, allWorks: works, types: types,+ hostname: hostname, site: site, context: context, timestamp: stamp)+ }+ } else { Self.applyManualAssignment(to: row, at: stamp) }+ if let newTarget { try row.authorTarget(newTarget) }+ group = Self.entryGroup(id: row.id, rows: [row], canonicalWorkIDs: [:])!+ before = []+ }+ if work.rows.allSatisfy({ $0.membership(for: hostname) == nil }) {+ context.insert(WorkSiteMembership(hostname: hostname, createdAt: stamp,+ workID: work.id, work: work.representative, site: site))+ }+ let isChapter = group.carrier.authoredTarget?.kind == .chapter+ let evidence = isChapter ? EntrySourceEvidence(+ confirmed: isCorrection ? [] : fresh.evidence.map(\.binding),+ superseded: isCorrection ? fresh.evidence.map(\.binding) : []) : nil+ associations.append(.init(entryID: group.id, url: capture.rawURLString, evidence: evidence))+ if let canonical = capture.canonicalURLString, !canonical.isEmpty {+ _ = try HostnameNormalizer.fromRawURL(canonical)+ associations.append(.init(entryID: group.id, url: canonical))+ }+ try EntrySources.associateAll(associations, timestamp: stamp, context: context)+ let deliberatelyAddsChapter: Bool+ if case .newChapter = draft.intent { deliberatelyAddsChapter = true }+ else { deliberatelyAddsChapter = false }+ let learnsMultiple = deliberatelyAddsChapter && selectedID == nil && isChapter && fresh.entries.contains {+ $0.target?.kind != .note && $0.sourceURLs.contains(ExactScalarString(capture.rawURLString))+ }+ for row in work.rows {+ if learnsMultiple { row.chapterCaptureDefault = .multipleChaptersPerPage }+ if selectedID == nil { row.promoteFromToRead() }+ row.modifiedAt = stamp+ }+ try NoEpisodeWriter.recordNoteTransition(before: before,+ after: Self.noteFacts(group, calendar: noteCalendar()), context: context)+ let sources = try EntrySourceIndex(context: context).urls(for: group.id)+ if let refusal = try self.commitResolution(context: context, hostnames: [hostname], operation: "chapter capture") {+ if case .invalidated(let reason) = refusal { return .reviewRequired(fresh, reason: reason) }+ return .reviewRequired(fresh, reason: "Review the chapter capture again")+ }+ return .committed(try Self.snapshot(group, sourceURLs: sources))+ } catch {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Entry>())+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<EntrySource>())+ _ = try? context.fetch(FetchDescriptor<Site>())+ _ = try? context.fetch(FetchDescriptor<WorkSiteMembership>())+ _ = try? context.fetch(FetchDescriptor<NoEpisodeAction>())+ throw error+ }+ }+}++extension LibraryRepository {+ internal static func chapterCaptureWorkID(rawURL: String, projectedWorkID: UUID?, context: ModelContext) throws -> UUID? {+ if let projectedWorkID { return projectedWorkID }+ let index = try EntrySourceIndex(context: context)+ let candidates = Set(index.groups.values.compactMap { group -> UUID? in+ guard group.rows.allSatisfy({ $0.mergedIntoEntryID == nil }),+ index.urls(for: group.id).contains(where: { ExactScalarString($0) == ExactScalarString(rawURL) }) else { return nil }+ return group.carrier.work?.id+ })+ return candidates.count == 1 ? candidates.first : nil+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ComposedTeaching.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ComposedTeaching.swiftindex 5b8ff20c..1c68d8e8 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ComposedTeaching.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ComposedTeaching.swift@@ -702,9 +702,11 @@ extension LibraryRepository { case .sequenceName(let key): (key, .urlRule, urlCited.map { .composed(url: $0, nameTitle: titleCited) } ?? .rawURL) }- entry.entryIdentityKey = derived.key- entry.identityBasis = derived.basis- citations.identity = derived.cited+ if entry.authoredTargetData == nil {+ entry.entryIdentityKey = derived.key+ entry.identityBasis = derived.basis+ citations.identity = derived.cited+ } // Extracted Work identity (evidence), present only when the rule supplies it. if let workIdentity = derivation.workIdentity, url != nil {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swiftindex 7aa680c3..d959461e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift@@ -317,6 +317,13 @@ extension LibraryRepository { batchSize: batchSize, saveStrategy: saveStrategy, droppedThumbnails: &droppedThumbnails) + for id in appliedWorkIDs {+ if let value = payload.workCaptureDefaults[id] {+ for row in workRows[id] ?? [] where row.chapterCaptureDefault != value { row.chapterCaptureDefault = value }+ }+ }+ if !payload.workCaptureDefaults.isEmpty { try saveStrategy.save(context) }+ // The row an Entry's assignment *points* at. Every row of the group is // the same Work (Req 5.5), so one deterministic target is enough. let workTargets = workRows.compactMapValues { rows in@@ -404,11 +411,15 @@ extension LibraryRepository { } // The group's modification time, not each row's — see the // Works step above for why all-or-none is the requirement.- guard record.modifiedAt >= group.modifiedAt else { continue }+ guard record.modifiedAt >= group.modifiedAt,+ !group.rows.contains(where: { $0.mergedIntoEntryID != nil && !$0.isResolvedRedirect }),+ payload.chapterEntries[record.id] != nil || group.rows.allSatisfy({ $0.authoredTargetData == nil && $0.mergedIntoEntryID == nil })+ else { continue } let beforeNoteFacts = NoEpisodeWriter.facts( rows: group.rows, calendar: noteCalendar) for existing in group.rows { apply(record, to: existing)+ if let value = payload.chapterEntries[record.id] { applyChapterArchive(value, to: existing) } // Value-guarded (T-2334): assigning the same Site/Work // reference back still dirties a SwiftData relationship, // so compare by identity before writing.@@ -421,6 +432,7 @@ extension LibraryRepository { context: context) } else { let entry = ArchiveRecordBuilders.makeEntry(record)+ if let value = payload.chapterEntries[record.id] { applyChapterArchive(value, to: entry) } context.insert(entry) entry.site = site entry.work = work@@ -434,6 +446,9 @@ extension LibraryRepository { try saveStrategy.save(context) } + try mergeImportedEntrySources(payload.entrySources, context: context)+ if !payload.entrySources.isEmpty { try saveStrategy.save(context) }+ // (4) The named records of both kinds, their suppressions and their // coverage — after the Works and Entries they attach to, so a record's // work reference and a coverage pair's source are both already in the
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swiftindex 8c99b1e7..6b0a1b6b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift@@ -662,15 +662,18 @@ extension LibraryRepository { Place.self, PlaceSuppression.self, survivors: survivors, in: touchedWorks, context: context, timestamp: timestamp) + let sourceRows = try context.fetch(FetchDescriptor<EntrySource>())+ let retainRedirects = allRows.contains { $0.authoredTargetData != nil }+ || sourceRows.contains { set.key.memberIDs.contains($0.entryID) } for id in losers {- for row in rowsByID[id] ?? [] {- // The pointer goes before the row does. `context.delete` leaves- // the Work's `entries` inverse holding the doomed row until the- // save, and this path validates the prospective graph *before*- // saving — so the Work would fail its own inverse check on an- // Entry the resolution is in the middle of removing.- row.work = nil- context.delete(row)+ if retainRedirects, let losing = rowsByID[id],+ let group = Self.entryGroup(id: id, rows: losing, canonicalWorkIDs: [:]) {+ try EntrySources.combine(loser: group, survivorID: survivorID, timestamp: timestamp, context: context)+ } else {+ for row in rowsByID[id] ?? [] {+ row.work = nil+ context.delete(row)+ } } } try NoEpisodeWriter.recordNoteTransition(@@ -703,14 +706,27 @@ extension LibraryRepository { ) { row.note = note row.rating = content.rating+ row.authoredTargetData = content.authoredTargetData+ row.mergedIntoEntryID = content.mergedIntoEntryID+ row.mergeResolutionData = content.mergeResolutionData // The carrier's citation arms are copied whole rather than kind by kind: // the blob's arms *are* the provenance, and copying a kind without its // cited rule is a state it cannot spell (Q39). let carried = carrier.citationValues+ if content.authoredTargetData != nil {+ row.entryIdentityKey = "entry/\(row.id.uuidString.lowercased())"+ row.conservativeIdentityKey = ""+ row.identityBasis = .authoredUUID+ } else {+ row.entryIdentityKey = carrier.entryIdentityKey+ row.conservativeIdentityKey = carrier.conservativeIdentityKey+ row.identityBasis = carrier.identityBasis+ } // One decode and one encode of the survivor's blob for both arms, with // the `.manual` guards read off the value already in hand. row.editCitations { citations in+ citations.identity = content.authoredTargetData != nil ? .authoredEntryID(row.id) : carried.identity if content.chapterTitle != nil { row.chapterTitle = carrier.chapterTitle citations.chapterTitle = carried.chapterTitle@@ -854,6 +870,7 @@ extension LibraryRepository { // verdict travels in the notes it just wrote (Q41). row.publicationStateData = publicationStateData row.workStatusRaw = authoredStatusRaw+ row.chapterCaptureDefaultRaw = carrier.chapterCaptureDefaultRaw row.readingStatus = carrier.readingStatus row.verdict = carrier.verdict // V11, carrier-wins like the three above, and as a pair so a@@ -1035,7 +1052,7 @@ extension LibraryRepository { /// (Req 5.3) — so validating the carrier's primary site alone would leave /// every other site of every other member unchecked. Sorted before the /// lookup so the refusal names the same site twice over one graph.- private func commitResolution(+ internal func commitResolution( context: ModelContext, hostnames: [String], operation: String ) throws -> DuplicateResolutionOutcome? { // T-2291: scoped to `hostnames` — every site the resolution wrote to,@@ -1048,6 +1065,7 @@ extension LibraryRepository { context.rollback() _ = try? context.fetch(FetchDescriptor<Entry>()) _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<EntrySource>()) resolutionLogger.error( "Duplicate \(operation) failed validation: \(String(describing: error), privacy: .public)") return .invalidated(reason: "The resolution could not be validated: \(error)")@@ -1062,6 +1080,7 @@ extension LibraryRepository { context.rollback() _ = try? context.fetch(FetchDescriptor<Entry>()) _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<EntrySource>()) return .invalidated( reason: "The resolution produced an invalid library state: \(reason)") }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swiftindex 897c0439..4c18e7f0 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift@@ -168,7 +168,7 @@ extension LibraryRepository { entities: [ entity(Place.self), entity(PlaceSuppression.self), entity(WorkLink.self), entity(WorkCredit.self), entity(WorkDistinctPair.self),- entity(NoEpisodeAction.self),+ entity(NoEpisodeAction.self), entity(EntrySource.self), ]), EmptyLibraryPhase(name: "5 works", entities: [entity(Work.self)]), EmptyLibraryPhase(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryCorrection.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryCorrection.swiftnew file mode 100644index 00000000..5e230686--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryCorrection.swift@@ -0,0 +1,119 @@+import Foundation+import SwiftData++public struct EntryCorrectionContract: Sendable, Equatable {+ public let entryID: UUID+ public let destinationID: UUID?+ public let source: EntryAuthoredContent+ public let destination: EntryAuthoredContent?+ public let sourceModifiedAt: Date+ public let destinationModifiedAt: Date?+ public var needsContentChoice: Bool {+ guard let destination else { return false }+ return !source.note.isEmpty && !destination.note.isEmpty && source.note != destination.note+ || source.rating != nil && destination.rating != nil && source.rating != destination.rating+ }+}++public enum EntryCorrectionContentChoice: String, Sendable { case source, destination }+public enum EntryCorrectionOutcome: Sendable, Equatable {+ case committed(entryID: UUID)+ case reviewRequired(reason: String)+}++extension LibraryRepository {+ public func projectEntryCorrection(entryID: UUID, destinationID: UUID? = nil) async throws -> EntryCorrectionContract {+ try await withLockedContext(mode: .shared, operation: "reviewing chapter correction") { context in+ let source = try Self.fetchNormalisedEntryGroup(id: entryID, context: context)+ let destination = try destinationID.map { try Self.fetchNormalisedEntryGroup(id: $0, context: context) }+ guard !source.isTorn, destination?.isTorn != true else {+ throw LibraryRepositoryError.invalidInput(operation: "chapter correction", reason: "Review differing copies before correcting this chapter")+ }+ guard destinationID != entryID else {+ throw LibraryRepositoryError.invalidInput(operation: "chapter correction", reason: "Choose another chapter")+ }+ if let destination {+ guard source.carrier.work?.id == destination.carrier.work?.id,+ source.carrier.work != nil else {+ throw LibraryRepositoryError.invalidInput(operation: "chapter correction", reason: "Choose a chapter in the same work")+ }+ }+ return EntryCorrectionContract(entryID: entryID, destinationID: destinationID,+ source: source.presentedContent, destination: destination?.presentedContent,+ sourceModifiedAt: source.modifiedAt, destinationModifiedAt: destination?.modifiedAt)+ }+ }++ /// Applies one reviewed correction. A refusal never reloads or discards the caller's draft.+ public func commitEntryCorrection(_ contract: EntryCorrectionContract, target: AuthoredEntryTarget,+ contentChoice: EntryCorrectionContentChoice? = nil) async throws -> EntryCorrectionOutcome {+ try await withLockedContext(mode: .exclusive, operation: "saving chapter correction") { context in+ let source = try Self.fetchNormalisedEntryGroup(id: contract.entryID, context: context)+ let destination = try contract.destinationID.map { try Self.fetchNormalisedEntryGroup(id: $0, context: context) }+ guard !source.isTorn, source.presentedContent == contract.source,+ source.modifiedAt == contract.sourceModifiedAt,+ destination?.isTorn != true, destination?.presentedContent == contract.destination,+ destination?.modifiedAt == contract.destinationModifiedAt else {+ return .reviewRequired(reason: "The chapter changed. Review the correction again")+ }+ if contract.needsContentChoice && contentChoice == nil {+ return .reviewRequired(reason: "Choose which note and rating to keep")+ }+ if let destination {+ guard source.carrier.work?.id == destination.carrier.work?.id,+ source.carrier.work != nil,+ destination.rows.allSatisfy({ $0.mergedIntoEntryID == nil }) else {+ return .reviewRequired(reason: "The destination chapter changed")+ }+ }+ let stamp = clock.now()+ let before = Self.noteFacts(source, calendar: self.noteCalendar())+ .union(destination.map { Self.noteFacts($0, calendar: self.noteCalendar()) } ?? [])+ do {+ try EntrySources.supersedeLegacyEvidence(of: source, timestamp: stamp, context: context)+ if let destination {+ let chosen = contentChoice == .source ? source.presentedContent : destination.presentedContent+ let legacySources = destination.rows.filter { $0.authoredTargetData == nil && !$0.rawURLString.isEmpty }.map {+ EntrySources.Association(entryID: $0.id, url: $0.rawURLString, evidence: .init(confirmed: EntrySources.legacyBindings(of: $0)))+ }+ try EntrySources.associateAll(legacySources, timestamp: stamp, context: context)+ for row in destination.rows {+ row.note = contentChoice != nil ? chosen.note : (chosen.note.isEmpty ? source.carrier.note : chosen.note)+ row.rating = contentChoice != nil ? chosen.rating : (chosen.rating ?? source.carrier.rating)+ row.modifiedAt = stamp+ // Preserve the destination identity and its label, authoring a legacy target once.+ if row.authoredTargetData == nil {+ try row.authorTarget(AuthoredEntryTarget(kind: .chapter, title: row.chapterTitle,+ designation: row.chapterSequence))+ }+ }+ try EntrySources.combine(loser: source, survivorID: destination.id, timestamp: stamp, context: context)+ } else {+ for row in source.rows {+ try row.authorTarget(target)+ row.mergedIntoEntryID = nil+ row.mergeResolutionData = nil+ row.modifiedAt = stamp+ }+ }+ try NoEpisodeWriter.recordNoteTransition(before: before,+ after: Self.noteFacts(destination ?? source, calendar: self.noteCalendar()), context: context)+ let hostnames = source.rows.map(\.hostname) + (destination?.rows.map(\.hostname) ?? [])+ if let refusal = try self.commitResolution(context: context, hostnames: hostnames, operation: "chapter correction") {+ switch refusal {+ case .invalidated(let reason): return .reviewRequired(reason: reason)+ default: return .reviewRequired(reason: "Review the correction again")+ }+ }+ } catch {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Entry>())+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<EntrySource>())+ _ = try? context.fetch(FetchDescriptor<NoEpisodeAction>())+ throw error+ }+ return .committed(entryID: destination?.id ?? source.id)+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swiftindex 9d418acb..d92a10bf 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Export.swift@@ -21,7 +21,12 @@ extension LibraryRepository { // Normalised from the store for the same reason every other // single-record read is: this and Recent must agree about which // content the record presents (Req 3.2).- let group = try Self.fetchNormalisedEntryGroup(id: entryID, context: context)+ let addressed = try Self.fetchNormalisedEntryGroup(id: entryID, context: context)+ let index = try EntrySourceIndex(context: context)+ let group: EntryGroup+ if let destination = index.destination(of: entryID, requireResolvedContent: true), !index.hasUnresolvedContent(for: destination) {+ group = try Self.fetchNormalisedEntryGroup(id: destination, context: context)+ } else { group = addressed } var sites = SiteLookupCache() return try Self.exportInput( for: Self.snapshot(group), includingWork: true, sites: &sites,@@ -173,6 +178,11 @@ extension LibraryRepository { private var cache: [String: [Site]] = [:] private var types: WorkTypeDirectory? private var works: [UUID: WorkLine] = [:]+ private var sourceIndex: EntrySourceIndex?+ mutating func sourceURLs(entryID: UUID, context: ModelContext) throws -> [String] {+ if sourceIndex == nil { sourceIndex = try EntrySourceIndex(context: context) }+ return sourceIndex!.urls(for: entryID)+ } private enum WorkLine { case missing@@ -248,7 +258,11 @@ extension LibraryRepository { // The chapter title where there is one, the cleaned capture title // otherwise (Req 1.2) — the same `presentationTitle` path Recent and // Entry detail display through.- let heading = try entry.chapterTitle+ let authoredHeading = entry.authoredTarget.map { target in+ target.kind == .note ? (target.title ?? "Note") : (target.title ?? target.designation ?? "Chapter")+ }+ let heading = try authoredHeading+ ?? entry.chapterTitle ?? displayTitle( for: entry.captureTitle, hostname: entry.hostname, sites: &sites, context: context) @@ -265,14 +279,17 @@ extension LibraryRepository { workTypeLabel = work?.typeLabel } + let links = try sites.sourceURLs(entryID: entry.id, context: context)+ let primary = entry.rawURLString.isEmpty ? links.first ?? "" : entry.rawURLString+ let additional = links.filter { ExactScalarString($0) != ExactScalarString(primary) } return EntryExportInput( headingText: heading,- rawURLString: entry.rawURLString,+ rawURLString: primary, workTitle: workTitle, workTypeLabel: workTypeLabel, dateText: exportDateText(entry.firstCapturedAt, locale: locale, calendar: calendar), rating: entry.rating,- note: entry.note)+ note: entry.note, additionalSourceURLs: additional) } /// The title a surface shows for a capture title on this hostname — the
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swiftindex c16b7942..211b49b2 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift@@ -71,7 +71,8 @@ public struct EntryGroup { /// anything that can fail, and snapshotting every group to place it would /// let one corrupt row take the whole cast down with it. internal var placementInputs: (chapterSequence: String?, chapterTitle: String?) {- (representative.chapterSequence, carrier.chapterTitle)+ (carrier.authoredTargetData == nil ? representative.chapterSequence : carrier.effectiveChapterSequence,+ carrier.effectiveChapterTitle) } /// Member timestamps (Definitions): the earliest first capture, the latest@@ -255,13 +256,18 @@ extension LibraryRepository { /// bulk write paths (Q69, Decision 9): a map to one row per UUID cannot /// express "write every row", and a derived-field write has to (Req 2.7). internal static func entryGroups(- _ rows: [Entry], canonicalWorkIDs: [UUID: UUID]+ _ rows: [Entry], canonicalWorkIDs: [UUID: UUID], includeResolvedRedirects: Bool = false ) -> [UUID: EntryGroup] { var buckets: [UUID: [Entry]] = [:] for row in rows { buckets[row.id, default: []].append(row) }- return buckets.compactMapValues { rows in+ let groups = buckets.compactMapValues { rows in entryGroup(id: rows[0].id, rows: rows, canonicalWorkIDs: canonicalWorkIDs) }+ guard !includeResolvedRedirects else { return groups }+ return groups.filter { id, group in+ guard group.rows.contains(where: { $0.mergedIntoEntryID != nil }) else { return true }+ return EntrySourceIndex.destination(of: id, groups: groups, requireResolvedContent: true) == nil+ } } /// The rows as one story-position input per logical entry@@ -288,12 +294,16 @@ extension LibraryRepository { buckets: [UUID: [Entry]] ) -> [StoryPositionIndex.EntryInput] { buckets.compactMap { id, rows in+ if rows.allSatisfy({ $0.mergedIntoEntryID != nil && $0.isResolvedRedirect }) { return nil }+ if rows.contains(where: { $0.mergedIntoEntryID != nil }) {+ return StoryPositionIndex.EntryInput(id: id, placement: nil, firstCapturedAt: rows.map(\.firstCapturedAt).min()!)+ } guard rows.count > 1 else { let row = rows[0] return StoryPositionIndex.EntryInput( id: id, placement: ChapterPlacement.of(- chapterSequence: row.chapterSequence, chapterTitle: row.chapterTitle),+ chapterSequence: row.effectiveChapterSequence, chapterTitle: row.effectiveChapterTitle), firstCapturedAt: row.firstCapturedAt) } guard let group = entryGroup(id: id, rows: rows, canonicalWorkIDs: [:]) else {@@ -342,8 +352,8 @@ extension LibraryRepository { /// Never a winner row's content (Q41). A mixed group whose bare row happens /// to represent would otherwise present an empty note over the variant the /// reader actually wrote, and an ordinary edit would fan out across it.- internal static func snapshot(_ group: EntryGroup) throws -> EntrySnapshot {- let base = try snapshot(group.representative)+ internal static func snapshot(_ group: EntryGroup, sourceURLs: [String] = []) throws -> EntrySnapshot {+ let base = try snapshot(group.representative, sourceURLs: sourceURLs) guard group.isSplit else { return base } let carried = try snapshot(group.carrier) return EntrySnapshot(@@ -353,8 +363,8 @@ extension LibraryRepository { rawURLString: base.rawURLString, canonicalURLString: base.canonicalURLString, hostname: base.hostname,- entryIdentityKey: base.entryIdentityKey,- identityKeyVersion: base.identityKeyVersion,+ entryIdentityKey: group.carrier.authoredTargetData == nil ? base.entryIdentityKey : carried.entryIdentityKey,+ identityKeyVersion: group.carrier.authoredTargetData == nil ? base.identityKeyVersion : carried.identityKeyVersion, chapterTitle: carried.chapterTitle, chapterTitleProvenance: carried.chapterTitleProvenance, note: carried.note,@@ -365,8 +375,11 @@ extension LibraryRepository { workID: carried.workID, workAssignmentProvenance: carried.workAssignmentProvenance, intentionallyUnattached: carried.intentionallyUnattached,- chapterSequence: base.chapterSequence,- conservativeIdentityKey: base.conservativeIdentityKey)+ chapterSequence: group.carrier.authoredTargetData == nil ? base.chapterSequence : carried.chapterSequence,+ conservativeIdentityKey: group.carrier.authoredTargetData == nil ? base.conservativeIdentityKey : carried.conservativeIdentityKey,+ authoredTarget: carried.authoredTarget,+ changesAfterCombine: group.rows.contains { $0.mergedIntoEntryID != nil && !$0.isResolvedRedirect },+ sourceURLs: sourceURLs) } /// The Work counterpart. Its Entries are the union across **every** row,@@ -429,7 +442,8 @@ extension LibraryRepository { credits: base.credits, thumbnail: base.thumbnail, releaseDays: base.releaseDays, releaseDaysRaw: base.releaseDaysRaw,- catchUp: catchUp, noEpisodeHistory: history, publicationState: base.publicationState)+ catchUp: catchUp, noEpisodeHistory: history, publicationState: base.publicationState,+ chapterCaptureDefault: base.chapterCaptureDefault) } // 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@@ -486,6 +500,7 @@ extension LibraryRepository { // section, presenting the days of the row whose content it presents. releaseDays: carried.releaseDays, releaseDaysRaw: carried.releaseDaysRaw,- catchUp: catchUp, noEpisodeHistory: history, publicationState: carried.publicationState)+ catchUp: catchUp, noEpisodeHistory: history, publicationState: carried.publicationState,+ chapterCaptureDefault: carried.chapterCaptureDefault) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ManualEntry.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ManualEntry.swiftnew file mode 100644index 00000000..4426a487--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ManualEntry.swift@@ -0,0 +1,109 @@+import Foundation+import SwiftData++/// A manual reaction is reader-owned content, with optional presentation and source.+public struct ManualEntryDraft: Equatable, Sendable {+ public let target: AuthoredEntryTarget+ public let sourceURL: String?+ public let note: String+ public let rating: Rating?+ public let existingEntryID: UUID?+ public let confirmedNewChapter: Bool+ public init(target: AuthoredEntryTarget = .init(kind: .note), sourceURL: String? = nil,+ note: String = "", rating: Rating? = nil, existingEntryID: UUID? = nil,+ confirmedNewChapter: Bool = false) {+ self.target = target; self.sourceURL = sourceURL; self.note = note; self.rating = rating+ self.existingEntryID = existingEntryID; self.confirmedNewChapter = confirmedNewChapter+ }+}++extension LibraryRepository {+ public func projectManualEntry(workID: UUID) async throws -> ChapterCaptureProjection {+ try await withLockedContext(mode: .shared, operation: "reviewing manual note") { context in+ try self.chapterCaptureProjection(rawURL: "", captureTitle: nil, hostname: "", workID: workID, context: context)+ }+ }+ public func commitManualEntry(projection: ChapterCaptureProjection, draft: ManualEntryDraft) async throws -> ChapterCaptureCommitOutcome {+ guard !draft.note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || draft.rating != nil else {+ throw LibraryRepositoryError.invalidInput(operation: "saving manual note", reason: "Add a note or rating")+ }+ let source = draft.sourceURL?.trimmingCharacters(in: .whitespacesAndNewlines)+ if let source, !source.isEmpty { _ = try HostnameNormalizer.fromRawURL(source) }+ guard let workID = projection.workID else {+ throw LibraryRepositoryError.invalidInput(operation: "saving manual note", reason: "Choose a work")+ }+ return try await withLockedContext(mode: .exclusive, operation: "saving manual note") { context in+ let fresh = try self.chapterCaptureProjection(rawURL: "", captureTitle: nil, hostname: "", workID: workID, context: context)+ guard fresh == projection else { return .reviewRequired(fresh, reason: "The work or entry changed. Review your note again") }+ let work = try Self.fetchWorkGroup(id: workID, context: context)+ guard !work.isTorn else { return .reviewRequired(fresh, reason: "Resolve this work's differing copies first") }+ let chosen: EntryGroup?+ if let id = draft.existingEntryID {+ guard let entry = fresh.entries.first(where: { $0.id == id }), !entry.requiresReview,+ entry.target?.kind == draft.target.kind || (entry.target == nil && draft.target.kind == .chapter) else {+ return .reviewRequired(fresh, reason: "Choose an existing entry of the appropriate kind")+ }+ chosen = try Self.fetchNormalisedEntryGroup(id: id, context: context)+ } else {+ let chapters = fresh.entries.filter { $0.target?.kind != .note }+ if draft.target.kind == .chapter && !chapters.isEmpty && !draft.confirmedNewChapter {+ return .reviewRequired(fresh, reason: "Choose an existing chapter or confirm a new one")+ }+ if draft.target.kind == .chapter, let designation = draft.target.designation,+ chapters.contains(where: { $0.target?.designation.map(ExactScalarString.init) == ExactScalarString(designation) }) {+ return .reviewRequired(fresh, reason: "A chapter already has that designation. Choose it or change the designation")+ }+ chosen = nil+ }+ do {+ let stamp = MillisecondInstant.quantize(self.clock.now())+ let group: EntryGroup+ let before: Set<NoEpisodeWriter.NoteFact>+ if let chosen {+ group = chosen+ before = Self.noteFacts(chosen, calendar: self.noteCalendar())+ let legacySources = chosen.rows.filter { $0.authoredTargetData == nil && !$0.rawURLString.isEmpty }.map {+ EntrySources.Association(entryID: $0.id, url: $0.rawURLString, evidence: .init(confirmed: EntrySources.legacyBindings(of: $0)))+ }+ try EntrySources.associateAll(legacySources, timestamp: stamp, context: context)+ for row in chosen.rows {+ if row.authoredTargetData == nil {+ try row.authorTarget(.init(kind: draft.target.kind,+ title: row.effectiveChapterTitle, designation: row.effectiveChapterSequence))+ }+ row.note = draft.note; row.rating = draft.rating; row.modifiedAt = stamp+ }+ } else {+ let row = Entry(captureTitle: "", captureTitleSource: .manual, rawURLString: "",+ hostname: "", entryIdentityKey: "", timestamp: stamp, note: draft.note, rating: draft.rating)+ try row.authorTarget(draft.target)+ context.insert(row)+ row.work = work.representative+ Self.applyManualAssignment(to: row, at: stamp)+ group = Self.entryGroup(id: row.id, rows: [row], canonicalWorkIDs: [:])!+ before = []+ }+ if let source, !source.isEmpty {+ try EntrySources.associate(entryID: group.id, url: source, timestamp: stamp, context: context)+ }+ for row in work.rows { row.promoteFromToRead(); row.modifiedAt = stamp }+ try LibraryValidator.validateEntryTuple(entry: group.carrier, works: work.rows)+ try NoEpisodeWriter.recordNoteTransition(before: before,+ after: Self.noteFacts(group, calendar: self.noteCalendar()), context: context)+ let sources = try EntrySourceIndex(context: context).urls(for: group.id)+ if let refusal = try self.commitResolution(context: context, hostnames: [], operation: "manual note") {+ if case .invalidated(let reason) = refusal { return .reviewRequired(fresh, reason: reason) }+ return .reviewRequired(fresh, reason: "Review your manual note again")+ }+ return .committed(try Self.snapshot(group, sourceURLs: sources))+ } catch {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Entry>())+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<EntrySource>())+ _ = try? context.fetch(FetchDescriptor<NoEpisodeAction>())+ throw error+ }+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swiftindex 00df9796..ee45ac4a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift@@ -140,7 +140,7 @@ extension LibraryRepository { // capture an uncovered revision for ever. let noted = group.rows .flatMap { $0.entryValues }- .filter { !$0.note.isEmpty }+ .filter { !$0.note.isEmpty && !($0.mergedIntoEntryID != nil && $0.isResolvedRedirect) } var seen: Set<UUID> = [] for entry in noted.sorted(by: { $0.firstCapturedAt < $1.firstCapturedAt }) where seen.insert(entry.id).inserted {@@ -366,7 +366,9 @@ extension LibraryRepository { ) -> Int { guard !works.isEmpty else { return 0 } var written = 0- let entriesByID = Dictionary(grouping: works.flatMap { $0.entryValues }, by: \.id)+ let entriesByID = Dictionary(grouping: works.flatMap { $0.entryValues }.filter {+ !($0.mergedIntoEntryID != nil && $0.isResolvedRedirect)+ }, by: \.id) for source in sources { switch source.ref { case .genericNotes:@@ -587,6 +589,7 @@ extension LibraryRepository { // dangling citation a tolerated state, and refusing the acceptance // would make routine curation look like a conflict. guard !entries.isEmpty else { return true }+ if entries.allSatisfy({ $0.mergedIntoEntryID != nil && $0.isResolvedRedirect }) { return false } return entries.contains { CharacterCoverageFingerprint.of($0.note) == source.fingerprint }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swiftindex 0c62e48b..d7508f4b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Redirect.swift@@ -113,6 +113,16 @@ extension LibraryRepository { // whether a reader's edit applies or is refused, and it has to agree // with the screen the reader was looking at when they made it. if let group = try? Self.fetchNormalisedEntryGroup(id: id, context: context) {+ if group.rows.contains(where: { $0.mergedIntoEntryID != nil }) {+ let index = try EntrySourceIndex(context: context)+ guard let destinationID = index.destination(of: id, requireResolvedContent: true),+ !index.hasUnresolvedContent(for: destinationID),+ let destination = index.groups[destinationID],+ !destination.isTorn,+ (matches ?? basis.matches)(destination.presentedContent) || destination.presentedContent.isBare+ else { return .refused(.recordChanged(recordID: id)) }+ return .resolved(destination)+ } return .resolved(group) } @@ -361,5 +371,6 @@ extension WorkEditBasis { // construction and `WorkAuthoredContent` does the same — so two rows // toggled in different orders are not a divergence (Req 7.5). && content.releaseDays == releaseDays+ && content.chapterCaptureDefaultRaw == chapterCaptureDefault.rawValue } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swiftindex 888820c3..57ae73ec 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift@@ -255,7 +255,13 @@ extension LibraryRepository { note: note, rating: rating ) let outcome = Self.computeCaptureOutcome(basis: basis, request: request)- return CaptureContract(basis: basis, request: request, outcome: outcome)+ let workID = try Self.chapterCaptureWorkID(rawURL: rawURLString,+ projectedWorkID: outcome.projectedWorkID, context: context)+ let chapters = try workID.map {+ try self.chapterCaptureProjection(rawURL: rawURLString, captureTitle: captureTitle,+ hostname: hostname, workID: $0, context: context)+ }+ return CaptureContract(basis: basis, request: request.withChapterProjection(chapters), outcome: outcome) } } @@ -279,10 +285,51 @@ extension LibraryRepository { // 3. Compare — if stale, return refreshed (zero writes) if currentBasis != contract.basis || currentOutcome != contract.outcome {- let freshContract = CaptureContract(basis: currentBasis, request: contract.request, outcome: currentOutcome)+ let workID = contract.request.chapterIntent == .automatic+ ? try Self.chapterCaptureWorkID(rawURL: contract.request.rawURLString,+ projectedWorkID: currentOutcome.projectedWorkID, context: context)+ : contract.request.chapterProjection?.workID+ let chapters = try workID.map {+ try self.chapterCaptureProjection(rawURL: contract.request.rawURLString,+ captureTitle: contract.request.captureTitle, hostname: validated.hostname,+ workID: $0, context: context)+ }+ let freshContract = CaptureContract(basis: currentBasis,+ request: contract.request.withChapterProjection(chapters, intent: contract.request.chapterIntent),+ outcome: currentOutcome) return .refreshed(freshContract) } + if let prior = contract.request.chapterProjection,+ contract.request.chapterIntent == .automatic && prior.resolution == .newEntry,+ let workID = prior.workID {+ let fresh = try self.chapterCaptureProjection(rawURL: contract.request.rawURLString,+ captureTitle: contract.request.captureTitle, hostname: validated.hostname,+ workID: workID, context: context)+ guard fresh == prior else {+ return .refreshed(CaptureContract(basis: currentBasis,+ request: contract.request.withChapterProjection(fresh, intent: .automatic), outcome: currentOutcome))+ }+ }+ if let chapters = contract.request.chapterProjection,+ !(contract.request.chapterIntent == .automatic && chapters.resolution == .newEntry) {+ let draft = ChapterCaptureDraft(projection: chapters,+ capture: CaptureDraft(captureTitle: contract.request.captureTitle,+ captureTitleSource: contract.request.captureTitleSource,+ rawURLString: contract.request.rawURLString,+ canonicalURLString: contract.request.canonicalURLString,+ note: contract.request.note, rating: contract.request.rating),+ intent: contract.request.chapterIntent,+ entryID: contract.request.entryID, capturedAt: contract.request.capturedAt)+ switch try self.applyChapterCapture(draft, hostname: validated.hostname, context: context) {+ case .committed(let entry): return .committed(entry)+ case .reviewRequired(let projection, _):+ return .refreshed(CaptureContract(basis: currentBasis,+ request: contract.request.withChapterProjection(projection, intent: contract.request.chapterIntent),+ outcome: currentOutcome))+ }+ }+ // 4. Lookup-to-commit race guard (Q27): a lookup-first `.new` capture // carries the candidate keys; if a matching Entry appeared since the // lookup, return its disposition instead of inserting a duplicate.@@ -405,6 +452,9 @@ extension LibraryRepository { } } + // Ordinary distinct-page capture keeps the established identity+ // bucket. Explicit/same-page chapters use the authored target path.+ // Validate the written tuple only (Req 6.5, Q9): no full-graph pass. // Cited ids resolve among what `entry.site` owns (Req 3.2) — the // row assigned above, which is also where every id the commit just@@ -446,7 +496,7 @@ extension LibraryRepository { } /// Applies a composed capture assignment to a single new Entry (Req 6.2).- private static func applyCaptureAssignment(+ internal static func applyCaptureAssignment( to entry: Entry, citations: inout EntryCitations, assignment: ComposedAssignmentProjection?, derivation: ComposedDerivation, titleRuleID: UUID, url: (id: UUID, definition: URLRuleDefinition)?,@@ -527,7 +577,7 @@ extension LibraryRepository { // MARK: - Capture basis builder - private func buildCaptureBasis(hostname: String, context: ModelContext) throws -> CaptureBasis {+ internal func buildCaptureBasis(hostname: String, context: ModelContext) throws -> CaptureBasis { // Hostname lookup, kept deliberately (Req 3.3, task 16): a capture is // projected from a raw URL before any Entry exists, so a hostname is // all there is to resolve — this is one of the two moments Q8 preserves.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swiftindex 6070c11c..b4a437c7 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift@@ -149,7 +149,8 @@ extension LibraryRepository { // and leads; duplication is informational, and the app repairs it // on its own. let siteAttention: RecentRowAttention? =- if site == nil { .siteMissing }+ if entry.authoredTarget != nil { missingWork ? .workMissing : nil }+ else if site == nil { .siteMissing } else if mode == nil { .siteRulesInvalid } else if isDuplicatedHostname { .siteDuplicated } else if missingWork { .workMissing }@@ -218,7 +219,7 @@ extension LibraryRepository { hostname: entry.hostname, workDisplayTitle: workDisplayTitle, // Sequence-only chapters present their sequence (Req 8.12).- chapterTitle: entry.chapterTitle ?? entry.chapterSequence,+ chapterTitle: entry.authoredNoteTitle ?? entry.chapterTitle ?? entry.chapterSequence, unresolvedCandidateTitle: replay.candidateTitle, siteMode: mode, isActionable: actionable,@@ -410,7 +411,8 @@ extension LibraryRepository { } private static func isRecentEntryActionable(_ entry: EntrySnapshot) -> Bool {- ActionabilityEvaluator.isActionable(+ guard entry.authoredTarget == nil else { return false }+ return ActionabilityEvaluator.isActionable( chapterTitle: entry.chapterTitle, chapterSequence: entry.chapterSequence, chapterProvenance: entry.chapterTitleProvenance,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDeletion.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDeletion.swiftindex 560c4d97..1c9113c8 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDeletion.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDeletion.swift@@ -28,17 +28,22 @@ public struct WorkDeletionContract: Sendable, Equatable { /// detaches, and what the dialog's count names (Q28). Groups shared with a /// duplicate-set sibling are not here: they are repointed (Q25). public let entryGroupIDs: Set<UUID>+ /// Hidden clean redirect groups are still owned physical records. They+ /// participate in freshness/cascade checks without inflating the note count.+ public let retainedEntryGroupIDs: Set<UUID> /// The owned groups whose rows disagree about something the reader wrote, /// with the variants the disclosure has to show (Req 7.2). public let tornEntryVariants: [UUID: [AuthoredVariant<EntryAuthoredContent>]] public init( basis: WorkEditBasis, workID: UUID, entryGroupIDs: Set<UUID>,- tornEntryVariants: [UUID: [AuthoredVariant<EntryAuthoredContent>]]+ tornEntryVariants: [UUID: [AuthoredVariant<EntryAuthoredContent>]],+ retainedEntryGroupIDs: Set<UUID> = [] ) { self.basis = basis self.workID = workID self.entryGroupIDs = entryGroupIDs+ self.retainedEntryGroupIDs = retainedEntryGroupIDs self.tornEntryVariants = tornEntryVariants } @@ -112,7 +117,8 @@ extension LibraryRepository { let (fresh, owned, shared) = try Self.workDeletionContract( for: group, context: context) guard fresh.basis == contract.basis,- fresh.entryGroupIDs == contract.entryGroupIDs+ fresh.entryGroupIDs == contract.entryGroupIDs,+ fresh.retainedEntryGroupIDs == contract.retainedEntryGroupIDs else { workDeletionLogger.debug("Work deletion detected stale state; refreshing") return .refreshed(fresh)@@ -138,6 +144,17 @@ extension LibraryRepository { let timestamp = MillisecondInstant.quantize(self.clock.now()) let noteCalendar = self.noteCalendar() + var didSave = false+ defer {+ if !didSave {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Entry>())+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<EntrySource>())+ _ = try? context.fetch(FetchDescriptor<NoEpisodeAction>())+ }+ }+ // 5. Shared groups are repointed, not deleted (Q25). Relying on // SwiftData's nullify would tear the group: a nil assignment never // normalises against the sibling's manual one, so the group would@@ -149,7 +166,11 @@ extension LibraryRepository { guard let survivor = entryGroup.rows.compactMap(\.work) .first(where: { $0.id != group.id }) else { continue }- for row in entryGroup.rows where row.work?.id == group.id { row.work = survivor }+ for row in entryGroup.rows where row.work?.id == group.id {+ let wasResolved = row.isResolvedRedirect+ row.work = survivor+ row.refreshAcceptedMergeAssignment(wasResolved: wasResolved)+ } try NoEpisodeWriter.recordNoteTransition( before: before, after: Self.noteFacts(entryGroup, calendar: noteCalendar), context: context)@@ -160,6 +181,7 @@ extension LibraryRepository { for entryGroup in owned { switch disposition { case .deleteEntries:+ try EntrySources.delete(ownedBy: [entryGroup.id], context: context) for row in entryGroup.rows { context.delete(row) } case .detachEntries: // Exactly `moveEntry`'s "Leave unattached" block (Q22) —@@ -167,9 +189,11 @@ extension LibraryRepository { // re-parse guarantee holds by the tests that already cover // it: no later re-parse reattaches these. for row in entryGroup.rows {+ let wasResolved = row.isResolvedRedirect row.work = nil row.intentionallyUnattached = true LibraryRepository.applyManualAssignment(to: row, at: timestamp)+ row.refreshAcceptedMergeAssignment(wasResolved: wasResolved) } } }@@ -295,6 +319,7 @@ extension LibraryRepository { self.recordPostCommitDiagnosis(diagnoses[hostname], hostname: hostname) } workDeletionLogger.debug("Deleted Work \(group.id.uuidString)")+ didSave = true return .committed } }@@ -322,11 +347,16 @@ extension LibraryRepository { for entryGroup in owned where entryGroup.isTorn { torn[entryGroup.id] = entryGroup.variants }+ let index = try EntrySourceIndex(context: context)+ let retained = Set(owned.filter {+ $0.rows.contains { $0.mergedIntoEntryID != nil }+ && index.destination(of: $0.id, requireResolvedContent: true) != nil+ }.map(\.id)) let contract = WorkDeletionContract( basis: WorkEditBasis(work: snapshot), workID: group.id,- entryGroupIDs: Set(owned.map(\.id)),- tornEntryVariants: torn)+ entryGroupIDs: Set(owned.map(\.id)).subtracting(retained),+ tornEntryVariants: torn, retainedEntryGroupIDs: retained) return (contract, owned, shared) } @@ -349,7 +379,8 @@ extension LibraryRepository { let rows = try context.fetch(FetchDescriptor<Entry>()) .filter { candidateIDs.contains($0.id) } let groups = entryGroups(- rows, canonicalWorkIDs: try canonicalWorkIDs(normalising: rows, context: context))+ rows, canonicalWorkIDs: try canonicalWorkIDs(normalising: rows, context: context),+ includeResolvedRedirects: true) var owned: [EntryGroup] = [] var shared: [EntryGroup] = []
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swiftindex ad9a9225..8fdad81e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift@@ -195,7 +195,7 @@ extension LibraryRepository { // resolve it: the chapter title, else the URL-rule-derived // sequence — a chapter the rule numbered but did not name is // still a parsed chapter — else the cleaned capture title.- let displayTitle = try entry.chapterTitle ?? entry.chapterSequence+ let displayTitle = try entry.authoredNoteTitle ?? entry.chapterTitle ?? entry.chapterSequence ?? Self.displayTitle( for: entry.captureTitle, hostname: entry.hostname, sites: &sites, context: context)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swiftindex 0d6c7e27..0283161d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift@@ -22,8 +22,17 @@ extension LibraryRepository { request: WorkURLRequest ) async throws -> WorkURLContract { try await withLockedContext(mode: .shared, operation: "projecting Work URL") { context in+ let selectedHostname: String+ if hostname.isEmpty {+ let value: String+ switch request {+ case .replaceManual(let url), .confirmCandidate(let url): value = url+ case .clear: value = ""+ }+ selectedHostname = try HostnameNormalizer.fromRawURL(value)+ } else { selectedHostname = hostname } let basis = try Self.buildWorkURLBasis(- workID: workID, hostname: hostname, context: context)+ workID: workID, hostname: selectedHostname, context: context) do { let outcome = try WorkURLPlanner.project(basis: basis, request: request) workMergeLogger.debug("Projected Work URL operation for Work \(workID.uuidString)")@@ -105,6 +114,21 @@ extension LibraryRepository { reason: "That Work URL is not on \(hostname).") } let urlTimestamp = self.clock.now()+ if contract.basis.membershipID == nil, contract.outcome.resultingURL != nil {+ do {+ let site = try Self.siteForWrite(hostname: hostname, context: context)+ for row in group.rows {+ context.insert(WorkSiteMembership(hostname: hostname, createdAt: urlTimestamp,+ workID: group.id, work: row, site: site))+ }+ } catch {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<Site>())+ _ = try? context.fetch(FetchDescriptor<WorkSiteMembership>())+ throw error+ }+ } for row in group.rows { // The address lands on the row's membership for this hostname // (Req 3.6): the Work's other sites keep theirs. A row of a split@@ -162,6 +186,10 @@ extension LibraryRepository { do { try self.saveStrategy.save(context) } catch {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<Site>())+ _ = try? context.fetch(FetchDescriptor<WorkSiteMembership>()) throw LibraryRepositoryError.libraryUnavailable( operation: "atomically saving confirmed Work URL", reason: String(describing: error)@@ -499,7 +527,9 @@ extension LibraryRepository { // A to-one relationship has no other shape (Q80): the pointer // names one row, and every row of the target group is the same // Work.+ let wasResolved = entry.isResolvedRedirect entry.work = target+ entry.refreshAcceptedMergeAssignment(wasResolved: wasResolved) entry.modifiedAt = timestamp } let afterNoteFacts = Set(sourceEntries.compactMap { entry -> NoEpisodeWriter.NoteFact? in@@ -1083,6 +1113,12 @@ extension LibraryRepository { throw LibraryRepositoryError.unresolvedDuplicate(type: "Work", id: workID) } let work = group.representative+ if group.rows.allSatisfy({ $0.membershipValues.isEmpty }) {+ return try WorkURLBasis(workID: group.id, membershipID: nil,+ siteHostname: ExactScalarString(hostname), identity: .none, currentRule: nil,+ entries: [], priorWorkURL: nil, siteFreeWorkContent: group.presentedContent,+ siteFreeWorkModifiedAt: group.modifiedAt)+ } let membership = try workURLMembership(of: group, hostname: hostname) let siteRules = try rules(for: membership, context: context) let identity = identitySnapshot(of: membership, rules: siteRules)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex eab06b51..12c97413 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -17,16 +17,18 @@ public struct LibraryRecordCounts: Equatable, Sendable { /// no type list, fixtures that count four kinds — keep compiling and keep /// meaning zero. public let workTypes: Int+ public let entrySources: Int public init( entries: Int, works: Int, sites: Int, titlePatterns: Int,- urlRulePatterns: Int = 0, workTypes: Int = 0+ urlRulePatterns: Int = 0, workTypes: Int = 0, entrySources: Int = 0 ) { self.entries = entries self.works = works self.sites = sites self.titlePatterns = titlePatterns self.urlRulePatterns = urlRulePatterns+ self.entrySources = entrySources self.workTypes = workTypes } @@ -42,7 +44,7 @@ public struct LibraryRecordCounts: Equatable, Sendable { /// creation-and-marker repair that Decision 2 of `retire-migration-chain` /// exists to keep open. public var holdsNoReaderRecords: Bool {- entries == 0 && works == 0 && sites == 0 && titlePatterns == 0 && urlRulePatterns == 0+ entries == 0 && works == 0 && sites == 0 && titlePatterns == 0 && urlRulePatterns == 0 && entrySources == 0 } } @@ -495,6 +497,9 @@ public actor LibraryRepository { saveStrategy: self.saveStrategy, clock: self.clock) + // Source association convergence follows directories, before entry sets.+ if try EntrySources.converge(context: context) { try saveStrategy.save(context) }+ // The duplicate phase, after the Site phases and inside the same // lock: rule state is what Work identity and citation replay read, // and the Site union has just moved it. Derived here, never@@ -1014,7 +1019,8 @@ public actor LibraryRepository { sites: context.fetchCount(FetchDescriptor<Site>()), titlePatterns: context.fetchCount(FetchDescriptor<TitlePattern>()), urlRulePatterns: context.fetchCount(FetchDescriptor<URLRulePattern>()),- workTypes: context.fetchCount(FetchDescriptor<WorkTypeEntity>())+ workTypes: context.fetchCount(FetchDescriptor<WorkTypeEntity>()),+ entrySources: context.fetchCount(FetchDescriptor<EntrySource>()) ) } @@ -1034,6 +1040,14 @@ public actor LibraryRepository { let validated = try Self.validateCapture(draft) Self.logger.debug("Capturing Entry for a validated Site boundary") return try await withLockedContext(mode: .exclusive, operation: "saving capture") { context in+ let sources = try EntrySourceIndex(context: context)+ if sources.groups.values.contains(where: { group in+ group.rows.contains { $0.authoredTargetData != nil }+ && sources.urls(for: group.id).contains { ExactScalarString($0) == ExactScalarString(draft.rawURLString) }+ }) {+ throw LibraryRepositoryError.invalidInput(operation: "saving capture",+ reason: "This page already has authored entries. Review the chapter capture choices before saving")+ } let site = try Self.siteForWrite(hostname: validated.hostname, context: context) let timestamp = clock.now()@@ -1075,7 +1089,19 @@ public actor LibraryRepository { // A read of one record's presented content, which is what the // normalisation decides: derived, so this and Recent cannot report // one group torn and whole (Req 3.2).- try Self.snapshot(Self.fetchNormalisedEntryGroup(id: id, context: context))+ let addressed = try Self.fetchNormalisedEntryGroup(id: id, context: context)+ let index = try EntrySourceIndex(context: context)+ guard addressed.rows.contains(where: { $0.mergedIntoEntryID != nil }) else {+ return try Self.snapshot(addressed, sourceURLs: index.urls(for: id))+ }+ if let destinationID = index.destination(of: id, requireResolvedContent: true),+ !index.hasUnresolvedContent(for: destinationID) {+ return try Self.snapshot(Self.fetchNormalisedEntryGroup(id: destinationID, context: context),+ sourceURLs: index.urls(for: destinationID))+ }+ // An unresolved retained loser is the reader's changed content,+ // so reopen it for review instead of guessing a URL survivor.+ return try Self.snapshot(addressed, sourceURLs: index.urls(for: id)) } } @@ -1161,13 +1187,35 @@ public actor LibraryRepository { } } + let sourceIndex = try EntrySourceIndex(context: context)+ let ownedGroups = sourceIndex.groups.values.filter {+ $0.id == group.id || sourceIndex.destination(of: $0.id, requireResolvedContent: false) == group.id+ }+ guard !ownedGroups.contains(where: { predecessor in+ predecessor.id != group.id && (predecessor.isTorn || predecessor.rows.contains { !$0.isResolvedRedirect })+ }) else {+ return .conflict(.recordChanged(recordID: group.id))+ }+ var didSave = false+ defer {+ if !didSave {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Entry>())+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<EntrySource>())+ _ = try? context.fetch(FetchDescriptor<NoEpisodeAction>())+ }+ } let calendar = noteCalendar() try NoEpisodeWriter.recordNoteTransition( before: Self.noteFacts(group, calendar: calendar), after: [], context: context) let timestamp = clock.now() let affectedWorkIDs = Set(group.rows.compactMap { $0.work?.id })- for row in group.rows { context.delete(row) }+ try EntrySources.delete(ownedBy: Set(ownedGroups.map(\.id)), context: context)+ for owned in ownedGroups {+ for row in owned.rows { context.delete(row) }+ } // The Work's rows are one logical record too, so they are stamped // together — a per-row stamp would leave the group's rows differing // in `modifiedAt` and move which one represents it.@@ -1183,6 +1231,7 @@ public actor LibraryRepository { reason: String(describing: error) ) }+ didSave = true return .committed } }@@ -1211,6 +1260,7 @@ public actor LibraryRepository { // hostname, or an HTTP(S) URL with or without its scheme. The host a // URL reduces to is the one capture derives for the same URL, so a // later capture of a page on that site lands on this same `Site` row.+ if draft.hostname.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return ("", nil) } let operation = "checking the site or URL" let hostname: String let workURL: String?@@ -1259,15 +1309,19 @@ public actor LibraryRepository { func insertWork( _ draft: NewWorkDraft, hostname: String, workURL: String?, context: ModelContext ) throws -> WorkSnapshot {- let site = try Self.siteForWrite(hostname: hostname, context: context)+ let site = hostname.isEmpty ? nil : try Self.siteForWrite(hostname: hostname, context: context) let timestamp = MillisecondInstant.quantize(clock.now()) // The Work points at the row the lookup returned — or at the one this // call inserted, never at whichever row a later fetch would order // first (Req 1.4) — and is born holding its first site membership // (Req 1.3).- let work = Work.create(- in: context, title: draft.displayTitle, hostname: hostname, site: site,- timestamp: timestamp)+ let work: Work+ if let site {+ work = Work.create(in: context, title: draft.displayTitle, hostname: hostname, site: site, timestamp: timestamp)+ } else {+ work = Work(displayTitle: draft.displayTitle, timestamp: timestamp)+ context.insert(work)+ } // `to-read` [2.1](../../../../specs/to-read/requirements.md#2.1), // before the one save this call already makes. `Work.create` is // deliberately left alone: every other creation path goes through it@@ -1416,7 +1470,8 @@ public actor LibraryRepository { // move destinations (Req 3.4) — a Work on another site with the same // title is not one of them. return try Self.workGroups(- try Self.worksOn(hostname: entry.hostname, context: context),+ entry.authoredTargetData != nil ? context.fetch(FetchDescriptor<Work>())+ : Self.worksOn(hostname: entry.hostname, context: context), types: types) .values .map {@@ -1574,6 +1629,7 @@ public actor LibraryRepository { // rewritten rather than left alone: the draft has no // representation for a day the toggles cannot draw (Req 1.6, // the statuses' Q19 rule over a list).+ if let captureDefault = draft.chapterCaptureDefault { work.chapterCaptureDefault = captureDefault } work.releaseDays = draft.releaseDays // Req 1.9, 2.2 and Q58: the three thumbnail columns land on // every row of the group, as one tuple, under the same stamp.@@ -1629,13 +1685,21 @@ public actor LibraryRepository { case .resolved(let resolved): group = resolved } if let refusal = Self.tornRefusal(group) { return refusal }+ let sourceIndex = try EntrySourceIndex(context: context)+ guard !sourceIndex.hasUnresolvedContent(for: group.id) else {+ return .conflict(.recordChanged(recordID: group.id))+ }+ let affectedRows = sourceIndex.groups.values.filter {+ sourceIndex.destination(of: $0.id) == group.id+ }.flatMap(\.rows)+ let cleanRedirectRows = Set(affectedRows.filter(\.isResolvedRedirect).map(ObjectIdentifier.init)) let calendar = noteCalendar() let before = Self.noteFacts(group, calendar: calendar) let timestamp = MillisecondInstant.quantize(clock.now()) let representative = group.representative- let priorWorkIDs = Set(group.rows.compactMap { $0.work?.id })+ let priorWorkIDs = Set(affectedRows.compactMap { $0.work?.id }) switch destination { case .existing(let workID):@@ -1645,7 +1709,7 @@ public actor LibraryRepository { // will do — a split group is one Work, and a row the heal has not // reached yet is not a reason to refuse the reader's move. let entryHostname = representative.hostname- guard destinationGroup.rows.contains(where: {+ guard representative.authoredTargetData != nil || destinationGroup.rows.contains(where: { $0.membership(for: entryHostname) != nil }) else { throw LibraryRepositoryError.invalidInput(@@ -1660,7 +1724,7 @@ public actor LibraryRepository { // claim success while leaving that row unattached and its // provenance never set to `.manual` (the block below sits after // this return). The `.unattached` arm has this shape too.- if group.rows.allSatisfy({+ if affectedRows.allSatisfy({ $0.work?.id == workID && !$0.intentionallyUnattached && $0.workAssignmentProvenance == .manual }) { return .committed }@@ -1681,7 +1745,7 @@ public actor LibraryRepository { // Every row of the Entry group points at one row of the // destination group, which is the whole Work as far as Req 5.5's // presentation is concerned.- for row in group.rows {+ for row in affectedRows { row.work = destinationGroup.representative row.intentionallyUnattached = false }@@ -1693,29 +1757,37 @@ public actor LibraryRepository { // and this path would pay for a fetch it never needed. The // lookup remains only as the fallback for an Entry whose own // relationship never arrived — Req 2.1's tolerated state.- let site = try group.rows.compactMap(\.site).first+ let site = try affectedRows.compactMap(\.site).first ?? Self.fetchSites(hostname: representative.hostname, context: context).first- let work = Work.create(- in: context, title: displayTitle, hostname: representative.hostname,- site: site, timestamp: timestamp)+ let work: Work+ if representative.authoredTargetData != nil && representative.hostname.isEmpty {+ work = Work(displayTitle: displayTitle, timestamp: timestamp)+ context.insert(work)+ } else {+ work = Work.create(in: context, title: displayTitle, hostname: representative.hostname,+ site: site, timestamp: timestamp)+ } try self.stampWorkGroups(priorWorkIDs, at: timestamp, context: context)- for row in group.rows {+ for row in affectedRows { row.work = work row.intentionallyUnattached = false } case .unattached: if priorWorkIDs.isEmpty,- group.rows.allSatisfy({+ affectedRows.allSatisfy({ $0.intentionallyUnattached && $0.workAssignmentProvenance == .manual }) { return .committed } try self.stampWorkGroups(priorWorkIDs, at: timestamp, context: context)- for row in group.rows {+ for row in affectedRows { row.work = nil row.intentionallyUnattached = true } } - for row in group.rows { Self.applyManualAssignment(to: row, at: timestamp) }+ for row in affectedRows {+ Self.applyManualAssignment(to: row, at: timestamp)+ row.refreshAcceptedMergeAssignment(wasResolved: cleanRedirectRows.contains(ObjectIdentifier(row)))+ } try NoEpisodeWriter.recordNoteTransition( before: before, after: Self.noteFacts(group, calendar: calendar), context: context) do { try saveStrategy.save(context) }@@ -2166,7 +2238,7 @@ public actor LibraryRepository { history: NoEpisodeHistory ) throws -> WorkSnapshot { try snapshot(- work, entries: try work.entryValues.map(snapshot).sorted(by: entryActivityOrder),+ work, entries: try work.entryValues.map { try snapshot($0) }.sorted(by: entryActivityOrder), types: types, series: series, credits: credits, history: history) } @@ -2223,7 +2295,8 @@ public actor LibraryRepository { releaseDaysRaw: work.releaseDaysRaw, catchUp: work.catchUpRecord, noEpisodeHistory: history,- publicationState: try work.decodedPublicationState()+ publicationState: try work.decodedPublicationState(),+ chapterCaptureDefault: work.chapterCaptureDefault ) } @@ -2293,7 +2366,7 @@ public actor LibraryRepository { /// the row itself and the mapper must not invent a value for it. A *nil* /// blob is neither (Q6) — it is a row V9 has not rewritten, it reads as the /// default, and the validator reports it.- internal static func snapshot(_ entry: Entry) throws -> EntrySnapshot {+ internal static func snapshot(_ entry: Entry, sourceURLs: [String] = []) throws -> EntrySnapshot { let citations = try entry.citations let chapter = citations.chapterTitle let assignment = FieldProvenance.tolerant(@@ -2308,7 +2381,7 @@ public actor LibraryRepository { hostname: entry.hostname, entryIdentityKey: entry.entryIdentityKey, identityKeyVersion: citations.identity.keyVersion,- chapterTitle: entry.chapterTitle,+ chapterTitle: entry.effectiveChapterTitle, chapterTitleProvenance: chapter, note: entry.note, rating: entry.rating,@@ -2318,8 +2391,11 @@ public actor LibraryRepository { workID: entry.work?.id, workAssignmentProvenance: assignment, intentionallyUnattached: entry.intentionallyUnattached,- chapterSequence: entry.chapterSequence,- conservativeIdentityKey: entry.conservativeIdentityKey+ chapterSequence: entry.effectiveChapterSequence,+ conservativeIdentityKey: entry.conservativeIdentityKey,+ authoredTarget: entry.authoredTarget,+ changesAfterCombine: entry.mergedIntoEntryID != nil && !entry.isResolvedRedirect,+ sourceURLs: sourceURLs ) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryValidator.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryValidator.swiftindex d63b4c9b..5d71b2bf 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryValidator.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryValidator.swift@@ -23,6 +23,7 @@ public struct LibraryGraph { /// arrived** (Req 8.3): an orphan is reachable from no Work, and its tuple /// is still a tuple on its hostname. public let memberships: [WorkSiteMembership]+ public let entrySources: [EntrySource] public init( entries: [Entry],@@ -31,7 +32,8 @@ public struct LibraryGraph { titlePatterns: [TitlePattern], urlRules: [URLRulePattern], workTypes: [WorkTypeEntity] = [],- memberships: [WorkSiteMembership] = []+ memberships: [WorkSiteMembership] = [],+ entrySources: [EntrySource] = [] ) { self.entries = entries self.works = works@@ -40,6 +42,7 @@ public struct LibraryGraph { self.urlRules = urlRules self.workTypes = workTypes self.memberships = memberships+ self.entrySources = entrySources } } @@ -269,6 +272,10 @@ public enum LibraryValidator { grouping: works + entries.compactMap(\.work), by: { $0.id.uuidString }, GroupOrdering.sortedWorkRows) + for source in try context.fetch(FetchDescriptor<EntrySource>(predicate: #Predicate { $0.hostname == hostname })) {+ do { try validateEntrySourceTuple(source) }+ catch let error as LibraryValidationError { record(hostname, error) }+ } for site in rows { do { try validate(site: site, allPatterns: allPatterns, allRules: allRules) } catch let error as LibraryValidationError { record(hostname, error) }@@ -339,7 +346,8 @@ public enum LibraryValidator { titlePatterns: try context.fetch(FetchDescriptor<TitlePattern>()), urlRules: try context.fetch(FetchDescriptor<URLRulePattern>()), workTypes: try context.fetch(FetchDescriptor<WorkTypeEntity>()),- memberships: try context.fetch(FetchDescriptor<WorkSiteMembership>())+ memberships: try context.fetch(FetchDescriptor<WorkSiteMembership>()),+ entrySources: try context.fetch(FetchDescriptor<EntrySource>()) ) ) } catch let error as LibraryValidationError {@@ -482,6 +490,13 @@ public enum LibraryValidator { } } + // Sources are independent sync rows. A not-yet-arrived owner is kept,+ // but malformed link/evidence bytes are tuple findings on its own host.+ for source in graph.entrySources {+ do { try validateEntrySourceTuple(source) }+ catch let error as LibraryValidationError { record(source.hostname, error) }+ }+ var orphanedEntries: [String: Int] = [:] var orphanedWorks: [String: Int] = [:] @@ -565,7 +580,9 @@ public enum LibraryValidator { } for group in entryRows { guard let entry = entries[group.key]?.first else { continue }- guard siteHostnames.contains(entry.hostname) else {+ let siteFreeAuthored = entry.authoredTargetData != nil && entry.rawURLString.isEmpty+ && entry.hostname.isEmpty && entry.canonicalURLString == nil && entry.site == nil+ guard siteFreeAuthored || siteHostnames.contains(entry.hostname) else { guard strictness == .tolerant else { throw unresolved("Entry", entry.id.uuidString, "Site \(entry.hostname)") }@@ -611,6 +628,20 @@ public enum LibraryValidator { /// relationship are the same row by Req 1.4, and it is the relationship that /// is read. The Site the write site assigned went with the last arm that /// read it (`remove-article-mode`).+ public static func validateEntrySourceTuple(_ source: EntrySource) throws {+ guard (try? HostnameNormalizer.fromRawURL(source.urlString)) == source.hostname else {+ throw LibraryValidationError.invalidStateTuple(type: "EntrySource", id: source.id.uuidString,+ reason: "Source URL must be absolute HTTP(S) on its recorded hostname")+ }+ if let data = source.evidenceData {+ do { _ = try JSONBlob.decode(EntrySourceEvidence.self, from: data) }+ catch {+ throw LibraryValidationError.invalidStateTuple(type: "EntrySource", id: source.id.uuidString,+ reason: "Source evidence cannot be read: \(error)")+ }+ }+ }+ public static func validateEntryTuple( entry: Entry, works: [Work] ) throws {@@ -1027,8 +1058,21 @@ public enum LibraryValidator { // `membership(for:)` faults and sorts the inverse array per Entry. } + if let data = entry.authoredTargetData {+ do { _ = try AuthoredEntryTarget.decode(data) }+ catch { throw invalid("Entry", id, "unreadable authored target") }+ guard entry.identityBasis == .authoredUUID,+ entry.entryIdentityKey == "entry/\(entry.id.uuidString.lowercased())",+ entry.conservativeIdentityKey.isEmpty,+ entry.citationValues.identity == .authoredEntryID(entry.id) else {+ throw invalid("Entry", id, "authored target requires UUID identity")+ }+ } else if entry.identityBasis == .authoredUUID {+ throw invalid("Entry", id, "UUID identity requires authored target")+ }+ // The conservative-key alias is always the immutable raw URL (Q21).- guard entry.conservativeIdentityKey == entry.rawURLString else {+ guard entry.authoredTargetData != nil || entry.conservativeIdentityKey == entry.rawURLString else { throw invalid("Entry", id, "conservative identity alias must equal the raw URL") } @@ -1065,6 +1109,8 @@ public enum LibraryValidator { // basis citing a URL rule, or a URL-rule basis citing none, is a row only // a partial write produces. switch (basis, citations.identity) {+ case (.authoredUUID, .authoredEntryID(let targetID)):+ guard targetID == entry.id else { throw invalid("Entry", id, "UUID identity mismatch") } case (.conservative, .rawURL): guard entry.entryIdentityKey == entry.rawURLString else { throw invalid("Entry", id, "conservative key must equal the raw URL")@@ -1082,7 +1128,7 @@ public enum LibraryValidator { identityReference: identityReference, workReference: workReference, sequenceReference: sequenceReference, citation)- case (.conservative, _), (.urlRule, .rawURL):+ default: throw invalid("Entry", id, "identity basis and cited identity arm disagree") }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swiftindex 353e0b5a..5e9e7edb 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryWrites.swift@@ -232,6 +232,7 @@ public struct WorkMembershipBasis: Sendable, Equatable, Hashable { /// title (§2.4), and V8 gives it one such relation **per membership** (Req 5.4), /// so the list of them is the identity half here. public struct WorkEditBasis: Sendable, Equatable {+ public let chapterCaptureDefault: ChapterCaptureDefault public let displayTitle: String /// The assignment the edit started from. Compared **canonicalized** against /// the survivor's authored content, in lockstep with `authoredContent`, so a@@ -287,8 +288,10 @@ public struct WorkEditBasis: Sendable, Equatable { membership: SeriesMembership? = nil, thumbnail: ThumbnailIdentity? = nil, releaseDays: [ReleaseDay] = [],- publicationStateData: Data? = nil+ publicationStateData: Data? = nil,+ chapterCaptureDefault: ChapterCaptureDefault = .ordinary ) {+ self.chapterCaptureDefault = chapterCaptureDefault self.releaseDays = ReleaseDay.canonical(releaseDays) self.thumbnail = thumbnail self.membership = membership@@ -306,6 +309,20 @@ public struct WorkEditBasis: Sendable, Equatable { self.verdict = verdict } + /// Carry only the membership authored by the reviewed URL commit. Other+ /// fields retain the editor's original conflict protection.+ public func addingSiteFreeMembership(hostname: String) -> Self {+ guard memberships.isEmpty else { return self }+ return Self(displayTitle: displayTitle, typeAssignment: typeAssignment,+ genreTags: genreTags, genericNotes: genericNotes,+ memberships: [.init(hostname: hostname, urlIdentity: .none)],+ lastParsedTitle: lastParsedTitle, titleProvenance: titleProvenance,+ workStatus: workStatus, readingStatus: readingStatus, verdict: verdict,+ membership: membership, thumbnail: thumbnail, releaseDays: releaseDays,+ publicationStateData: publicationStateData,+ chapterCaptureDefault: chapterCaptureDefault)+ }+ public init(work: WorkSnapshot) { self.init( displayTitle: work.displayTitle, typeAssignment: work.typeDisplay.assignment,@@ -326,7 +343,8 @@ public struct WorkEditBasis: Sendable, Equatable { // tolerant too, so an unknown spelling on either side is not a // divergence on its own (`update-schedule` Req 1.6). releaseDays: work.releaseDays,- publicationStateData: work.publicationStateData)+ publicationStateData: work.publicationStateData,+ chapterCaptureDefault: work.chapterCaptureDefault) } /// The basis's first membership hostname, or the empty string — the same
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LookupCaptureViewModel.swift b/Packages/AsterismCore/Sources/AsterismCore/LookupCaptureViewModel.swiftindex 6b4fc33b..3c9ff83f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LookupCaptureViewModel.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LookupCaptureViewModel.swift@@ -85,11 +85,15 @@ public protocol LookupCaptureCoordinating: Sendable { func captureLookup(rawURL: String, captureTitle: String?) async throws -> CaptureLookupDisposition /// Commit re-share update. func commitReShareUpdate(basis: ReShareEditBasis, note: String, rating: Rating?) async throws -> ReShareUpdateOutcome+ func commitChapterCapture(_ draft: ChapterCaptureDraft) async throws -> ChapterCaptureCommitOutcome /// Title acquisition for new captures (called only when disposition is .new). func fetchTitle(rawURL: String) async throws -> String? } public extension LookupCaptureCoordinating {+ func commitChapterCapture(_ draft: ChapterCaptureDraft) async throws -> ChapterCaptureCommitOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "chapter capture", reason: "Chapter choices are unavailable")+ } func captureLookup(rawURL: String, captureTitle: String?) async throws -> CaptureLookupDisposition { try await captureLookup(rawURL: rawURL) }@@ -103,12 +107,32 @@ public extension LookupCaptureCoordinating { public final class LookupCaptureViewModel { public private(set) var lookupState: LookupCaptureState = .loading + public private(set) var chapterIntent: ChapterCaptureIntent = .automatic+ public var chapterProjection: ChapterCaptureProjection? { currentEditBasis?.chapterProjection }+ public func chooseChapterIntent(_ intent: ChapterCaptureIntent) {+ chapterIntent = intent+ guard case .existing(let id, let contentChoice) = intent,+ let selected = chapterProjection?.entries.first(where: { $0.id == id }),+ case .readyEdit(var edit) = lookupState else { return }+ if contentChoice == .destination || contentChoice == nil && !hasEditedAuthoredContent {+ edit.draftNote = selected.note; edit.draftRating = selected.rating+ lookupState = .readyEdit(edit)+ }+ }+ private var hasEditedAuthoredContent = false+ /// The edit basis retained for commit (valid only in readyEdit state). private var currentEditBasis: ReShareEditBasis? public var canSaveUpdate: Bool {- guard case .readyEdit = lookupState else { return false }- return true+ guard case .readyEdit(let edit) = lookupState else { return false }+ if chapterIntent == .automatic {+ switch chapterProjection?.resolution {+ case .chooseChapter, .newChapter(requiresConfirmation: true): return false+ default: break+ }+ }+ return chapterProjection?.needsContentChoice(intent: chapterIntent, note: edit.draftNote, rating: edit.draftRating) != true } public var canSaveNew: Bool {@@ -166,6 +190,7 @@ public final class LookupCaptureViewModel { // Dispatch on disposition switch disposition { case .edit(let basis):+ hasEditedAuthoredContent = false; chapterIntent = .automatic // Req 4.2: Editing state, prefill from persisted values currentEditBasis = basis lookupState = .readyEdit(ReShareEditState(@@ -201,6 +226,7 @@ public final class LookupCaptureViewModel { /// can still change before tapping Update. public func enterEdit(handoff: RacedCaptureHandoff) { let basis = handoff.basis+ hasEditedAuthoredContent = handoff.reconciledNote != basis.persistedNote || handoff.reconciledRating != basis.persistedRating currentEditBasis = basis lookupState = .readyEdit(ReShareEditState( entryID: basis.entryID,@@ -225,6 +251,7 @@ public final class LookupCaptureViewModel { public func setDraftNote(_ note: String) { guard case .readyEdit(var state) = lookupState else { return }+ hasEditedAuthoredContent = true state.draftNote = note state.errorMessage = nil lookupState = .readyEdit(state)@@ -232,6 +259,7 @@ public final class LookupCaptureViewModel { public func setDraftRating(_ rating: Rating?) { guard case .readyEdit(var state) = lookupState else { return }+ hasEditedAuthoredContent = true state.draftRating = rating state.errorMessage = nil lookupState = .readyEdit(state)@@ -244,7 +272,7 @@ public final class LookupCaptureViewModel { /// On stale: preserves reader's exact draft, refreshes persisted values. /// On failure: preserves reader's exact draft with error message. public func submitUpdate(coordinator: any LookupCaptureCoordinating) async {- guard case .readyEdit(let editState) = lookupState,+ guard canSaveUpdate, case .readyEdit(let editState) = lookupState, let basis = currentEditBasis else { return }@@ -253,6 +281,25 @@ public final class LookupCaptureViewModel { let draftRating = editState.draftRating lookupState = .saving+ if chapterIntent != .automatic, let projection = basis.chapterProjection {+ do {+ let draft = ChapterCaptureDraft(projection: projection,+ capture: CaptureDraft(captureTitle: projection.captureTitle ?? "",+ captureTitleSource: .manual, rawURLString: projection.rawURL,+ note: draftNote, rating: draftRating), intent: chapterIntent)+ switch try await coordinator.commitChapterCapture(draft) {+ case .committed(let entry): lookupState = .saved(entryID: entry.id)+ case .reviewRequired(let fresh, let reason):+ currentEditBasis = basis.with(chapterProjection: fresh)+ var refused = editState; refused.errorMessage = reason+ lookupState = .readyEdit(refused)+ }+ } catch {+ var failed = editState; failed.errorMessage = "Unable to save. Please try again."+ lookupState = .readyEdit(failed)+ }+ return+ } let outcome: ReShareUpdateOutcome do {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/MarkdownExport.swift b/Packages/AsterismCore/Sources/AsterismCore/MarkdownExport.swiftindex 76c0f358..13ce064c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/MarkdownExport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/MarkdownExport.swift@@ -20,6 +20,7 @@ import Foundation public struct EntryExportInput: Sendable, Equatable { public let headingText: String public let rawURLString: String+ public let additionalSourceURLs: [String] public let workTitle: String? public let workTypeLabel: String? /// The entry's `firstCapturedAt` in the reader's locale, long style (Q8,@@ -35,10 +36,12 @@ public struct EntryExportInput: Sendable, Equatable { workTypeLabel: String? = nil, dateText: String, rating: Rating? = nil,- note: String = ""+ note: String = "",+ additionalSourceURLs: [String] = [] ) { self.headingText = headingText self.rawURLString = rawURLString+ self.additionalSourceURLs = additionalSourceURLs self.workTitle = workTitle self.workTypeLabel = workTypeLabel self.dateText = dateText@@ -421,8 +424,14 @@ public enum MarkdownExport { // no new metadata (Req 1.6). // Collapsed like every other title-bearing value: a raw URL carrying a // stray newline would otherwise split the link across two paragraphs.- let headingText = heading.isEmpty ? escape(collapsed(input.rawURLString)) : heading- paragraphs.append("## [\(headingText)](\(encodeLinkTarget(input.rawURLString)))")+ let headingText = heading.isEmpty ? (input.rawURLString.isEmpty ? "Note" : escape(collapsed(input.rawURLString))) : heading+ if input.rawURLString.isEmpty { paragraphs.append("## \(headingText)") }+ else { paragraphs.append("## [\(headingText)](\(encodeLinkTarget(input.rawURLString)))") }+ if !input.additionalSourceURLs.isEmpty {+ paragraphs.append("Sources: " + input.additionalSourceURLs.map {+ "[\(escape(collapsed($0)))](\(encodeLinkTarget($0)))"+ }.joined(separator: " · "))+ } if includingWorkLine, let line = workLine(input) { paragraphs.append(line) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Models.swift b/Packages/AsterismCore/Sources/AsterismCore/Models.swiftindex 1e430979..602bd748 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 V19's, nested inside `AsterismSchemaV19`+// The live model classes are V20's, nested inside `AsterismSchemaV20` // (Decision 6, Q20). Top-level typealiases keep every call site (`Entry`, // `Site`, …) unchanged. //@@ -11,50 +11,51 @@ import SwiftData // *top-level* `@Model` per entity name — and there are none, because every // top-level name here is a typealias. Two top-level `@Model`s sharing an entity // name crash `ModelContext` (`docs/agent-notes/schema-migration.md`).-public typealias Entry = 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+public typealias Entry = AsterismSchemaV20.Entry+public typealias Work = AsterismSchemaV20.Work+public typealias Site = AsterismSchemaV20.Site+public typealias TitlePattern = AsterismSchemaV20.TitlePattern+public typealias URLRulePattern = AsterismSchemaV20.URLRulePattern+public typealias WorkTypeEntity = AsterismSchemaV20.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 = AsterismSchemaV19.WorkSiteMembership+public typealias WorkSiteMembership = AsterismSchemaV20.WorkSiteMembership /// V8: a reader's "not the same work" over an unordered pair of Works (Q20).-public typealias WorkDistinctPair = AsterismSchemaV19.WorkDistinctPair+public typealias WorkDistinctPair = AsterismSchemaV20.WorkDistinctPair /// V11: a reader-named, ordered collection a Work belongs to at most once /// (`series-and-related-works` Decision 1).-public typealias Series = AsterismSchemaV19.Series+public typealias Series = AsterismSchemaV20.Series /// V11: an undirected, typed connection between two distinct Works /// (`series-and-related-works` Decision 5).-public typealias WorkLink = AsterismSchemaV19.WorkLink+public typealias WorkLink = AsterismSchemaV20.WorkLink /// V12: a person a work is credited to, a reader-managed directory record /// (`work-creators` Decision 2).-public typealias Creator = AsterismSchemaV19.Creator+public typealias Creator = AsterismSchemaV20.Creator /// V12: one entry in the ordered role list credits reference by identity /// (`work-creators` Decision 1).-public typealias CreatorRole = AsterismSchemaV19.CreatorRole+public typealias CreatorRole = AsterismSchemaV20.CreatorRole /// V12: one work-and-creator pairing, carrying the roles that creator holds on /// that work (`work-creators` Decision 6).-public typealias WorkCredit = AsterismSchemaV19.WorkCredit+public typealias WorkCredit = AsterismSchemaV20.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 = AsterismSchemaV19.Character-public typealias CharacterSuppression = AsterismSchemaV19.CharacterSuppression+public typealias CharacterRecord = AsterismSchemaV20.Character+public typealias CharacterSuppression = AsterismSchemaV20.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 = AsterismSchemaV19.Place+public typealias Place = AsterismSchemaV20.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 = AsterismSchemaV19.PlaceSuppression-public typealias NoEpisodeAction = AsterismSchemaV19.NoEpisodeAction+public typealias PlaceSuppression = AsterismSchemaV20.PlaceSuppression+public typealias EntrySource = AsterismSchemaV20.EntrySource+public typealias NoEpisodeAction = AsterismSchemaV20.NoEpisodeAction /// The presentation-enum tolerance policy for the **model accessors**, in one /// place (Q2).@@ -136,10 +137,13 @@ enum JSONBlob { } } -extension AsterismSchemaV19 {+extension AsterismSchemaV20 { @Model public final class Entry {+ public var authoredTargetData: Data?+ public var mergedIntoEntryID: UUID?+ public var mergeResolutionData: Data? public var id: UUID = UUID() public var captureTitle: String = "" public var captureTitleSourceRaw: String = CaptureTitleSource.manual.rawValue@@ -348,6 +352,7 @@ public final class Entry { @Model public final class Work {+ public var chapterCaptureDefaultRaw: String = "ordinary" public var id: UUID = UUID() public var displayTitle: String = "" public var lastParsedTitle: String?@@ -424,7 +429,7 @@ 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.+ /// V20: 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).@@ -1765,7 +1770,7 @@ public final class PlaceSuppression { } } -} // extension AsterismSchemaV19+} // extension AsterismSchemaV20 /// A rule-derived URL identity a creation site already holds, passed through /// `Work.create` so the minted membership is born carrying it (Req 1.3, 3.1).
diff --git a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swiftindex c78aba30..b73a85cd 100644--- a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift@@ -10,6 +10,7 @@ public enum NoEpisodeWriter { // Work; taking one global max would clear the wrong date on one side. var latestByAssignment: [EntryWorkKey: Date] = [:] for row in rows {+ if row.mergedIntoEntryID != nil && row.isResolvedRedirect { continue } guard let workID = row.work?.id else { continue } let key = EntryWorkKey(entryID: row.id, workID: workID) if let latest = latestByAssignment[key], latest >= row.lastSharedAt { continue }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/PendingCaptureDrain.swift b/Packages/AsterismCore/Sources/AsterismCore/PendingCaptureDrain.swiftindex fa0eeca6..f102e540 100644--- a/Packages/AsterismCore/Sources/AsterismCore/PendingCaptureDrain.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/PendingCaptureDrain.swift@@ -500,14 +500,22 @@ public actor PendingCaptureDrain { switch disposition { case .edit(let basis): switch try await recordReShare(basis, sharedAt: record.sharedAt) {- case .some(let entryID): return .recordedAgainstExisting(entryID)+ case .committed: return .recordedAgainstExisting(basis.entryID) // Req 4.6: the entry it matched is gone, or no longer carries the // key. Fall through and create a new entry, as a capture taken now // would — guarded on the key it matched, because that is the key a // capture landing in the meantime would carry.- case .none: raceGuardKeys = [basis.identityKey]+ case .entryGone: raceGuardKeys = [basis.identityKey]+ case .reviewRequired: return .invalidated(.chapterSelectionRequired) } case .new(let basis):+ if let projection = basis.chapterProjection {+ switch projection.resolution {+ case .chooseChapter, .newChapter(requiresConfirmation: true):+ return .invalidated(.chapterSelectionRequired)+ default: break+ }+ } // Without these the drain has the window the sheet's guard closes: // the reader commits a capture of the same page between this pass's // lookup and its commit, and both insert. `commitCapture` answers@@ -566,7 +574,9 @@ public actor PendingCaptureDrain { rating: contract.request.rating, raceGuardKeys: raceGuardKeys, entryID: record.id,- capturedAt: record.sharedAt)+ capturedAt: record.sharedAt,+ chapterProjection: contract.request.chapterProjection,+ chapterIntent: contract.request.chapterIntent) let outcome = try await repository.commitCapture( CaptureContract(basis: contract.basis, request: stamped, outcome: contract.outcome)) @@ -593,21 +603,19 @@ public actor PendingCaptureDrain { // `.raced(.new)`, so the other arm is a defensive wait. guard case .edit(let basis) = resolved else { return .waiting(.observedFailure) } switch try await recordReShare(basis, sharedAt: record.sharedAt) {- case .some(let entryID): return .recordedAgainstExisting(entryID)- case .none: return .waiting(.observedFailure)+ case .committed: return .recordedAgainstExisting(basis.entryID)+ case .entryGone: return .waiting(.observedFailure)+ case .reviewRequired: return .invalidated(.chapterSelectionRequired) } } } /// Records the re-share, returning the entry it landed on, or nil when the /// entry is gone and the caller must create one (Req 4.6).- private func recordReShare(_ basis: ReShareEditBasis, sharedAt: Date) async throws -> UUID? {+ private func recordReShare(_ basis: ReShareEditBasis, sharedAt: Date) async throws -> DrainedReShareOutcome { let target = DrainedReShareTarget(- entryID: basis.entryID, hostname: basis.hostname, identityKey: basis.identityKey)- switch try await repository.recordDrainedReShare(target: target, sharedAt: sharedAt) {- case .committed: return basis.entryID- case .entryGone: return nil- }+ entryID: basis.entryID, hostname: basis.hostname, identityKey: basis.identityKey, chapterProjection: basis.chapterProjection)+ return try await repository.recordDrainedReShare(target: target, sharedAt: sharedAt) } // MARK: - Helpers
diff --git a/Packages/AsterismCore/Sources/AsterismCore/PendingCaptureSpool.swift b/Packages/AsterismCore/Sources/AsterismCore/PendingCaptureSpool.swiftindex c8791945..d03506a2 100644--- a/Packages/AsterismCore/Sources/AsterismCore/PendingCaptureSpool.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/PendingCaptureSpool.swift@@ -157,6 +157,8 @@ public struct PendingCaptureRecord: Codable, Sendable, Equatable, Identifiable { /// apart from `invalidated` because the missing part is nameable, and the /// reader's row already shows the page URL it belongs to. case noResolvableTitle+ /// The reader must select or confirm a chapter before this share can save.+ case chapterSelectionRequired } /// What the queue is doing with this record. Held in the body rather than in
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift b/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swiftindex 201e40e9..f23fdecd 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift@@ -268,6 +268,8 @@ public struct CaptureBasis: Sendable, Equatable { /// The capture request: exact pending title + evidence. public struct CaptureRequest: Sendable, Equatable {+ public let chapterProjection: ChapterCaptureProjection?+ public let chapterIntent: ChapterCaptureIntent public let captureTitle: String public let captureTitleSource: CaptureTitleSource public let rawURLString: String@@ -293,7 +295,11 @@ public struct CaptureRequest: Sendable, Equatable { public init(captureTitle: String, captureTitleSource: CaptureTitleSource, rawURLString: String, canonicalURLString: String?, note: String, rating: Rating?, raceGuardKeys: [String]? = nil,- entryID: UUID? = nil, capturedAt: Date? = nil) {+ entryID: UUID? = nil, capturedAt: Date? = nil,+ chapterProjection: ChapterCaptureProjection? = nil,+ chapterIntent: ChapterCaptureIntent = .automatic) {+ self.chapterProjection = chapterProjection+ self.chapterIntent = chapterIntent self.captureTitle = captureTitle self.captureTitleSource = captureTitleSource self.rawURLString = rawURLString@@ -304,6 +310,11 @@ public struct CaptureRequest: Sendable, Equatable { self.entryID = entryID self.capturedAt = capturedAt }+ public func withChapterProjection(_ projection: ChapterCaptureProjection?, intent: ChapterCaptureIntent = .automatic) -> Self {+ Self(captureTitle: captureTitle, captureTitleSource: captureTitleSource, rawURLString: rawURLString,+ canonicalURLString: canonicalURLString, note: note, rating: rating, raceGuardKeys: raceGuardKeys,+ entryID: entryID, capturedAt: capturedAt, chapterProjection: projection, chapterIntent: intent)+ } } /// The capture outcome: what the capture will produce.@@ -387,7 +398,9 @@ public struct WorkURLBasis: Equatable, Sendable { /// site-specific address, so every value below — the hostname, the identity, /// the evidence and the prior URL — belongs to one of the Work's site /// memberships, and this names it.- public let membershipID: UUID+ public let membershipID: UUID?+ public let siteFreeWorkContent: WorkAuthoredContent?+ public let siteFreeWorkModifiedAt: Date? public let siteHostname: ExactScalarString public let identity: WorkIdentitySnapshot public let currentRule: URLRuleBasisEntry?@@ -396,13 +409,17 @@ public struct WorkURLBasis: Equatable, Sendable { public init( workID: UUID,- membershipID: UUID = UUID(),+ membershipID: UUID? = UUID(), siteHostname: ExactScalarString, identity: WorkIdentitySnapshot, currentRule: URLRuleBasisEntry?, entries: [WorkURLSourceEntry],- priorWorkURL: String?+ priorWorkURL: String?,+ siteFreeWorkContent: WorkAuthoredContent? = nil,+ siteFreeWorkModifiedAt: Date? = nil ) throws {+ self.siteFreeWorkContent = siteFreeWorkContent+ self.siteFreeWorkModifiedAt = siteFreeWorkModifiedAt guard !siteHostname.isBlank else { throw WorkURLPlanningError.blankHostname } guard identity.isValid else { throw WorkURLPlanningError.invalidIdentity } if let priorWorkURL, !WorkURLPlanner.isValidHTTPURL(priorWorkURL) {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift b/Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swiftindex b7bbe751..8fd2b14d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/RepositoryDrafts.swift@@ -59,6 +59,8 @@ public struct NewWorkDraft: Equatable, Sendable { } public struct WorkMetadataDraft: Equatable, Sendable {+ /// Nil keeps the existing default for callers that did not edit this field.+ public let chapterCaptureDefault: ChapterCaptureDefault? public let displayTitle: String /// What the editor's picker selected, as an assignment rather than a raw /// value — the picker offers configured entries, the blank untyped row, and@@ -110,8 +112,10 @@ public struct WorkMetadataDraft: Equatable, Sendable { releaseDays: [ReleaseDay], membership: SeriesMembership?, credits: CreditsDraft? = nil,- thumbnail: ThumbnailWrite+ thumbnail: ThumbnailWrite,+ chapterCaptureDefault: ChapterCaptureDefault? = nil ) {+ self.chapterCaptureDefault = chapterCaptureDefault self.releaseDays = ReleaseDay.canonical(releaseDays) self.thumbnail = thumbnail self.credits = credits
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ShareTransport.swift b/Packages/AsterismCore/Sources/AsterismCore/ShareTransport.swiftindex 369628de..a188df07 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ShareTransport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ShareTransport.swift@@ -357,7 +357,8 @@ public actor CaptureCoordinator: CaptureCoordinating, LookupCaptureCoordinating // (Q23), so nothing here depends on it — but a rebuild that drops // fields is a defect whichever caller meets it. entryID: id,- capturedAt: request.capturedAt+ capturedAt: request.capturedAt,+ chapterProjection: request.chapterProjection, chapterIntent: request.chapterIntent ) // The outcome and basis are unchanged (they depend on neither the guard // keys nor the id), so the repository's staleness check still passes.@@ -398,6 +399,10 @@ public actor CaptureCoordinator: CaptureCoordinating, LookupCaptureCoordinating try await repository.commitReShareUpdate(basis: basis, note: note, rating: rating) } + public func commitChapterCapture(_ draft: ChapterCaptureDraft) async throws -> ChapterCaptureCommitOutcome {+ try await repository.commitChapterCapture(draft)+ }+ public func fetchTitle(rawURL: String) async throws -> String? { guard let fetcher else { return nil } return try await fetcher.fetch(url: rawURL)?.title
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift b/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swiftindex fc443d1a..3c26fc20 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift@@ -346,13 +346,13 @@ extension LibraryRepository { // carrier's note, the placement — stays below, where the carrier is // known, so the filter has one job and the selection states the // whole rule.- let noted = rowsByID.values.filter { rows in- rows.contains { !$0.note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }- } // Pure over the rows already faulted in: `entryGroups` builds no // snapshots, so a corrupt row elsewhere in the work cannot fail the // walk. Only the selected group is snapshotted, below.- let groups = Self.entryGroups(noted.flatMap { $0 }, canonicalWorkIDs: [:])+ let activeGroups = Self.entryGroups(rowsByID.values.flatMap { $0 }, canonicalWorkIDs: [:])+ let groups = activeGroups.filter { _, group in+ group.rows.contains { !$0.note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }+ } // Where `excludingEntryID` applies: the entry the re-share sheet is // editing is a live entry of the work, so the ranking above counts // it (Req 2.7) and only the note the editor already holds is@@ -367,10 +367,12 @@ extension LibraryRepository { // back to the reader. let candidates = groups.values.compactMap { group -> (EntryGroup, ChapterPlacement)? in guard group.id != excludingEntryID,+ group.carrier.authoredTarget?.kind != .note,+ !group.rows.contains(where: { $0.mergedIntoEntryID != nil }), !group.carrier.note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, let placement = ChapterPlacement.of(- chapterSequence: group.carrier.chapterSequence,- chapterTitle: group.carrier.chapterTitle),+ chapterSequence: group.carrier.effectiveChapterSequence,+ chapterTitle: group.carrier.effectiveChapterTitle), placement < anchor else { return nil } return (group, placement)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swiftindex 538ea5ae..1abbd1c4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift@@ -27,6 +27,21 @@ public struct EntrySnapshot: Equatable, Sendable { public let workID: UUID? public let workAssignmentProvenance: FieldProvenance public let intentionallyUnattached: Bool+ public let authoredTarget: AuthoredEntryTarget?+ public let changesAfterCombine: Bool+ /// Verbatim source links, in deterministic scalar order.+ public let sourceURLs: [String]+ public var authoredNoteTitle: String? {+ authoredTarget?.kind == .note ? (authoredTarget?.title ?? "Note") : nil+ }+ public var primarySourceURL: URL? {+ ([rawURLString] + sourceURLs).compactMap { value in+ guard let url = URL(string: value),+ let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme),+ url.host != nil else { return nil }+ return url+ }.first+ } public init( id: UUID, captureTitle: String, captureTitleSource: CaptureTitleSource,@@ -42,9 +57,15 @@ public struct EntrySnapshot: Equatable, Sendable { // it (Q64), so the redirect reports "gone" rather than resolving to a // wrong record. Every production snapshot goes through // `LibraryRepository.snapshot(_:)`, which sets it from the row.- conservativeIdentityKey: String = ""+ conservativeIdentityKey: String = "",+ authoredTarget: AuthoredEntryTarget? = nil,+ changesAfterCombine: Bool = false,+ sourceURLs: [String] = [] ) { self.conservativeIdentityKey = conservativeIdentityKey+ self.authoredTarget = authoredTarget+ self.changesAfterCombine = changesAfterCombine+ self.sourceURLs = sourceURLs self.id = id self.captureTitle = captureTitle self.captureTitleSource = captureTitleSource@@ -99,6 +120,7 @@ public struct WorkSiteMembershipSnapshot: Equatable, Sendable, Identifiable { } public struct WorkSnapshot: Equatable, Sendable {+ public let chapterCaptureDefault: ChapterCaptureDefault public let id: UUID public let displayTitle: String public let lastParsedTitle: String?@@ -285,8 +307,10 @@ public struct WorkSnapshot: Equatable, Sendable { releaseDaysRaw: [String]? = nil, catchUp: CatchUpRecord = .pristine, noEpisodeHistory: NoEpisodeHistory = .empty,- publicationState: WorkPublicationState? = nil+ publicationState: WorkPublicationState? = nil,+ chapterCaptureDefault: ChapterCaptureDefault = .ordinary ) {+ self.chapterCaptureDefault = chapterCaptureDefault // Both parameters stay, so no call site moves: a caller reading a row // hands over what the row holds, and a caller stating only the days it // means gets the canonical spelling of them. Only the raw list is kept
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swiftindex ec097826..204ce06a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift@@ -897,7 +897,7 @@ struct BackupExportDegradedRefusalTests { metadata: BackupV18Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch)) let decoded = try BackupV18Codec.decode(encoded) - let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none) let container = try ModelContainer(for: schema, configurations: [configuration])
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swiftindex 2616055a..338b3a50 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.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: AsterismV19MigrationPlan.self,+ migrationPlan: AsterismV20MigrationPlan.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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -715,7 +715,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV19MigrationPlan.self,+ migrationPlan: AsterismV20MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -758,7 +758,7 @@ private func createReadySiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -767,7 +767,7 @@ private func createReadySiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV19MigrationPlan.self,+ migrationPlan: AsterismV20MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -802,7 +802,7 @@ private func createReadyDuplicateSiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -811,7 +811,7 @@ private func createReadyDuplicateSiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV19MigrationPlan.self,+ migrationPlan: AsterismV20MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swiftindex fccb7795..a5deb034 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift@@ -1954,7 +1954,7 @@ struct BackupV18ExportTests { private var carrier: Work! init() throws {- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) container = try ModelContainer( for: schema, configurations: [@@ -2226,7 +2226,7 @@ struct BackupV18ImportTests { #expect(reason.contains("format \(pair.format)")) #expect(reason.contains("schema \(pair.schema)")) // Req 13.1 names both pairs: the archive's and the one this build reads.- #expect(reason.contains("(\(BackupV18Document.formatVersion)/\(BackupV18Document.schemaVersion))"))+ #expect(reason.contains("(\(BackupV19Document.formatVersion)/\(BackupV19Document.schemaVersion))")) } @Test("A mismatched pair around 16/17 is unsupported")@@ -2573,7 +2573,7 @@ struct BackupV18ImportTests { /// which is what Req 1.8 promises a restore does. @Test("Re-applying the same archive cover writes nothing, and a broken blob heals") func reapplyingTheSameCoverWritesNothing() throws {- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let container = try ModelContainer( for: schema, configurations: [@@ -3875,7 +3875,7 @@ struct BackupV18ImportTests { /// the third is exactly where the two differ (Q23). @Test("Re-applying the same archive citations writes nothing; undecodable and absent blobs heal") func reapplyingTheSameCitationsWritesNothing() throws {- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let container = try ModelContainer( for: schema, configurations: [@@ -3966,7 +3966,7 @@ struct BackupV18ImportTests { /// on both sides of an undecodable row and skip the heal. @Test("Re-applying the same archive facts writes nothing; undecodable bytes heal") func reapplyingTheSameFactsWritesNothing() throws {- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swiftindex 5d100467..b09b29ce 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift@@ -209,7 +209,7 @@ struct BackupV18ImportMatrixTests { } #expect(reason.contains("format 15")) #expect(reason.contains("schema 16"))- #expect(reason.contains("(18/19)"))+ #expect(reason.contains("(19/20)")) // And it writes nothing (Req 5.3). The refusal is at `plan`, which runs // outside the repository actor and holds no lease, so there is no plan
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV19ChapterTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV19ChapterTests.swiftnew file mode 100644index 00000000..d51568ee--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV19ChapterTests.swift@@ -0,0 +1,181 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Chapter archives 19/20", .serialized)+struct BackupV19ChapterTests {+ @Test("Current backup snapshot and exporter preserve actionable torn-group refusal", arguments: [false, true])+ func actionableTornRefusal(export: Bool) async throws {+ let fixture = try await M5Fixture()+ let work = UUID(), entry = UUID()+ try await fixture.repository.seedM5Rows(sites: [.init(hostname: "example.com")],+ works: [.init(id: work, displayTitle: "Book", hostname: "example.com")],+ entries: [.init(id: entry, captureTitle: "Chapter", hostname: "example.com", path: "one", note: "First", workID: work),+ .init(id: entry, captureTitle: "Chapter", hostname: "example.com", path: "one", note: "Second", workID: work)])+ let staging = fixture.directory.appendingPathComponent("refusal-stage")+ do {+ if export {+ _ = try await BackupV19Exporter(repository: fixture.repository, stagingDirectory: staging)+ .export(metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ } else { _ = try await fixture.repository.backupV19Snapshot() }+ Issue.record("A torn record cannot be exported")+ } catch let error as BackupV18ExportError {+ #expect(error == .tornGroups(.init(count: 1, blockingWorkSet: nil)))+ } catch { Issue.record("The actionable refusal must cross the lock boundary intact: \(type(of: error))") }+ #expect(!FileManager.default.fileExists(atPath: staging.path))+ #expect(try await fixture.repository.archiveEntryNotes(id: entry) == Set(["First", "Second"]))+ }+ @Test("Released 18/19 restores without inventing authored targets, sources or work defaults")+ func predecessorRestore() async throws {+ let encoded = try BackupV18Codec.encode(payload: BackupV18Fixtures.payload(), metadata: BackupV18Fixtures.metadata())+ let plan = try BackupImporter.plan(from: encoded)+ #expect(plan.metadata.formatVersion == 18 && plan.metadata.schemaVersion == 19)+ #expect(plan.payload.chapterEntries.isEmpty && plan.payload.entrySources.isEmpty)+ let fixture = try await M5Fixture()+ _ = try await fixture.repository.confirmImport(plan: plan)+ let restored = try await fixture.repository.backupV19Snapshot()+ #expect(restored.entries.allSatisfy { $0.authoredTargetData == nil })+ #expect(restored.entrySources.isEmpty)+ #expect(restored.works.allSatisfy { $0.chapterCaptureDefault == .ordinary })+ }++ @Test("Codec and additive restore preserve hidden loser UUIDs, accepted baselines and durable sources")+ func combinedRoundTrip() async throws {+ let source = try await M5Fixture()+ let work = UUID(), loser = UUID(), survivor = UUID()+ try await source.repository.seedM5Rows(sites: [.init(hostname: "example.com")],+ works: [.init(id: work, displayTitle: "Book", hostname: "example.com")],+ entries: [.init(id: loser, captureTitle: "First", hostname: "example.com", path: "a", workID: work),+ .init(id: survivor, captureTitle: "Second", hostname: "example.com", path: "b", workID: work)])+ let contract = try await source.repository.projectEntryCorrection(entryID: loser, destinationID: survivor)+ #expect(try await source.repository.commitEntryCorrection(contract,+ target: .init(kind: .chapter, designation: "12")) == .committed(entryID: survivor))+ let payload = try await source.repository.backupV19Snapshot()+ #expect(payload.entries.count == 2)+ #expect(payload.entries.first { $0.id == loser }?.mergedIntoEntryID == survivor)+ #expect(payload.entrySources.contains { $0.urlString == "https://example.com/a" })+ let encoded = try BackupV19Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let decoded = try BackupV19Codec.decode(encoded)+ #expect(decoded.payload == payload)+ #expect(decoded.backupFormatVersion == 19 && decoded.databaseSchemaVersion == 20)+ let plan = try BackupImporter.plan(from: encoded)+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: plan)+ #expect(try await restored.repository.entry(id: loser).id == survivor)+ let first = try await restored.repository.backupV19Snapshot()+ _ = try await restored.repository.confirmImport(plan: plan)+ #expect(try await restored.repository.backupV19Snapshot() == first)+ #expect(first.entries.count == 2 && first.entrySources.count == payload.entrySources.count)+ }++ @Test("Contradictory authored target with legacy identity refuses the new archive")+ func oldShapeRejectsUUID() throws {+ let original = try #require(BackupV18Fixtures.payload().entries.first)+ let target = try AuthoredEntryTarget(kind: .chapter, designation: "12").encoded()+ let record = BackupV19Entry(predecessor: original, authoredTargetData: target)+ // An authored target with legacy identity is contradictory in 19/20.+ let payload = BackupV19Payload(entries: [record], works: [], sites: BackupV18Fixtures.payload().sites,+ titlePatterns: [], urlRules: [])+ #expect(throws: BackupCodecError.self) {+ try BackupV19Codec.decode(BackupV19Codec.encode(payload: payload,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch)))+ }+ }++ @Test("Released 18/19 decoder does not admit the newly added UUID identity arm")+ func frozenIdentityArms() throws {+ let original = try #require(BackupV18Fixtures.payload().entries.first)+ let row = ArchiveRecordBuilders.makeEntry(original)+ try row.authorTarget(.init(kind: .chapter, designation: "12"))+ let group = try #require(LibraryRepository.entryGroup(id: row.id, rows: [row], canonicalWorkIDs: [:]))+ let record = try LibraryRepository.mapV18EntryRecord(group, citations: EntryCitationsCache([row]))+ let payload = BackupV18Payload(entries: [record], works: [], sites: BackupV18Fixtures.payload().sites,+ titlePatterns: [], urlRules: [])+ #expect(throws: BackupCodecError.self) {+ try BackupV18Codec.decode(BackupV18Codec.encode(payload: payload, metadata: BackupV18Fixtures.metadata()))+ }+ }++ @Test("URL-free manual notes and purchase sources survive codec and additive restore")+ func manualArchive() async throws {+ let source = try await M5Fixture()+ let work = try await source.repository.createWork(.init(displayTitle: "Published book", hostname: ""))+ let projection = try await source.repository.projectManualEntry(workID: work.id)+ guard case .committed(let entry) = try await source.repository.commitManualEntry(projection: projection,+ draft: .init(sourceURL: "https://amazon.com/book", rating: .up)) else {+ Issue.record("Manual rating-only note must save"); return+ }+ let payload = try await source.repository.backupV19Snapshot()+ #expect(payload.sites.isEmpty && payload.memberships.isEmpty)+ let encoded = try BackupV19Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: BackupImporter.plan(from: encoded))+ #expect(try await restored.repository.entry(id: entry.id).rating == .up)+ let result = try await restored.repository.backupV19Snapshot()+ #expect(result.entries.first?.rawURL.isEmpty == true)+ #expect(result.entrySources.first?.urlString == "https://amazon.com/book")+ #expect(result.sites.isEmpty && result.memberships.isEmpty)+ }++ @Test("A valid imported late source is retained when local combined content needs review")+ func incomingSourceDuringConflict() async throws {+ let fixture = try await M5Fixture()+ let work = UUID(), loser = UUID(), survivor = UUID()+ try await fixture.repository.seedM5Rows(sites: [.init(hostname: "example.com")],+ works: [.init(id: work, displayTitle: "Book", hostname: "example.com")],+ entries: [.init(id: loser, captureTitle: "First", hostname: "example.com", path: "a", workID: work),+ .init(id: survivor, captureTitle: "Second", hostname: "example.com", path: "b", workID: work)])+ let contract = try await fixture.repository.projectEntryCorrection(entryID: loser, destinationID: survivor)+ _ = try await fixture.repository.commitEntryCorrection(contract, target: .init(kind: .chapter, designation: "12"))+ let original = try await fixture.repository.backupV19Snapshot()+ let sourceID = UUID()+ let incoming = BackupV19EntrySource(id: sourceID, entryID: loser, urlString: "https://example.com/late",+ hostname: "example.com", createdAt: M5Fixture.epoch, modifiedAt: M5Fixture.epoch)+ let payload = BackupV19Payload(entries: original.entries, works: original.works, sites: original.sites,+ titlePatterns: original.titlePatterns, urlRules: original.urlRules, workTypes: original.workTypes,+ memberships: original.memberships, distinctPairs: original.distinctPairs, characters: original.characters,+ suppressions: original.suppressions, places: original.places, placeSuppressions: original.placeSuppressions,+ series: original.series, links: original.links, creators: original.creators, creatorRoles: original.creatorRoles,+ credits: original.credits, noEpisodeActions: original.noEpisodeActions, entrySources: original.entrySources + [incoming])+ let encoded = try BackupV19Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let plan = try BackupImporter.plan(from: encoded)+ try await fixture.repository.seedArchiveLateEdit(entryID: loser)+ _ = try await fixture.repository.confirmImport(plan: plan)+ #expect(try await fixture.repository.entry(id: loser).changesAfterCombine)+ #expect(try await fixture.repository.archiveHasSource(id: sourceID, owner: loser))+ await #expect(throws: (any Error).self) { try await fixture.repository.backupV19Snapshot() }+ }++ @Test("Evidence order is byte-stable for scalar-distinct Unicode labels")+ func unicodeEvidenceOrder() throws {+ let rule = UUID()+ let a = EntrySourceEvidence.Binding(origin: .designation, key: "é", ruleID: rule)+ let b = EntrySourceEvidence.Binding(origin: .designation, key: "e\u{301}", ruleID: rule)+ let forward = try EntrySourceEvidence.union([.init(confirmed: [a]), .init(confirmed: [b])]).encoded()+ let reverse = try EntrySourceEvidence.union([.init(confirmed: [b]), .init(confirmed: [a])]).encoded()+ #expect(forward == reverse)+ #expect(try JSONBlob.decode(EntrySourceEvidence.self, from: forward).active.count == 2)+ }+}++extension LibraryRepository {+ fileprivate func archiveEntryNotes(id: UUID) async throws -> Set<String> {+ try await withLockedContext(mode: .shared, operation: "checking untouched refused backup") { context in+ Set(try Self.fetchNormalisedEntryGroup(id: id, context: context).rows.map(\.note))+ }+ }+ fileprivate func seedArchiveLateEdit(entryID: UUID) async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding late archive edit") { context in+ for row in try Self.fetchNormalisedEntryGroup(id: entryID, context: context).rows {+ row.note = "Late offline edit"; row.modifiedAt = row.modifiedAt.addingTimeInterval(1000)+ }+ try context.save()+ }+ }+ fileprivate func archiveHasSource(id: UUID, owner: UUID) async throws -> Bool {+ try await withLockedContext(mode: .shared, operation: "reading preserved archive source") { context in+ try context.fetch(FetchDescriptor<EntrySource>()).contains { $0.id == id && $0.entryID == owner }+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swiftindex cc25f3c2..30c8fd13 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() == "19",+ #expect(try root.markerText() == "20", "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("19\n")+ try root.writeMarker("20\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("19\n")+ try root.writeMarker("20\n") case .readinessMarkerWithoutAStore: try root.createStoreDirectory()- try root.writeMarker("19\n")+ try root.writeMarker("20\n") case .historicalMarkerWithoutAStore: try root.createStoreDirectory() try root.writeHistoricalMarker()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swiftindex 4c467b67..dcc67c28 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("19\n")+ try root.writeMarker("20\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("19\n")+ try root.writeMarker("20\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("19\n")+ try root.writeMarker("20\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 .nineteen: try root.writeMarker("19\n")+ case .twenty: try root.writeMarker("20\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 == .nineteen, storePresent { return .ready }+ if marker == .twenty, 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, nineteen, unrecognisedText, nonUTF8+ case absent, four, five, six, fourteen, fifteen, sixteen, seventeen, twenty, unrecognisedText, nonUTF8 } /// What the seeded main file is meant to record. The expectation is derived from
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swiftindex 12fbc914..53ea52c0 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 = "19\n"+private let readyMarkerBytes = "20\n" /// The counts of a library seeded with exactly one `Site`. ///
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CaptureStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CaptureStateTests.swiftindex 113bde2d..879b384e 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CaptureStateTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CaptureStateTests.swift@@ -7,6 +7,84 @@ import Testing @Suite("Capture state and extension lifecycle", .serialized) struct CaptureStateTests { + @Test("An individual-page, whole-work, then individual-page journey selects the same chapter without losing the draft")+ @MainActor func mixedLayoutThreeStepJourney() async throws {+ let fixture = CaptureStateFixture.taughtSite(), work = UUID(), chapter = UUID(), rule = UUID()+ let binding = EntrySourceEvidence.Binding(origin: .v2, key: "12", ruleID: rule)+ let individual = "https://taught.example/ch12", whole = "https://taught.example/whole", alternate = "https://taught.example/read/ch12"+ for (step, url) in [individual, whole, alternate].enumerated() {+ let entries: [ChapterCaptureEntry] = step == 0 ? [] : [.init(id: chapter, workID: work,+ target: .init(kind: .chapter, designation: "12"), bindings: [binding],+ sourceURLs: step == 1 ? [individual] : [individual, whole], note: "Saved chapter")]+ let evidence: [ChapterCaptureEvidence] = step == 1 ? [] : [.init(origin: .v2, key: "12", ruleID: rule, chapterFact: "12")]+ let projection = ChapterCaptureResolver.project(workID: work, rawURL: url,+ evidence: evidence, entries: entries, captureDefault: step == 2 ? .multipleChaptersPerPage : .ordinary)+ let request = CaptureRequest(captureTitle: "Chapter 12", captureTitleSource: .safariDocument,+ rawURLString: url, canonicalURLString: nil, note: "", rating: nil,+ chapterProjection: projection)+ fixture.coordinator.prepareResult = .success(.init(rawURL: url, resolvedTitle: "Chapter 12",+ titleSource: .safariDocument, canonicalURL: nil, siteStatus: .existingTaught))+ fixture.coordinator.projectCaptureResult = .success(.init(+ basis: CaptureBasis(siteMode: .taught, hostname: "taught.example", activePattern: nil, works: []),+ request: request, outcome: makeReuseOutcome(chapter: "12", workID: work)))+ fixture.coordinator.commitOutcome = .committed(SnapshotTestFixtures.makeEntry(id: chapter))+ let model = CaptureViewModel()+ await model.load(payload: .init(providerURL: url, safari: .init(title: "Chapter 12", locationHref: url)), coordinator: fixture.coordinator)+ if step == 1 {+ model.chooseChapterIntent(.existing(chapter))+ #expect(model.currentDraft?.note == "Saved chapter")+ await model.setNote("Whole-view draft", coordinator: fixture.coordinator)+ model.chooseChapterIntent(.existing(chapter, contentChoice: .source))+ } else {+ #expect(!model.chapterProjection!.offersAnotherChapter)+ if step == 2 { #expect(model.chapterProjection?.resolution == .update(entryID: chapter)) }+ }+ #expect(model.canSave)+ await model.save(coordinator: fixture.coordinator)+ if case .saved(let id) = model.state { #expect(id == chapter) }+ else { Issue.record("Every reviewed stage must save") }+ #expect(fixture.coordinator.lastCommittedContract?.request.rawURLString == url)+ if step == 1 { #expect(fixture.coordinator.lastCommittedContract?.request.note == "Whole-view draft") }+ }+ #expect(fixture.coordinator.commitCaptureCallCount == 3)+ }++ @Test("Whole-page chapter choices preserve edited content and avoid reprojecting on every note edit")+ @MainActor func chapterChoiceContentAndProjection() async throws {+ let fixture = CaptureStateFixture.taughtSite()+ let work = UUID(), first = UUID(), second = UUID()+ let chapterProjection = ChapterCaptureResolver.project(workID: work, rawURL: "https://taught.example/ch5",+ evidence: [], entries: [+ .init(id: first, workID: work, target: .init(kind: .chapter, designation: "5"),+ sourceURLs: ["https://taught.example/ch5"], note: "First", rating: .up),+ .init(id: second, workID: work, target: .init(kind: .chapter, designation: "6"),+ sourceURLs: ["https://taught.example/ch5"], note: "Second", rating: .down)+ ], captureDefault: .ordinary)+ let base = makeContract(outcome: makeReuseOutcome(chapter: "5", workID: work))+ fixture.coordinator.projectCaptureResult = .success(CaptureContract(basis: base.basis,+ request: base.request.withChapterProjection(chapterProjection, intent: .automatic), outcome: base.outcome))+ await fixture.viewModel.load(payload: fixture.defaultPayload, coordinator: fixture.coordinator)+ #expect(!fixture.viewModel.canSave)+ fixture.viewModel.chooseChapterIntent(.existing(first))+ #expect(fixture.viewModel.currentDraft?.note == "First" && fixture.viewModel.currentDraft?.rating == .up)+ fixture.viewModel.chooseChapterIntent(.existing(second))+ #expect(fixture.viewModel.currentDraft?.note == "Second" && fixture.viewModel.currentDraft?.rating == .down)+ let projectionCount = fixture.coordinator.projectCaptureCallCount+ await fixture.viewModel.setNote("Draft", coordinator: fixture.coordinator)+ fixture.viewModel.chooseChapterIntent(.existing(first))+ #expect(fixture.viewModel.currentDraft?.note == "Draft" && !fixture.viewModel.canSave)+ fixture.viewModel.chooseChapterIntent(.existing(first, contentChoice: .source))+ #expect(fixture.viewModel.canSave)+ await fixture.viewModel.setNote("", coordinator: fixture.coordinator)+ await fixture.viewModel.setRating(nil, coordinator: fixture.coordinator)+ fixture.viewModel.chooseChapterIntent(.existing(second))+ #expect(fixture.viewModel.currentDraft?.note.isEmpty == true && fixture.viewModel.currentDraft?.rating == nil)+ #expect(!fixture.viewModel.canSave)+ fixture.viewModel.chooseChapterIntent(.existing(second, contentChoice: .destination))+ #expect(fixture.viewModel.currentDraft?.note == "Second" && fixture.viewModel.canSave)+ #expect(fixture.coordinator.projectCaptureCallCount == projectionCount)+ }+ // MARK: - State machine: loading → ready/invalidInput @Test("State begins as loading before preparation completes")@@ -1070,6 +1148,7 @@ private final class FakeCaptureCoordinating: CaptureCoordinating, @unchecked Sen private var _commitCaptureCallCount = 0 var commitCaptureCallCount: Int { lock.withLock { _commitCaptureCallCount } } var commitOutcome: CaptureCommitOutcome?+ var lastCommittedContract: CaptureContract? var commitShouldThrow = false /// Track legacy save calls — should always be 0 in new flow@@ -1160,6 +1239,7 @@ private final class FakeCaptureCoordinating: CaptureCoordinating, @unchecked Sen } func commitCapture(_ contract: CaptureContract) async throws -> CaptureCommitOutcome {+ lastCommittedContract = contract lock.withLock { _commitCaptureCallCount += 1 } let shouldThrow: Bool = lock.withLock { commitShouldThrow } if shouldThrow {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swiftindex 9bef3cd6..3c3361af 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift@@ -166,6 +166,6 @@ struct CatchUpArchiveTests { return } #expect(reason.contains("format 15/schema 16"))- #expect(reason.contains("(18/19)"))+ #expect(reason.contains("(19/20)")) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swiftindex b328b586..b4a2db72 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) == ["19.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["20.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) == "19",+ #expect(try markerContent(cfg) == "20", "an empty store has nothing to bring forward and is certified at birth (Q26)") withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureResolverTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureResolverTests.swiftnew file mode 100644index 00000000..068235d6--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureResolverTests.swift@@ -0,0 +1,111 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Chapter capture decisions")+struct ChapterCaptureResolverTests {+ let work = UUID(), rule = UUID()+ let page = "https://example.com/whole"+ func evidence(_ key: String, origin: EntrySourceEvidence.Binding.Origin = .v2) -> ChapterCaptureEvidence {+ .init(origin: origin, key: key, ruleID: rule)+ }+ func project(_ entries: [ChapterCaptureEntry], evidence: [ChapterCaptureEvidence] = [],+ captureDefault: ChapterCaptureDefault = .ordinary) -> ChapterCaptureProjection {+ ChapterCaptureResolver.project(workID: work, rawURL: page, evidence: evidence,+ entries: entries, captureDefault: captureDefault)+ }++ @Test("Specific chapter evidence wins over a shared-page association in either mode")+ func specificWins() {+ let twelve = UUID(), thirteen = UUID()+ let entries = [ChapterCaptureEntry(id: twelve, workID: work, bindings: [evidence("12").binding]),+ ChapterCaptureEntry(id: thirteen, workID: work, bindings: [evidence("13").binding], sourceURLs: [page])]+ for mode in [ChapterCaptureDefault.ordinary, .multipleChaptersPerPage] {+ let result = project(entries, evidence: [evidence("12")], captureDefault: mode)+ #expect(result.resolution == .update(entryID: twelve))+ #expect(!result.offersAnotherChapter)+ }+ }+ @Test("Saved and new URL defaults remain ordinary; multiple mode begins a chapter draft")+ func defaults() {+ let id = UUID()+ let entries = [ChapterCaptureEntry(id: id, workID: work, sourceURLs: [page])]+ #expect(project(entries).resolution == .update(entryID: id))+ #expect(project([]).resolution == .newEntry)+ #expect(project(entries, captureDefault: .multipleChaptersPerPage).resolution == .newChapter(requiresConfirmation: true))+ #expect(project(entries).offersAnotherChapter)+ }+ @Test("Mixed layout and manual untitled chapters require selection before a new chapter")+ func incomparable() {+ let id = UUID()+ let entries = [ChapterCaptureEntry(id: id, workID: work, target: .init(kind: .chapter), sourceURLs: [page])]+ #expect(project(entries, evidence: [evidence("12")]).resolution == .chooseChapter(entryIDs: [id], reason: "Choose an existing chapter or confirm a new one"))+ #expect(!project(entries, evidence: [evidence("12")]).offersAnotherChapter)+ }+ @Test("Generic untitled notes do not force chapter selection or match an empty label")+ func notes() {+ let entry = ChapterCaptureEntry(id: UUID(), workID: work, target: .init(kind: .note))+ #expect(project([entry], evidence: [evidence("12")]).resolution == .newChapter(requiresConfirmation: false))+ }+ @Test("Conflicting specific keys and torn targets require review")+ func conflicts() {+ let a = UUID(), b = UUID()+ let entries = [ChapterCaptureEntry(id: a, workID: work, bindings: [evidence("12").binding]),+ ChapterCaptureEntry(id: b, workID: work, bindings: [evidence("13", origin: .v3).binding])]+ if case .chooseChapter(let ids, _) = project(entries, evidence: [evidence("12"), evidence("13", origin: .v3)]).resolution {+ #expect(Set(ids) == [a, b])+ } else { Issue.record("Conflicting chapter keys must require selection") }+ let torn = ChapterCaptureEntry(id: a, workID: work, bindings: [evidence("12").binding], requiresReview: true)+ if case .chooseChapter = project([torn], evidence: [evidence("12")]).resolution {} else {+ Issue.record("A torn target must never update automatically")+ }+ }+ @Test("A novel display title does not contradict a unique taught key")+ func newDisplayTitle() {+ let twelve = UUID(), thirteen = UUID()+ let key = evidence("12")+ let label = evidence("New display title", origin: .designation)+ let known = ChapterCaptureEntry(id: twelve, workID: work, bindings: [key.binding])+ #expect(project([known], evidence: [key, label]).resolution == .update(entryID: twelve))+ let another = ChapterCaptureEntry(id: thirteen, workID: work, bindings: [label.binding])+ if case .chooseChapter(let ids, _) = project([known, another], evidence: [key, label]).resolution {+ #expect(Set(ids) == [twelve, thirteen])+ } else { Issue.record("A positively matched other chapter contradicts the taught key") }+ }++ @Test("An unsaved conflicting chapter key never permits a sole existing update")+ func unmatchedConflict() {+ let id = UUID()+ let twelve = ChapterCaptureEvidence(origin: .v2, key: "12", ruleID: rule, chapterFact: "12")+ let thirteen = ChapterCaptureEvidence(origin: .v3, key: "13", ruleID: rule, chapterFact: "13")+ let entry = ChapterCaptureEntry(id: id, workID: work, bindings: [twelve.binding])+ #expect(project([entry], evidence: [twelve, thirteen]).resolution == .chooseChapter(entryIDs: [id], reason: "The chapter evidence disagrees"))+ let note = ChapterCaptureEntry(id: id, workID: work, target: .init(kind: .note), bindings: [twelve.binding])+ #expect(project([note], evidence: [twelve]).resolution == .newChapter(requiresConfirmation: false))+ }++ @Test("Scalar-distinct composed and decomposed designations never bind together")+ func unicodeDesignation() {+ let composed = evidence("é", origin: .designation)+ let decomposed = evidence("e\u{301}", origin: .designation)+ #expect(composed.binding != decomposed.binding)+ #expect(Set([composed.binding, decomposed.binding]).count == 2)+ let id = UUID()+ let entry = ChapterCaptureEntry(id: id, workID: work, bindings: [composed.binding])+ #expect(project([entry], evidence: [decomposed]).resolution == .newChapter(requiresConfirmation: false))+ #expect(AuthoredEntryTarget(kind: .chapter, designation: "é") != AuthoredEntryTarget(kind: .chapter, designation: "e\u{301}"))+ }++ @Test("Work scope and exact namespace keep site-wide IDs and spellings independent")+ func scope() {+ let id = UUID()+ let entry = ChapterCaptureEntry(id: id, workID: work, bindings: [evidence("012").binding])+ #expect(project([entry], evidence: [evidence("12")]).resolution == .newChapter(requiresConfirmation: false))+ let foreign = ChapterCaptureEntry(id: id, workID: UUID(), bindings: [evidence("12").binding])+ #expect(project([foreign], evidence: [evidence("12")]).resolution == .newChapter(requiresConfirmation: false))+ let manual = ChapterCaptureEntry(id: id, workID: work, target: .init(kind: .chapter, designation: "12"))+ if case .chooseChapter = project([manual], evidence: [evidence("site-wide-1200")]).resolution {} else {+ Issue.record("Ordering numbers do not establish chapter identity")+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureTransactionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureTransactionTests.swiftnew file mode 100644index 00000000..68fe53f4--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureTransactionTests.swift@@ -0,0 +1,368 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Chapter capture transactions", .serialized)+struct ChapterCaptureTransactionTests {+ @Test("Automatic clear chapters on one source do not silently teach a work default")+ func automaticSamePageDoesNotLearn() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ try await fixture.repository.seedTitleOnlyChapterRule()+ let page = "https://example.com/whole"+ for title in ["Book - 12", "Book - 13"] {+ let projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: title, workID: work.id)+ #expect(projection.resolution == .newChapter(requiresConfirmation: false))+ guard case .committed = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: .init(captureTitle: title, captureTitleSource: .manual, rawURLString: page, note: title), intent: .automatic)) else {+ Issue.record("Clear chapter must save"); return+ }+ }+ #expect(try await fixture.repository.work(id: work.id).chapterCaptureDefault == .ordinary)+ #expect(try await fixture.repository.projectManualEntry(workID: work.id).entries.count == 2)+ }+ @Test("Title-only legacy identity remains matched after manual or combine-destination promotion", arguments: [false, true])+ func titleOnlyLegacyPromotion(combine: Bool) async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ try await fixture.repository.seedTitleOnlyChapterRule()+ let page = "https://example.com/first"+ let initial = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book - 12", workID: work.id)+ guard case .committed(let legacy) = try await fixture.repository.commitChapterCapture(.init(projection: initial,+ capture: .init(captureTitle: "Book - 12", captureTitleSource: .manual, rawURLString: page, note: "Saved"), intent: .automatic)) else {+ Issue.record("Legacy chapter must save"); return+ }+ #expect(legacy.authoredTarget == nil)+ let manual = try await fixture.repository.projectManualEntry(workID: work.id)+ if combine {+ guard case .committed(let other) = try await fixture.repository.commitManualEntry(projection: manual,+ draft: .init(target: .init(kind: .chapter, designation: "13"), note: "Other", confirmedNewChapter: true)) else {+ Issue.record("Source must save"); return+ }+ let correction = try await fixture.repository.projectEntryCorrection(entryID: other.id, destinationID: legacy.id)+ #expect(try await fixture.repository.commitEntryCorrection(correction,+ target: .init(kind: .chapter, designation: "13"), contentChoice: .destination) == .committed(entryID: legacy.id))+ } else {+ guard case .committed = try await fixture.repository.commitManualEntry(projection: manual,+ draft: .init(target: .init(kind: .chapter, title: "12"), note: "Saved", existingEntryID: legacy.id)) else {+ Issue.record("Manual promotion must save"); return+ }+ }+ let alternate = try await fixture.repository.projectChapterCapture(rawURL: "https://example.com/alternate", captureTitle: "Book - 12", workID: work.id)+ #expect(alternate.resolution == .update(entryID: legacy.id))+ }+ @Test("A late source link refreshes an ordinary new capture even when the work revision stays unchanged")+ func lateSourceArrival() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ let manual = try await fixture.repository.projectManualEntry(workID: work.id)+ guard case .committed(let chapter) = try await fixture.repository.commitManualEntry(projection: manual,+ draft: .init(target: .init(kind: .chapter, designation: "12"), note: "Saved")) else {+ Issue.record("Chapter must save"); return+ }+ let page = "https://example.com/late"+ let base = try await fixture.repository.projectCapture(hostname: "example.com", captureTitle: "Book",+ captureTitleSource: .manual, rawURLString: page, canonicalURLString: nil, note: "Draft", rating: nil)+ let chapters = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ #expect(chapters.resolution == .newEntry)+ let contract = CaptureContract(basis: base.basis,+ request: base.request.withChapterProjection(chapters, intent: .automatic), outcome: base.outcome)+ let before = try await fixture.repository.work(id: work.id)+ try await fixture.repository.arriveChapterTestSource(entryID: chapter.id, url: page)+ #expect(try await fixture.repository.work(id: work.id).modifiedAt == before.modifiedAt)+ guard case .refreshed(let fresh) = try await fixture.repository.commitCapture(contract) else {+ Issue.record("The new source must require renewed review, never create a second entry"); return+ }+ #expect(fresh.request.note == "Draft")+ #expect(fresh.request.chapterProjection?.resolution == .update(entryID: chapter.id))+ #expect(try await fixture.repository.projectManualEntry(workID: work.id).entries.count == 1)+ #expect(try await fixture.repository.entry(id: chapter.id).note == "Saved")+ }+ @Test("An explicit existing chapter choice authors UUID identity even without detected chapter evidence")+ func explicitLegacyChoiceWithoutEvidence() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ let firstURL = "https://example.com/chapter"+ let initial = try await fixture.repository.projectChapterCapture(rawURL: firstURL, captureTitle: "Book", workID: work.id)+ guard case .committed(let legacy) = try await fixture.repository.commitChapterCapture(.init(projection: initial,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: firstURL, note: "Saved"),+ intent: .automatic)) else { Issue.record("Ordinary capture must save"); return }+ #expect(legacy.authoredTarget == nil)+ let alternate = "https://example.com/whole"+ let projection = try await fixture.repository.projectChapterCapture(rawURL: alternate, captureTitle: "Book", workID: work.id)+ #expect(projection.evidence.isEmpty)+ guard case .committed(let chosen) = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: alternate),+ intent: .existing(legacy.id))) else { Issue.record("Explicit chapter choice must save"); return }+ #expect(chosen.id == legacy.id && chosen.authoredTarget?.kind == .chapter)+ #expect(chosen.note == "Saved")+ #expect(Set(chosen.sourceURLs) == Set([firstURL, alternate]))+ }++ @Test("Rejected detected evidence stays rejected after a retained owner receives late authored content")+ func lateCorrectedOwner() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ try await fixture.repository.seedChapterCaptureTestRule()+ let page = "https://example.com/chapter?w=book&c=12"+ let projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ guard case .committed(let corrected) = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: page, note: "Saved", rating: .up),+ intent: .correctedNewChapter(.init(kind: .chapter, designation: "13")))) else {+ Issue.record("Correction must save"); return+ }+ let manual = try await fixture.repository.projectManualEntry(workID: work.id)+ guard case .committed(let survivor) = try await fixture.repository.commitManualEntry(projection: manual,+ draft: .init(target: .init(kind: .chapter, designation: "14"), note: "Saved", rating: .up, confirmedNewChapter: true)) else {+ Issue.record("Destination must save"); return+ }+ let combine = try await fixture.repository.projectEntryCorrection(entryID: corrected.id, destinationID: survivor.id)+ #expect(try await fixture.repository.commitEntryCorrection(combine, target: .init(kind: .chapter, designation: "13"), contentChoice: .destination) == .committed(entryID: survivor.id))+ let export = try await fixture.repository.entryExportInput(entryID: corrected.id, locale: Locale(identifier: "en_US"))+ let reopened = try await fixture.repository.entry(id: corrected.id)+ #expect(export.headingText == reopened.authoredTarget?.designation && export.note == reopened.note)+ try await fixture.repository.lateChapterCaptureTestNote(entryID: corrected.id)+ let late = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ #expect(late.evidence.isEmpty)+ if case .chooseChapter = late.resolution {} else { Issue.record("Late content needs review") }+ }++ @Test("Choosing an existing chapter preserves saved content until the reader chooses a replacement")+ func existingSelectionContent() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ let page = "https://example.com/whole"+ let initial = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ guard case .committed(let chapter) = try await fixture.repository.commitChapterCapture(.init(projection: initial,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: page, note: "Saved", rating: .up),+ intent: .newChapter(.init(kind: .chapter, designation: "12"), confirmedNew: true))) else {+ Issue.record("Chapter must save"); return+ }+ let otherPage = "https://example.com/other"+ var projection = try await fixture.repository.projectChapterCapture(rawURL: otherPage, captureTitle: "Book", workID: work.id)+ guard case .committed(let selected) = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: otherPage), intent: .existing(chapter.id))) else {+ Issue.record("A pristine selection must preserve existing content"); return+ }+ #expect(selected.note == "Saved" && selected.rating == .up)+ projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ let result = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: page, note: "Draft", rating: .down),+ intent: .existing(chapter.id)))+ if case .reviewRequired = result {} else { Issue.record("Different authored contents require a choice") }+ let saved = try await fixture.repository.entry(id: chapter.id)+ #expect(saved.note == "Saved" && saved.rating == .up)+ }++ @Test("Share correction rejects detected keys rather than teaching them to the corrected chapter")+ func shareCorrection() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ try await fixture.repository.seedChapterCaptureTestRule()+ let page = "https://example.com/chapter?w=book&c=12"+ let projected = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ let corrected = try await fixture.repository.commitChapterCapture(.init(projection: projected,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: page, note: "Actually thirteen"),+ intent: .correctedNewChapter(.init(kind: .chapter, designation: "13"))))+ guard case .committed(let entry) = corrected else { Issue.record("Correction must save"); return }+ let samePage = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ #expect(samePage.evidence.isEmpty && samePage.resolution == .update(entryID: entry.id))+ let actualTwelve = try await fixture.repository.projectChapterCapture(rawURL: "https://example.com/other?w=book&c=12", captureTitle: "Book", workID: work.id)+ #expect(actualTwelve.resolution != .update(entryID: entry.id))+ #expect(try await fixture.repository.work(id: work.id).chapterCaptureDefault == .ordinary)+ let contract = try await fixture.repository.projectEntryCorrection(entryID: entry.id)+ #expect(try await fixture.repository.commitEntryCorrection(contract, target: .init(kind: .note, title: "12")) == .committed(entryID: entry.id))+ let note = try await fixture.repository.entry(id: entry.id)+ #expect(note.chapterTitle == nil && note.chapterSequence == nil && note.authoredNoteTitle == "12")+ #expect(try await fixture.repository.projectChapterCapture(rawURL: "https://example.com/other?w=book&c=12", captureTitle: "Book", workID: work.id).resolution == .newChapter(requiresConfirmation: false))+ }++ @Test("New blank captures promote To Read; existing re-shares do not")+ func captureStatus() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com", readingStatus: .toRead))+ let page = "https://example.com/whole"+ var projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ if case .committed = try await fixture.repository.commitChapterCapture(+ .init(projection: projection, capture: .init(captureTitle: "Book", captureTitleSource: .manual,+ rawURLString: page), intent: .genericNote)) {} else { Issue.record("Blank capture must save") }+ #expect(try await fixture.repository.work(id: work.id).readingStatus == .reading)+ try await fixture.repository.setChapterCaptureTestStatus(workID: work.id, status: .toRead)+ projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ if case .committed = try await fixture.repository.commitChapterCapture(+ .init(projection: projection, capture: .init(captureTitle: "Book", captureTitleSource: .manual,+ rawURLString: page, note: "Re-share"), intent: .automatic)) {} else { Issue.record("Re-share must save") }+ #expect(try await fixture.repository.work(id: work.id).readingStatus == .toRead)+ }++ @Test("A drained different URL adds a chapter source without authored overwrite, and replay is a no-op")+ func drainedChapterSource() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ try await fixture.repository.seedChapterCaptureTestRule()+ let original = "https://example.com/chapter?w=book&c=12"+ let alternate = "https://example.com/whole?w=book&c=12"+ let initial = try await fixture.repository.projectChapterCapture(rawURL: original, captureTitle: "Book", workID: work.id)+ let id: UUID+ if case .committed(let entry) = try await fixture.repository.commitChapterCapture(+ .init(projection: initial, capture: .init(captureTitle: "Book", captureTitleSource: .manual,+ rawURLString: original, note: "Keep", rating: .up), intent: .automatic)) { id = entry.id }+ else { Issue.record("First specific chapter must save"); return }+ let projection = try await fixture.repository.projectChapterCapture(rawURL: alternate, captureTitle: "Book", workID: work.id)+ #expect(projection.resolution == .update(entryID: id))+ let target = DrainedReShareTarget(entryID: id, hostname: "example.com", identityKey: "entry/\(id.uuidString.lowercased())", chapterProjection: projection)+ let sharedAt = Date(timeIntervalSince1970: 2_000_000_000)+ #expect(try await fixture.repository.recordDrainedReShare(target: target, sharedAt: sharedAt) == .committed)+ let saved = try await fixture.repository.entry(id: id)+ #expect(saved.note == "Keep" && saved.rating == .up && saved.lastSharedAt == sharedAt)+ let after = try await fixture.repository.projectChapterCapture(rawURL: alternate, captureTitle: "Book", workID: work.id)+ #expect(after.entries.first?.sourceURLs.contains(ExactScalarString(alternate)) == true)+ #expect(try await fixture.repository.recordDrainedReShare(target: target, sharedAt: sharedAt) == .committed)+ #expect(try await fixture.repository.entry(id: id).modifiedAt == saved.modifiedAt)+ #expect(try await fixture.repository.chapterCaptureFacts(workID: work.id).count == 1)+ }++ @Test("A stale authored note/rating preserves both saved edit and immutable capture draft")+ func staleContent() async throws {+ let fixture = try await M5Fixture()+ let work = UUID(), entry = UUID()+ try await fixture.repository.seedM5Rows(+ sites: [.init(hostname: "example.com")],+ works: [.init(id: work, displayTitle: "Book", hostname: "example.com")],+ entries: [.init(id: entry, captureTitle: "Book", hostname: "example.com", path: "page", note: "Before", workID: work)])+ let projection = try await fixture.repository.projectChapterCapture(rawURL: "https://example.com/page", captureTitle: "Book", workID: work)+ let capture = CaptureDraft(captureTitle: "Book", captureTitleSource: .manual,+ rawURLString: "https://example.com/page", note: "Draft note", rating: .up)+ let draft = ChapterCaptureDraft(projection: projection, capture: capture, intent: .automatic)+ try await fixture.repository.updateEntry(id: entry, note: "Other device", rating: .down)+ if case .reviewRequired = try await fixture.repository.commitChapterCapture(draft) {} else {+ Issue.record("A concurrent authored edit must require review")+ }+ let current = try await fixture.repository.entry(id: entry)+ #expect(current.note == "Other device" && current.rating == .down)+ #expect(draft.capture.note == "Draft note" && draft.capture.rating == .up)+ }++ @Test("Distinct confirmed same-page chapters survive reconcile and teach the work default atomically")+ func samePageChapters() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ let page = "https://example.com/whole"+ for designation in ["12", "13"] {+ let projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ let draft = ChapterCaptureDraft(projection: projection,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: page, note: designation),+ intent: .newChapter(.init(kind: .chapter, designation: designation), confirmedNew: true))+ if case .committed = try await fixture.repository.commitChapterCapture(draft) {} else {+ Issue.record("An explicitly confirmed different chapter must save")+ }+ }+ let facts = try await fixture.repository.chapterCaptureFacts(workID: work.id)+ #expect(facts.count == 2)+ #expect(facts.captureDefault == .multipleChaptersPerPage)+ #expect(facts.duplicateSets == 0)+ let projected = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ #expect(projected.resolution == .newChapter(requiresConfirmation: true))+ }++ @Test("Choosing one of two linked generic notes updates it without changing kind")+ func chooseGenericNote() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ let page = "https://example.com/whole"+ var ids: [UUID] = []+ for note in ["First", "Second"] {+ let projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ if case .committed(let entry) = try await fixture.repository.commitChapterCapture(+ .init(projection: projection, capture: .init(captureTitle: "Book", captureTitleSource: .manual,+ rawURLString: page, note: note), intent: .genericNote)) { ids.append(entry.id) }+ }+ #expect(ids.count == 2)+ let projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ if case .chooseChapter(let candidates, _) = projection.resolution { #expect(Set(candidates) == Set(ids)) }+ else { Issue.record("Two linked notes need an entry choice") }+ let id = try #require(ids.first)+ if case .committed(let updated) = try await fixture.repository.commitChapterCapture(+ .init(projection: projection, capture: .init(captureTitle: "Book", captureTitleSource: .manual,+ rawURLString: page, note: "Updated"), intent: .existing(id, contentChoice: .source))) {+ #expect(updated.note == "Updated" && updated.authoredTarget?.kind == .note)+ } else { Issue.record("The selected generic note must be updateable") }+ #expect(try await fixture.repository.chapterCaptureFacts(workID: work.id).count == 2)+ }++ @Test("A generic note neither teaches multiple-page behavior nor becomes a chapter")+ func genericNote() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ let page = "https://example.com/whole"+ for _ in 0..<2 {+ let projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ if case .committed(let snapshot) = try await fixture.repository.commitChapterCapture(+ .init(projection: projection, capture: .init(captureTitle: "Book", captureTitleSource: .manual,+ rawURLString: page, rating: .up), intent: .genericNote)) {+ #expect(snapshot.authoredTarget?.kind == .note)+ #expect(snapshot.chapterSequence == nil)+ } else { Issue.record("Generic rating-only notes must save independently") }+ }+ let facts = try await fixture.repository.chapterCaptureFacts(workID: work.id)+ #expect(facts.count == 2 && facts.captureDefault == .ordinary && facts.duplicateSets == 0)+ }+}++private struct ChapterCaptureFacts: Sendable {+ let count: Int+ let captureDefault: ChapterCaptureDefault+ let duplicateSets: Int+}+extension LibraryRepository {+ fileprivate func seedTitleOnlyChapterRule() async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding title-only rule") { context in+ let site = try #require(Self.fetchSites(hostname: "example.com", context: context).first)+ site.mode = .taught+ context.insert(try TitlePattern(version: 1, isActive: true, createdAt: M5Fixture.epoch, definition: .phrase(prefix: "", separator: " - ", suffix: "", order: .workThenChapter), site: site))+ try context.save()+ }+ }+ fileprivate func arriveChapterTestSource(entryID: UUID, url: String) async throws {+ try await withLockedContext(mode: .exclusive, operation: "receiving a delayed source") { context in+ context.insert(EntrySource(entryID: entryID, urlString: url, hostname: "example.com", timestamp: M5Fixture.epoch))+ try context.save()+ }+ }+ fileprivate func lateChapterCaptureTestNote(entryID: UUID) async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding late authored content") { context in+ for row in try Self.fetchNormalisedEntryGroup(id: entryID, context: context).rows {+ row.note = "Late offline note"; row.rating = .down+ }+ try context.save()+ }+ }+ fileprivate func setChapterCaptureTestStatus(workID: UUID, status: ReadingStatus) async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding capture status") { context in+ for row in try Self.fetchWorkGroup(id: workID, context: context).rows { row.readingStatus = status }+ try context.save()+ }+ }+ fileprivate func seedChapterCaptureTestRule() async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding capture rule") { context in+ let site = try #require(Self.fetchSites(hostname: "example.com", context: context).first)+ site.mode = .taught+ context.insert(try TitlePattern(version: 1, isActive: true, createdAt: M5Fixture.epoch, definition: .wholeTitle, site: site))+ let rule = try URLRulePattern(version: 1, isCurrent: true, createdAt: M5Fixture.epoch,+ origin: .readerTaught, definition: .workAndSequence(+ work: .init(locator: .query(name: ExactScalarString("w"))),+ sequence: .init(locator: .query(name: ExactScalarString("c")))), site: site)+ context.insert(rule)+ try context.save()+ }+ }+ fileprivate func chapterCaptureFacts(workID: UUID) async throws -> ChapterCaptureFacts {+ try await withLockedContext(mode: .shared, operation: "reading chapter capture facts") { context in+ let entries = try context.fetch(FetchDescriptor<Entry>())+ return ChapterCaptureFacts(count: Self.entryGroups(entries, canonicalWorkIDs: [:]).count,+ captureDefault: try Self.fetchWorkGroup(id: workID, context: context).carrier.chapterCaptureDefault,+ duplicateSets: try DuplicateScan.run(context: context).entrySets.count)+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swiftnew file mode 100644index 00000000..77f57dc0--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swift@@ -0,0 +1,201 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Chapter correction transactions", .serialized)+struct ChapterCorrectionTests {+ @Test("Clean retained losers do not count as current no-episode notes")+ func combinedNoEpisodeFacts() throws {+ let container = try ModelContainer(for: Schema(AsterismSchemaV20.models),+ configurations: ModelConfiguration(isStoredInMemoryOnly: true))+ let context = ModelContext(container)+ let work = Work(displayTitle: "Book", timestamp: M5Fixture.epoch)+ context.insert(work)+ let loser = Entry(captureTitle: "12", captureTitleSource: .manual, rawURLString: "https://example.com/a", hostname: "example.com", entryIdentityKey: "a", timestamp: M5Fixture.epoch)+ let survivor = Entry(captureTitle: "13", captureTitleSource: .manual, rawURLString: "https://example.com/b", hostname: "example.com", entryIdentityKey: "b", timestamp: M5Fixture.epoch.addingTimeInterval(86_400))+ context.insert(loser); context.insert(survivor); loser.work = work; survivor.work = work+ loser.mergeResolutionData = try EntryMergeResolution(entry: loser).encoded()+ loser.mergedIntoEntryID = survivor.id+ let calendar = Calendar(identifier: .gregorian)+ let facts = NoEpisodeWriter.facts(rows: [loser, survivor], calendar: calendar)+ #expect(facts.count == 1 && facts.first?.entryID == survivor.id)+ loser.note = "Late offline reaction"+ #expect(NoEpisodeWriter.facts(rows: [loser, survivor], calendar: calendar).count == 2)+ }++ @Test("Failed correction keeps source ownership, evidence and both authored contents")+ func failedSave() async throws {+ let saves = InstrumentedSaveStrategy()+ let fixture = try await M5Fixture(saveStrategy: saves)+ let work = UUID(), loser = UUID(), survivor = UUID()+ try await fixture.repository.seedM5Rows(+ sites: [.init(hostname: "example.com")],+ works: [.init(id: work, displayTitle: "Book", hostname: "example.com")],+ entries: [+ .init(id: loser, captureTitle: "First", hostname: "example.com", path: "a", note: "First note", workID: work),+ .init(id: survivor, captureTitle: "Second", hostname: "example.com", path: "b", note: "Second note", workID: work)+ ])+ try await fixture.repository.seedChapterSource(entryID: loser)+ let before = try await fixture.repository.chapterTransactionState()+ let contract = try await fixture.repository.projectEntryCorrection(entryID: loser, destinationID: survivor)+ saves.resetCounts(); saves.shouldFail = true+ await #expect(throws: (any Error).self) {+ try await fixture.repository.commitEntryCorrection(contract,+ target: .init(kind: .chapter, designation: "12"), contentChoice: .source)+ }+ #expect(saves.attemptCount == 1)+ #expect(saves.successCount == 0)+ #expect(try await fixture.repository.chapterTransactionState() == before)+ // The same immutable review draft remains usable on retry.+ saves.shouldFail = false+ #expect(try await fixture.repository.commitEntryCorrection(contract,+ target: .init(kind: .chapter, designation: "12"), contentChoice: .source) == .committed(entryID: survivor))+ }++ @Test("Missing content choice refuses before mutating sources")+ func refusalBeforeMutation() async throws {+ let saves = InstrumentedSaveStrategy()+ let fixture = try await M5Fixture(saveStrategy: saves)+ let work = UUID(), loser = UUID(), survivor = UUID()+ try await fixture.repository.seedM5Rows(+ sites: [.init(hostname: "example.com")],+ works: [.init(id: work, displayTitle: "Book", hostname: "example.com")],+ entries: [+ .init(id: loser, captureTitle: "First", hostname: "example.com", path: "a", note: "First", workID: work),+ .init(id: survivor, captureTitle: "Second", hostname: "example.com", path: "b", note: "Second", workID: work)+ ])+ try await fixture.repository.seedChapterSource(entryID: loser)+ let before = try await fixture.repository.chapterTransactionState()+ let contract = try await fixture.repository.projectEntryCorrection(entryID: loser, destinationID: survivor)+ saves.resetCounts()+ #expect(try await fixture.repository.commitEntryCorrection(contract,+ target: .init(kind: .chapter, designation: "12")) == .reviewRequired(reason: "Choose which note and rating to keep"))+ #expect(saves.attemptCount == 0)+ #expect(try await fixture.repository.chapterTransactionState() == before)+ }++ @Test("Work delete cascades clean redirects and late loser-addressed sources")+ func deleteWork() async throws {+ let fixture = try await M5Fixture()+ let work = UUID(), loser = UUID(), survivor = UUID()+ try await fixture.repository.seedM5Rows(+ sites: [.init(hostname: "example.com")],+ works: [.init(id: work, displayTitle: "Book", hostname: "example.com")],+ entries: [+ .init(id: loser, captureTitle: "First", hostname: "example.com", path: "a", workID: work),+ .init(id: survivor, captureTitle: "Second", hostname: "example.com", path: "b", workID: work)+ ])+ let correction = try await fixture.repository.projectEntryCorrection(entryID: loser, destinationID: survivor)+ #expect(try await fixture.repository.commitEntryCorrection(correction,+ target: .init(kind: .chapter, designation: "12")) == .committed(entryID: survivor))+ try await fixture.repository.seedChapterSource(entryID: loser)+ let deletion = try await fixture.repository.projectWorkDeletion(workID: work)+ #expect(deletion.entryGroupIDs == [survivor])+ #expect(deletion.retainedEntryGroupIDs == [loser])+ #expect(try await fixture.repository.commitWorkDeletion(deletion,+ disposition: .deleteEntries, disclosedVariants: nil) == .committed)+ let state = try await fixture.repository.chapterTransactionState()+ #expect(state.entries.isEmpty)+ #expect(state.sources.isEmpty)+ }++ @Test("Moving a survivor retains alias routing after deleting its former work")+ func moveSurvivor() async throws {+ let fixture = try await M5Fixture()+ let former = UUID(), destination = UUID(), loser = UUID(), survivor = UUID()+ try await fixture.repository.seedM5Rows(+ sites: [.init(hostname: "example.com")],+ works: [.init(id: former, displayTitle: "Former", hostname: "example.com"),+ .init(id: destination, displayTitle: "Destination", hostname: "example.com")],+ entries: [+ .init(id: loser, captureTitle: "First", hostname: "example.com", path: "a", workID: former),+ .init(id: survivor, captureTitle: "Second", hostname: "example.com", path: "b", workID: former)+ ])+ let correction = try await fixture.repository.projectEntryCorrection(entryID: loser, destinationID: survivor)+ #expect(try await fixture.repository.commitEntryCorrection(correction,+ target: .init(kind: .chapter, designation: "12")) == .committed(entryID: survivor))+ try await fixture.repository.moveEntry(survivor, to: .existing(destination))+ try await fixture.repository.seedChapterSource(entryID: loser)+ let deletion = try await fixture.repository.projectWorkDeletion(workID: former)+ #expect(deletion.entryGroupIDs.isEmpty && deletion.retainedEntryGroupIDs.isEmpty)+ #expect(try await fixture.repository.commitWorkDeletion(deletion,+ disposition: .deleteEntries, disclosedVariants: nil) == .committed)+ let state = try await fixture.repository.chapterTransactionState()+ #expect(state.entries.count == 2)+ #expect(state.entries.allSatisfy { $0.workID == destination })+ #expect(state.entries.first { $0.id == loser }?.resolved == true)+ #expect(state.sources.contains { $0.owner == loser && $0.url == "https://example.com/late" })+ #expect(try await fixture.repository.entry(id: loser).id == survivor)+ }++ @Test("Work detach moves clean baselines but keeps late authored changes visible")+ func detachWork() async throws {+ for offlineEdit in [false, true] {+ let fixture = try await M5Fixture()+ let work = UUID(), loser = UUID(), survivor = UUID()+ try await fixture.repository.seedM5Rows(+ sites: [.init(hostname: "example.com")],+ works: [.init(id: work, displayTitle: "Book", hostname: "example.com")],+ entries: [+ .init(id: loser, captureTitle: "First", hostname: "example.com", path: "a", workID: work),+ .init(id: survivor, captureTitle: "Second", hostname: "example.com", path: "b", workID: work)+ ])+ let correction = try await fixture.repository.projectEntryCorrection(entryID: loser, destinationID: survivor)+ #expect(try await fixture.repository.commitEntryCorrection(correction,+ target: .init(kind: .chapter, designation: "12")) == .committed(entryID: survivor))+ try await fixture.repository.seedChapterSource(entryID: loser, offlineNote: offlineEdit ? "Offline note" : nil)+ let deletion = try await fixture.repository.projectWorkDeletion(workID: work)+ #expect(try await fixture.repository.commitWorkDeletion(deletion,+ disposition: .detachEntries, disclosedVariants: nil) == .committed)+ let state = try await fixture.repository.chapterTransactionState()+ #expect(state.entries.allSatisfy { $0.workID == nil && $0.unattached })+ let retained = try #require(state.entries.first { $0.id == loser })+ #expect(retained.resolved == !offlineEdit)+ #expect(retained.note == (offlineEdit ? "Offline note" : ""))+ #expect(!state.sources.isEmpty)+ let reopened = try await fixture.repository.entry(id: loser)+ #expect(reopened.id == (offlineEdit ? loser : survivor))+ #expect(reopened.changesAfterCombine == offlineEdit)+ }+ }+}++private struct ChapterTransactionState: Equatable, Sendable {+ struct EntryValue: Equatable, Sendable {+ let id: UUID, workID: UUID?, redirect: UUID?+ let note: String, target: Data?, baseline: Data?, resolved: Bool, unattached: Bool+ }+ struct SourceValue: Equatable, Sendable {+ let id: UUID, owner: UUID, url: String, evidence: Data?, modified: Date+ }+ let entries: [EntryValue], sources: [SourceValue]+}++extension LibraryRepository {+ fileprivate func seedChapterSource(entryID: UUID, offlineNote: String? = nil) async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding delayed source") { context in+ context.insert(EntrySource(entryID: entryID, urlString: "https://example.com/late", hostname: "example.com", timestamp: M5Fixture.epoch,+ evidenceData: try EntrySourceEvidence().encoded()))+ if let offlineNote {+ for row in try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { $0.id == entryID })) {+ row.note = offlineNote+ }+ }+ try context.save()+ }+ }+ fileprivate func chapterTransactionState() async throws -> ChapterTransactionState {+ try await withLockedContext(mode: .shared, operation: "reading chapter transaction") { context in+ ChapterTransactionState(+ entries: try context.fetch(FetchDescriptor<Entry>()).map {+ .init(id: $0.id, workID: $0.work?.id, redirect: $0.mergedIntoEntryID, note: $0.note,+ target: $0.authoredTargetData, baseline: $0.mergeResolutionData,+ resolved: $0.isResolvedRedirect, unattached: $0.intentionallyUnattached)+ }.sorted { $0.id.uuidString < $1.id.uuidString },+ sources: try context.fetch(FetchDescriptor<EntrySource>()).map {+ .init(id: $0.id, owner: $0.entryID, url: $0.urlString, evidence: $0.evidenceData, modified: $0.modifiedAt)+ }.sorted { $0.id.uuidString < $1.id.uuidString })+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swiftnew file mode 100644index 00000000..32ddf316--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swift@@ -0,0 +1,228 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Authored chapter identity", .serialized)+struct ChapterIdentityTests {+ @Test("Distinct explicit chapters sharing one page never form a collapse set")+ func samePage() throws {+ let fixture = try ChapterIdentityFixture()+ fixture.add(designation: "12")+ fixture.add(designation: "13")+ try fixture.context.save()+ #expect(try DuplicateScan.run(context: fixture.context).entrySets.isEmpty)+ }++ @Test("Authored target differences in one UUID require content review")+ func targetIsAuthoredContent() throws {+ let fixture = try ChapterIdentityFixture()+ let id = UUID()+ let a = fixture.add(id: id, designation: "12")+ let b = fixture.add(id: id, designation: "13")+ let group = try #require(LibraryRepository.entryGroups([a, b], canonicalWorkIDs: [:])[id])+ #expect(group.isTorn)+ }++ @Test("Independent URL-free generic notes and chapters keep UUID identity")+ func independentNotes() throws {+ let fixture = try ChapterIdentityFixture()+ fixture.add(designation: nil, url: "")+ fixture.add(designation: nil, url: "")+ try fixture.context.save()+ #expect(try fixture.context.fetchCount(FetchDescriptor<Entry>()) == 2)+ #expect(try DuplicateScan.run(context: fixture.context).entrySets.isEmpty)+ }+ @Test("Canonical target spelling does not create false authored conflicts")+ func canonicalTarget() throws {+ let fixture = try ChapterIdentityFixture()+ let id = UUID()+ let a = fixture.add(id: id, designation: "12")+ let b = fixture.add(id: id, designation: "12")+ b.authoredTargetData = Data(#"{ "designation": " 12 ", "kind": "chapter", "title": " " }"#.utf8)+ #expect(GroupOrdering.authoredContent(of: a) == GroupOrdering.authoredContent(of: b))+ b.authoredTargetData = try AuthoredEntryTarget(kind: .chapter, designation: "012").encoded()+ #expect(GroupOrdering.authoredContent(of: a) != GroupOrdering.authoredContent(of: b))+ }++ @Test("Raw-only links and later loser-addressed links survive a durable combination")+ func durableSources() throws {+ let fixture = try ChapterIdentityFixture()+ let loser = fixture.add(designation: "12", url: "https://example.com/a")+ let survivor = fixture.add(designation: "12", url: "https://example.com/b")+ loser.note = "Accepted note"+ try fixture.context.save()+ let group = try #require(LibraryRepository.entryGroup(id: loser.id, rows: [loser], canonicalWorkIDs: [:]))+ try EntrySources.combine(loser: group, survivorID: survivor.id, timestamp: loser.modifiedAt, context: fixture.context)+ try fixture.context.save()+ let fresh = ModelContext(fixture.container)+ let late = EntrySource(entryID: loser.id, urlString: "https://example.com/late", hostname: "example.com", timestamp: loser.modifiedAt)+ fresh.insert(late)+ try fresh.save()+ let index = try EntrySourceIndex(context: ModelContext(fixture.container))+ #expect(index.destination(of: loser.id) == survivor.id)+ #expect(index.urls(for: survivor.id) == ["https://example.com/a", "https://example.com/b", "https://example.com/late"])+ #expect(!index.hasUnresolvedContent(for: survivor.id))+ #expect(LibraryRepository.entryGroups(try fresh.fetch(FetchDescriptor<Entry>()), canonicalWorkIDs: [:]).count == 1)+ }++ @Test("Late loser note and rating edits stay visible and block automatic targeting")+ func lateContent() throws {+ let fixture = try ChapterIdentityFixture()+ let loser = fixture.add(designation: "12", url: "https://example.com/a")+ let survivor = fixture.add(designation: "12", url: "https://example.com/b")+ loser.note = "Accepted note"+ let group = try #require(LibraryRepository.entryGroup(id: loser.id, rows: [loser], canonicalWorkIDs: [:]))+ try EntrySources.combine(loser: group, survivorID: survivor.id, timestamp: loser.modifiedAt, context: fixture.context)+ loser.note = "Offline edit"+ loser.rating = .down+ try fixture.context.save()+ let index = try EntrySourceIndex(context: fixture.context)+ #expect(index.destination(of: loser.id) == survivor.id)+ #expect(index.destination(of: loser.id, requireResolvedContent: true) == nil)+ #expect(index.hasUnresolvedContent(for: survivor.id))+ #expect(LibraryRepository.entryGroups([loser, survivor], canonicalWorkIDs: [:]).count == 2)+ #expect(survivor.note.isEmpty)+ }++ @Test("Torn descendants retain link routing while blocking targeting")+ func tornDescendant() throws {+ let fixture = try ChapterIdentityFixture()+ let loser = fixture.add(designation: "12")+ let survivor = fixture.add(designation: "12", url: "https://example.com/b")+ let group = try #require(LibraryRepository.entryGroup(id: loser.id, rows: [loser], canonicalWorkIDs: [:]))+ try EntrySources.combine(loser: group, survivorID: survivor.id, timestamp: loser.modifiedAt, context: fixture.context)+ let offline = fixture.add(id: loser.id, designation: "12")+ offline.mergedIntoEntryID = survivor.id+ offline.mergeResolutionData = loser.mergeResolutionData+ offline.note = "Offline content"+ try fixture.context.save()+ let index = try EntrySourceIndex(context: fixture.context)+ #expect(index.groups[loser.id]?.isTorn == true)+ #expect(index.destination(of: loser.id) == survivor.id)+ #expect(index.hasUnresolvedContent(for: survivor.id))+ #expect(index.destination(of: loser.id, requireResolvedContent: true) == nil)+ }++ @Test("Missing baselines, dangling targets and redirect cycles remain review states")+ func unresolvedRedirects() throws {+ let fixture = try ChapterIdentityFixture()+ let a = fixture.add(designation: "12")+ let b = fixture.add(designation: "13")+ a.mergedIntoEntryID = b.id+ try fixture.context.save()+ let missing = try EntrySourceIndex(context: fixture.context)+ #expect(missing.hasUnresolvedContent(for: b.id))+ b.mergedIntoEntryID = a.id+ try fixture.context.save()+ let cycle = try EntrySourceIndex(context: fixture.context)+ #expect(cycle.destination(of: a.id) == nil)+ #expect(cycle.hasUnresolvedContent(for: a.id))+ b.mergedIntoEntryID = UUID()+ try fixture.context.save()+ #expect(try EntrySourceIndex(context: fixture.context).destination(of: b.id) == nil)+ }++ @Test("Unreadable authored targets and source evidence stay review states")+ func malformedEvidence() throws {+ let fixture = try ChapterIdentityFixture()+ let target = fixture.add(designation: "12")+ target.authoredTargetData = Data("future target".utf8)+ let source = EntrySource(entryID: target.id, urlString: "https://example.com/a", hostname: "example.com",+ timestamp: target.modifiedAt, evidenceData: Data("future source".utf8))+ fixture.context.insert(source)+ try fixture.context.save()+ #expect(try !EntrySources.converge(context: fixture.context))+ #expect(source.evidenceData == Data("future source".utf8))+ let index = try EntrySourceIndex(context: fixture.context)+ #expect(index.destination(of: target.id, requireResolvedContent: true) == nil)+ #expect(index.hasUnresolvedContent(for: target.id))+ #expect(target.authoredTarget == nil)+ #expect(target.effectiveChapterTitle == nil)+ }++ @Test("Same-UUID conflicting source owners block both chapter targets")+ func sourceOwnershipConflict() throws {+ let fixture = try ChapterIdentityFixture()+ let first = fixture.add(designation: "12")+ let second = fixture.add(designation: "13")+ let sourceID = UUID()+ for owner in [first.id, second.id] {+ fixture.context.insert(EntrySource(id: sourceID, entryID: owner, urlString: "https://example.com/a", hostname: "example.com", timestamp: first.modifiedAt))+ }+ try fixture.context.save()+ let index = try EntrySourceIndex(context: fixture.context)+ #expect(index.hasUnresolvedContent(for: first.id))+ #expect(index.hasUnresolvedContent(for: second.id))+ #expect(try !EntrySources.converge(context: fixture.context))+ }++ @Test("Source buckets preserve scalar-distinct URLs across generated arrival orderings")+ func sourceURLOrdering() throws {+ let urls = ["https://example.com/é", "https://example.com/e\u{301}", "https://example.com/a", "https://example.com/z"]+ var expected: [String]?+ for shift in 0..<urls.count {+ for reverse in [false, true] {+ let fixture = try ChapterIdentityFixture()+ let target = fixture.add(designation: "12", url: "")+ let rotated = Array(urls[shift...] + urls[..<shift])+ let order = reverse ? Array(rotated.reversed()) : rotated+ for url in order {+ // Preserve raw rows from sync, even if a newer writer has+ // produced a URL this reader cannot validate for writes.+ fixture.context.insert(EntrySource(entryID: target.id, urlString: url,+ hostname: "example.com", timestamp: target.modifiedAt))+ }+ try fixture.context.save()+ #expect(try !EntrySources.converge(context: fixture.context))+ let rows = try fixture.context.fetch(FetchDescriptor<EntrySource>())+ #expect(rows.count == 4)+ let index = try EntrySourceIndex(context: fixture.context)+ #expect(index.hasUnresolvedContent(for: target.id))+ let actual = index.urls(for: target.id)+ #expect(Set(actual.map(ExactScalarString.init)).count == 4)+ if let expected { #expect(actual.map(ExactScalarString.init) == expected.map(ExactScalarString.init)) }+ else { expected = actual }+ }+ }+ }++ @Test("Source evidence converges independently of arrival order and is idempotent")+ func sourceEvidenceConverges() throws {+ for reverse in [false, true] {+ let fixture = try ChapterIdentityFixture()+ let target = fixture.add(designation: "12")+ let key = EntrySourceEvidence.Binding(origin: .v2, key: "exact/key", ruleID: UUID())+ let facts = [EntrySourceEvidence(confirmed: [key]), EntrySourceEvidence(superseded: [key])]+ for fact in reverse ? facts.reversed().map({ $0 }) : facts {+ fixture.context.insert(EntrySource(entryID: target.id, urlString: "https://example.com/page", hostname: "example.com", timestamp: target.modifiedAt, evidenceData: try fact.encoded()))+ }+ try fixture.context.save()+ #expect(try EntrySources.converge(context: fixture.context))+ try fixture.context.save()+ #expect(try !EntrySources.converge(context: fixture.context))+ let rows = try fixture.context.fetch(FetchDescriptor<EntrySource>())+ #expect(Set(rows.compactMap(\.evidenceData)).count == 1)+ let evidence = try #require(rows.first?.evidenceData)+ #expect(try JSONBlob.decode(EntrySourceEvidence.self, from: evidence).active.isEmpty)+ }+ }++}++private struct ChapterIdentityFixture {+ let container: ModelContainer+ let context: ModelContext+ init() throws {+ let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ container = try ModelContainer(for: schema, configurations: [ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)])+ context = ModelContext(container)+ }+ @discardableResult func add(id: UUID = UUID(), designation: String?, url: String = "https://example.com/whole") -> Entry {+ let entry = Entry(id: id, captureTitle: "Book", captureTitleSource: .manual, rawURLString: url, hostname: url.isEmpty ? "" : "example.com", entryIdentityKey: url, timestamp: Date(timeIntervalSince1970: 1_800_000_000))+ entry.conservativeIdentityKey = url+ try! entry.authorTarget(AuthoredEntryTarget(kind: designation == nil ? .note : .chapter, designation: designation))+ context.insert(entry)+ return entry+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterMetadataMigrationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterMetadataMigrationTests.swiftnew file mode 100644index 00000000..2849a13b--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterMetadataMigrationTests.swift@@ -0,0 +1,125 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Chapter metadata migration", .serialized)+struct ChapterMetadataMigrationTests {+ @Test("Live schema contains additive optional chapter metadata and source entity")+ func additiveShape() throws {+ let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let entry = try #require(schema.entities.first { $0.name == "Entry" })+ for name in ["authoredTargetData", "mergedIntoEntryID", "mergeResolutionData"] {+ let attribute = try #require(entry.attributes.first { $0.name == name })+ #expect(attribute.isOptional)+ #expect(!attribute.isUnique)+ }+ let work = try #require(schema.entities.first { $0.name == "Work" })+ #expect(work.attributes.contains { $0.name == "chapterCaptureDefaultRaw" })+ let source = try #require(schema.entities.first { $0.name == "EntrySource" })+ #expect(source.relationships.isEmpty)+ #expect(source.attributes.allSatisfy { !$0.isUnique })+ }+ @Test("V20 changes only the approved additive metadata and retains supported migration stages")+ func frozenDelta() throws {+ let frozen = Schema(versionedSchema: AsterismSchemaV19.self)+ let live = Schema(versionedSchema: AsterismSchemaV20.self)+ #expect(Set(live.entities.map(\.name)).subtracting(frozen.entities.map(\.name)) == ["EntrySource"])+ for old in frozen.entities {+ let current = try #require(live.entities.first { $0.name == old.name })+ var properties = Set(current.properties.map(\.name))+ if old.name == "Entry" {+ properties.subtract(["authoredTargetData", "mergedIntoEntryID", "mergeResolutionData"])+ }+ if old.name == "Work" { properties.remove("chapterCaptureDefaultRaw") }+ #expect(properties == Set(old.properties.map(\.name)), "Unexpected delta in \(old.name)")+ for attribute in old.attributes {+ let new = try #require(current.attributes.first { $0.name == attribute.name })+ #expect(String(reflecting: new.valueType) == String(reflecting: attribute.valueType))+ #expect(new.isOptional == attribute.isOptional)+ #expect(new.options == attribute.options)+ }+ #expect(Set(current.relationships.map(\.name)) == Set(old.relationships.map(\.name)))+ for relationship in old.relationships {+ let new = try #require(current.relationships.first { $0.name == relationship.name })+ #expect(new.destination == relationship.destination)+ #expect(new.deleteRule == relationship.deleteRule)+ #expect(new.inverseName == relationship.inverseName)+ #expect(new.isOptional == relationship.isOptional)+ }+ }+ #expect(AsterismV20MigrationPlan.schemas.map { $0.versionIdentifier.major } == [16, 17, 18, 19, 20])+ #expect(AsterismV20MigrationPlan.stages.count == 4)+ }++ @Test("Recorded V19 store retains capture evidence and all authored values")+ func recordedStore() async throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "T2416Migration-\(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(), entryID = UUID()+ let instant = Date(timeIntervalSince1970: 1_800_000_000)+ try seed(url: configuration.storeURL, workID: workID, entryID: entryID, instant: instant)+ try Data("19\n".utf8).write(to: configuration.readinessMarkerURL)+ let (_, repository) = try await LibraryRepository.openForApp(configuration)+ let facts = try await repository.withLockedContext(mode: .shared, operation: "verify recorded chapter migration") { context in+ let entry = try #require(try context.fetch(FetchDescriptor<Entry>()).first)+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ #expect(entry.authoredTargetData == nil)+ #expect(entry.mergedIntoEntryID == nil)+ #expect(entry.mergeResolutionData == nil)+ #expect(work.chapterCaptureDefaultRaw == "ordinary")+ #expect(try context.fetchCount(FetchDescriptor<EntrySource>()) == 0)+ #expect(entry.id == entryID)+ #expect(work.id == workID)+ #expect(entry.captureTitle == "Chapter 12")+ #expect(entry.rawURLString == "https://example.com/ch12")+ #expect(entry.note == "Original note")+ #expect(entry.ratingRaw == "up")+ #expect(entry.firstCapturedAt == instant)+ #expect(entry.modifiedAt == instant)+ #expect(entry.work?.id == workID)+ #expect(entry.citationValues == EntryCitations())+ #expect(work.readingStatusRaw == "catchingUp")+ #expect(work.publicationStateData == (try WorkPublicationState(status: .ongoing).canonicalData()))+ return entry.id+ }+ #expect(facts == entryID)+ await repository.shutdown()+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "20\n")+ }++ private func seed(url: URL, workID: UUID, entryID: UUID, instant: Date) throws {+ let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let container = try ModelContainer(for: schema, configurations: [ModelConfiguration("AsterismV3", schema: schema, url: url, cloudKitDatabase: .none)])+ let context = ModelContext(container)+ let work = AsterismSchemaV19.Work()+ work.displayTitle = "Recorded work"+ work.createdAt = instant+ work.modifiedAt = instant+ work.id = workID+ work.readingStatusRaw = "catchingUp"+ work.publicationStateData = try WorkPublicationState(status: .ongoing).canonicalData()+ let entry = AsterismSchemaV19.Entry()+ entry.id = entryID+ entry.captureTitle = "Chapter 12"+ entry.captureTitleSourceRaw = "host"+ entry.rawURLString = "https://example.com/ch12"+ entry.hostname = "example.com"+ entry.entryIdentityKey = entry.rawURLString+ entry.conservativeIdentityKey = entry.rawURLString+ entry.citationsData = try JSONEncoder().encode(EntryCitations())+ entry.firstCapturedAt = instant+ entry.lastSharedAt = instant+ entry.modifiedAt = instant+ entry.note = "Original note"+ entry.ratingRaw = "up"+ entry.work = work+ context.insert(work)+ context.insert(entry)+ try context.save()+ withExtendedLifetime(container) {}+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterExtractionRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterExtractionRepositoryTests.swiftindex e0c98229..038a93ab 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterExtractionRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterExtractionRepositoryTests.swift@@ -48,6 +48,22 @@ struct ExtractionCandidateReadTests { return fixture } + @Test("Combined extraction sources disappear from sweeps and pending acceptances are stale")+ func combinedSource() async throws {+ let fixture = try await fixture()+ let pending = DecisionRequest(workID: workA, kind: .character, action: .accept,+ displayedKeys: ["hanna"], displayedTargetID: nil, proposedName: "Hanna",+ facts: [fact("Leads", "Hanna led the squad", .entry(entry1))],+ completedSources: [.init(ref: .entry(entry1), fingerprint: CharacterCoverageFingerprint.of("Hanna led the squad"))])+ let review = try await fixture.repository.projectEntryCorrection(entryID: entry1, destinationID: entry2)+ #expect(try await fixture.repository.commitEntryCorrection(review, target: .init(kind: .chapter), contentChoice: .source) == .committed(entryID: entry2))+ let sources = try await fixture.repository.extractionCandidates(limit: 100).first(where: { $0.workID == workA })?.sources+ #expect(sources?.contains(where: { $0.ref == .entry(entry1) }) == false)+ #expect(sources?.contains(where: { $0.ref == .entry(entry2) }) == true)+ #expect(try await fixture.repository.commitDecision(pending) == .refused(.staleSource(.entry(entry1))))+ #expect(try await fixture.repository.advanceCoverage(workID: workA, sources: pending.completedSources) == 0)+ }+ @Test("Every source of a work comes back with its fingerprint and its coverage") func sourcesCarryFingerprintsAndCoverage() async throws { let fixture = try await fixture()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swiftindex e47a00d7..d7e96cb2 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CitationSurgery.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CitationSurgery.swiftindex 4574ede4..37dda16e 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CitationSurgery.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CitationSurgery.swift@@ -20,7 +20,7 @@ extension EntryCitations.Identity { guard let url = urlRule, nameTitleRule != nil else { return self } let replaced = CitedRule(id: id) switch self {- case .rawURL: return self+ case .rawURL, .authoredEntryID: return self case .rule: return .rule(url: url, nameTitle: replaced) case .composed: return .composed(url: url, nameTitle: replaced) }@@ -30,7 +30,7 @@ extension EntryCitations.Identity { var citingNoNameTitle: Self { guard let url = urlRule else { return self } switch self {- case .rawURL: return self+ case .rawURL, .authoredEntryID: return self case .rule: return .rule(url: url, nameTitle: nil) case .composed: return .composed(url: url, nameTitle: nil) }@@ -41,7 +41,7 @@ extension EntryCitations.Identity { guard urlRule != nil else { return self } let replaced = CitedRule(id: id) switch self {- case .rawURL: return self+ case .rawURL, .authoredEntryID: return self case .rule: return .rule(url: replaced, nameTitle: nameTitleRule) case .composed: return .composed(url: replaced, nameTitle: nameTitleRule) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ComposedCaptureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ComposedCaptureTests.swiftindex b7ae67b3..5dcb20c7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ComposedCaptureTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ComposedCaptureTests.swift@@ -170,7 +170,7 @@ struct ComposedCaptureTests { let context = fixture.freshContext() let entry = try #require(try context.fetch(FetchDescriptor<Entry>()).first { $0.id == snapshot.id })- #expect(entry.citationValues.identity.keyVersion == 1) // conservative+ #expect(entry.citationValues.identity.keyVersion == 1) #expect(entry.entryIdentityKey == entry.rawURLString) #expect(entry.chapterSequence == nil) #expect(entry.chapterTitle == "Chapter 3") // settled by the title
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swiftindex 9ff63689..c64b5877 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift@@ -367,12 +367,12 @@ private final class RuleGroupStore { let directory = FileManager.default.temporaryDirectory .appending(path: "AsterismConvergedRules-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) let container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) self.init(context: ModelContext(container)) retained = container
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swiftindex d6d0f643..b60ef19a 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swiftindex 0e823fe6..e8797df1 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swiftindex bd2e5ff3..ab922fcd 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swiftindex 8a0acb70..f0fd5ced 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) seed = ModelContext(container) if let saveStrategy {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swiftindex 0ade8e33..1983489b 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swiftindex bae82bac..42383158 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift@@ -23,7 +23,7 @@ struct EmptyLibraryTests { try await fixture.seedGoldenLibrary() let before = try await fixture.repository.emptyLibraryRowCounts()- #expect(before.count == 18, "the phase list must name every entity")+ #expect(before.count == 19, "the phase list must name every entity") #expect( before.values.allSatisfy { $0 > 0 }, "the seed leaves \(before.filter { $0.value == 0 }.keys.sorted()) empty")@@ -812,6 +812,7 @@ private final class EmptyLibraryFixture { from: try BackupV18Codec.encode( payload: BackupGoldenLibrary.payload, metadata: BackupGoldenLibrary.metadata)))+ try await repository.seedGoldenEntrySource() } /// One waiting capture, one set aside, one refusal receipt, a drain report@@ -886,6 +887,14 @@ extension LibraryRepository { /// `AsterismSchemaV17.models`, so counting through it is counting the /// schema's entities — and the alternative, a second hand-written list of /// seventeen fetches, is one more thing to forget at the next bump.+ fileprivate func seedGoldenEntrySource() async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding new source entity") { context in+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first)+ context.insert(EntrySource(entryID: entry.id, urlString: entry.rawURLString,+ hostname: entry.hostname, timestamp: entry.firstCapturedAt))+ try context.save()+ }+ } fileprivate func emptyLibraryRowCounts() async throws -> [String: Int] { try await withLockedContext(mode: .shared, operation: "counting every entity") { context in var counts: [String: Int] = [:]
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swiftindex 726aad82..dd38bfb0 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 = "19\n"+ private static let markerContents = "20\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", "AsterismSchemaV19",- "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "AsterismV19MigrationPlan",+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20",+ "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "AsterismV19MigrationPlan", "AsterismV20MigrationPlan", "atOrAboveV5", "belowV5", "firstV5Major", ] /// The archive format — 15/16, the one shape the app reads and writes,@@ -325,6 +325,10 @@ struct FrozenLibraryPathTests { /// single format, and a digit in their names would be a digit describing /// nothing. let namesTheArchiveFormat: Set<String> = [+ // 19/20 is the additive authored-target/source wire generation.+ "BackupV19Codec", "BackupV19Document", "BackupV19Entry", "BackupV19EntrySource",+ "BackupV19Exporter", "BackupV19Metadata", "BackupV19Payload", "BackupV19ReferenceValidator",+ "BackupV19SnapshotProviding", "BackupV19Work", "backupV19Snapshot", "BackupV18Entry", "BackupV18Site", "BackupV18TitlePattern", "BackupV18URLRule", "BackupV18Work", "BackupV18WorkType", "BackupV18Membership", "BackupV18DistinctPair", "BackupV18Character", "BackupV18Codec", "BackupV18Series", "BackupV18Link",@@ -347,7 +351,7 @@ struct FrozenLibraryPathTests { /// Entry, and the validator has to say which one it is checking. let namesAnIdentityKeyGeneration: Set<String> = [ "EntryIdentityKeyV2Codec", "EntryIdentityKeyV3Codec",- "validateV2", "validateV3", "v3IdentityReason",+ "validateV2", "validateV3", "v3IdentityReason", "v2", ] let justified = declaresAStoreSchemaOrMarkerGeneration@@ -390,13 +394,13 @@ struct FrozenLibraryPathTests { } #expect( declared.sorted() == [- "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19",+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", ], "the package declares versioned schemas \(declared); Req 3.3 allows only ones a plan references") - let referenced = AsterismV19MigrationPlan.schemas.map { String(describing: $0) }+ let referenced = AsterismV20MigrationPlan.schemas.map { String(describing: $0) } #expect(- referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19"],+ referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20"], "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 +412,13 @@ struct FrozenLibraryPathTests { // superseded them (Q15 of `work-creators`, Q65 of `place-extraction`, // `work-thumbnails`, `update-schedule`, and this bump). #expect(- AsterismV19MigrationPlan.stages.count == 3,+ AsterismV20MigrationPlan.stages.count == 4, "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(- AsterismSchemaV19.versionIdentifier == Schema.Version(19, 0, 0),+ AsterismSchemaV20.versionIdentifier == Schema.Version(20, 0, 0), "the live schema's version stamp is what every recorded store is compared against") }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swiftindex 4d73575b..341412c2 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift@@ -294,12 +294,12 @@ private final class GroupStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismGroupFetch-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swiftindex c8c4cca1..2dafe451 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift@@ -938,12 +938,12 @@ private final class OrderingStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismGroupOrdering-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swiftindex c58bd7c7..3d0e4a3b 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swiftindex 5a6cf22f..e70a4d2c 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swiftindex 6c2188df..ab1c9874 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swiftindex b423cd7a..764cf92a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift@@ -11,6 +11,37 @@ import Testing @Suite("Lookup-first capture state model", .serialized) struct LookupFirstCaptureStateTests { + @Test("Re-share chapter selection preserves edited content and commits explicit corrected intent after review")+ @MainActor func chapterControlParity() async throws {+ let fixture = LookupCaptureFixture.editExisting(), second = UUID(), work = UUID()+ guard case .edit(let basis) = fixture.coordinator.lookupResult else { Issue.record("Expected edit fixture"); return }+ let projection = ChapterCaptureResolver.project(workID: work, rawURL: "https://example.com/chapter-1", evidence: [], entries: [+ .init(id: fixture.entryID, workID: work, target: .init(kind: .chapter, designation: "1"), sourceURLs: ["https://example.com/chapter-1"], note: "existing note", rating: .up),+ .init(id: second, workID: work, target: .init(kind: .chapter, designation: "2"), sourceURLs: ["https://example.com/chapter-1"], note: "Second", rating: .down)+ ], captureDefault: .ordinary)+ fixture.coordinator.lookupResult = .edit(basis.with(chapterProjection: projection))+ fixture.coordinator.chapterOutcome = .reviewRequired(projection, reason: "Review the refreshed chapter")+ await fixture.viewModel.loadWithLookup(payload: fixture.payload, coordinator: fixture.coordinator)+ #expect(!fixture.viewModel.canSaveUpdate)+ fixture.viewModel.chooseChapterIntent(.existing(second))+ guard case .readyEdit(let selected) = fixture.viewModel.lookupState else { Issue.record("Expected edit"); return }+ #expect(selected.draftNote == "Second" && selected.draftRating == .down)+ fixture.viewModel.setDraftNote("Draft"); fixture.viewModel.setDraftRating(.up)+ fixture.viewModel.chooseChapterIntent(.existing(fixture.entryID))+ #expect(!fixture.viewModel.canSaveUpdate)+ fixture.viewModel.chooseChapterIntent(.correctedExisting(fixture.entryID, contentChoice: .source))+ await fixture.viewModel.submitUpdate(coordinator: fixture.coordinator)+ guard case .readyEdit(let refused) = fixture.viewModel.lookupState else { Issue.record("Expected retained draft"); return }+ #expect(refused.draftNote == "Draft" && refused.draftRating == .up && refused.errorMessage != nil)+ #expect(fixture.coordinator.chapterDrafts.first?.intent == .correctedExisting(fixture.entryID, contentChoice: .source))+ #expect(fixture.coordinator.commitReShareCallCount == 0 && fixture.coordinator.titleFetchCallCount == 0)+ fixture.coordinator.chapterOutcome = .committed(SnapshotTestFixtures.makeEntry(id: fixture.entryID))+ await fixture.viewModel.submitUpdate(coordinator: fixture.coordinator)+ #expect(fixture.coordinator.chapterDrafts.count == 2)+ if case .saved(let id) = fixture.viewModel.lookupState { #expect(id == fixture.entryID) }+ else { Issue.record("Reviewed correction must save") }+ }+ // MARK: - Lookup before title acquisition @Test("Lookup runs before title acquisition — no network fetch for edit")@@ -357,7 +388,7 @@ private struct LookupCaptureFixture { _ seed: (ModelContext, String) -> Void ) throws -> LookupCaptureFixture { let url = "https://example.com/chapter-1"- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let container = try ModelContainer( for: schema, configurations: [@@ -401,6 +432,14 @@ private final class FakeLookupCoordinator: LookupCaptureCoordinating, @unchecked var lookupResult: CaptureLookupDisposition = .new(NewLookupBasis(hostname: "example.com", identityKey: "key")) var reShareOutcome: ReShareUpdateOutcome = .committed var reShareShouldThrow = false+ var chapterOutcome: ChapterCaptureCommitOutcome?+ var chapterDrafts: [ChapterCaptureDraft] = []++ func commitChapterCapture(_ draft: ChapterCaptureDraft) async throws -> ChapterCaptureCommitOutcome {+ chapterDrafts.append(draft)+ guard let chapterOutcome else { throw LibraryRepositoryError.invalidInput(operation: "test", reason: "Chapter outcome not configured") }+ return chapterOutcome+ } private var _captureLookupCallCount = 0 var captureLookupCallCount: Int { lock.withLock { _captureLookupCallCount } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ManualEntryRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ManualEntryRepositoryTests.swiftnew file mode 100644index 00000000..8e622f96--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ManualEntryRepositoryTests.swift@@ -0,0 +1,129 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Manual notes and URL-free works", .serialized)+struct ManualEntryRepositoryTests {+ @Test("Work metadata explicitly overrides and resets a learned chapter default without changing entries")+ func workDefaultRoundTrip() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ let page = "https://example.com/whole"+ for designation in ["12", "13"] {+ let projection = try await fixture.repository.projectChapterCapture(rawURL: page, captureTitle: "Book", workID: work.id)+ guard case .committed = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: .init(captureTitle: "Book", captureTitleSource: .manual, rawURLString: page, note: designation),+ intent: .newChapter(.init(kind: .chapter, designation: designation), confirmedNew: true))) else {+ Issue.record("Chapter must save"); return+ }+ }+ let learned = try await fixture.repository.work(id: work.id)+ #expect(learned.chapterCaptureDefault == .multipleChaptersPerPage)+ for mode in [ChapterCaptureDefault.ordinary, .multipleChaptersPerPage, .ordinary] {+ let before = try await fixture.repository.work(id: work.id)+ let draft = WorkMetadataDraft(displayTitle: before.displayTitle, typeAssignment: before.typeDisplay.assignment,+ genreTags: before.genreTags, genericNotes: before.genericNotes, publicationEdit: .unchanged,+ readingStatus: before.readingStatus, verdict: before.verdict, releaseDays: before.releaseDays,+ membership: before.membership, thumbnail: .keep, chapterCaptureDefault: mode)+ #expect(try await fixture.repository.updateWork(id: work.id, basis: WorkEditBasis(work: before), draft: draft, calendar: .current) == .committed)+ let after = try await fixture.repository.work(id: work.id)+ #expect(after.chapterCaptureDefault == mode && after.entries.map(\.id) == learned.entries.map(\.id))+ let projected = try await fixture.repository.projectChapterCapture(rawURL: "https://example.com/new", captureTitle: "Book", workID: work.id)+ #expect(projected.resolution == (mode == .ordinary ? .newEntry : .newChapter(requiresConfirmation: true)))+ }+ }+ @Test("A site-free work can later add an optional purchase URL through the Work URL save")+ func laterPurchaseURL() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: ""))+ let before = try await fixture.repository.work(id: work.id)+ let contract = try await fixture.repository.projectWorkURL(workID: work.id, hostname: "", request: .replaceManual("https://www.amazon.com/dp/book"))+ #expect(try await fixture.repository.work(id: work.id) == before)+ #expect(try await fixture.repository.sites().isEmpty)+ #expect(contract.basis.membershipID == nil)+ #expect(try await fixture.repository.commitWorkURL(contract) == .committed(workID: work.id))+ let linked = try await fixture.repository.work(id: work.id)+ #expect(linked.memberships.count == 1 && linked.memberships.first?.hostname == "www.amazon.com")+ #expect(linked.memberships.first?.workURLString == "https://www.amazon.com/dp/book")+ #expect(linked.entries.isEmpty)+ }++ @Test("Every work can be created without a site, URL or fabricated membership")+ func siteFreeWork() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Published book", hostname: ""))+ #expect(work.memberships.isEmpty)+ #expect(try await fixture.repository.sites().isEmpty)+ }+ @Test("Independent untitled notes and rating-only reactions retain distinct identities")+ func independentNotes() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ var ids: Set<UUID> = []+ for draft in [ManualEntryDraft(note: "First"), .init(note: "Second"), .init(rating: .up)] {+ let projection = try await fixture.repository.projectManualEntry(workID: work.id)+ if case .committed(let entry) = try await fixture.repository.commitManualEntry(projection: projection, draft: draft) {+ ids.insert(entry.id)+ #expect(entry.rawURLString.isEmpty && entry.hostname.isEmpty)+ #expect(entry.authoredTarget?.kind == .note && entry.authoredTarget?.title == nil)+ } else { Issue.record("A valid manual reaction must save") }+ }+ #expect(ids.count == 3)+ #expect(try await fixture.repository.projectManualEntry(workID: work.id).entries.count == 3)+ }+ @Test("Blank reactions and malformed optional sources refuse without writing")+ func invalidDrafts() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ let projection = try await fixture.repository.projectManualEntry(workID: work.id)+ for draft in [ManualEntryDraft(), .init(sourceURL: "file:///book", note: "Keep draft")] {+ await #expect(throws: (any Error).self) {+ try await fixture.repository.commitManualEntry(projection: projection, draft: draft)+ }+ }+ #expect(try await fixture.repository.projectManualEntry(workID: work.id).entries.isEmpty)+ }+ @Test("Manual chapter selection updates the chosen chapter without title guessing")+ func chosenChapter() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: "example.com"))+ var projection = try await fixture.repository.projectManualEntry(workID: work.id)+ let first = try await fixture.repository.commitManualEntry(projection: projection,+ draft: .init(target: .init(kind: .chapter, designation: "12"), note: "First"))+ guard case .committed(let entry) = first else { Issue.record("First chapter must save"); return }+ projection = try await fixture.repository.projectManualEntry(workID: work.id)+ if case .committed(let updated) = try await fixture.repository.commitManualEntry(projection: projection,+ draft: .init(target: .init(kind: .chapter), note: "Updated", rating: .down, existingEntryID: entry.id)) {+ #expect(updated.id == entry.id && updated.authoredTarget?.designation == "12")+ #expect(updated.note == "Updated" && updated.rating == .down)+ } else { Issue.record("Explicit existing chapter choice must update") }+ #expect(try await fixture.repository.projectManualEntry(workID: work.id).entries.count == 1)+ }+ @Test("URL-free Markdown headings are readable and contain no empty link")+ func unlinkedMarkdown() {+ let text = MarkdownExport.renderEntry(.init(headingText: "", rawURLString: "", dateText: "10 October", rating: .up))+ #expect(text.contains("## Note\n"))+ #expect(!text.contains("]()"))+ }+ @Test("A numeric generic-note title stays out of chapter progress while retaining source links")+ func genericNoteConsumers() async throws {+ let fixture = try await M5Fixture()+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: ""))+ let projection = try await fixture.repository.projectManualEntry(workID: work.id)+ let result = try await fixture.repository.commitManualEntry(projection: projection,+ draft: .init(target: .init(kind: .note, title: "12"), sourceURL: "https://example.com/book", rating: .up))+ guard case .committed(let saved) = result else { Issue.record("Reaction must save"); return }+ let reopened = try await fixture.repository.entry(id: saved.id)+ #expect(reopened.authoredNoteTitle == "12")+ #expect(try await fixture.repository.entryExportInput(entryID: saved.id, locale: Locale(identifier: "en_US")).headingText == "12")+ #expect(reopened.chapterTitle == nil && reopened.chapterSequence == nil)+ #expect(NumberedNote.from([reopened]).isEmpty)+ #expect(reopened.sourceURLs == ["https://example.com/book"])+ #expect(reopened.primarySourceURL?.absoluteString == "https://example.com/book")+ #expect(try await fixture.repository.work(id: work.id).memberships.isEmpty)+ let today = try await fixture.repository.todayPresentation(calendar: Calendar(identifier: .gregorian))+ #expect(today.actionableCount == 0)+ #expect(today.allRows.first(where: { $0.id == saved.id })?.attention == nil)+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swiftindex a264053a..1e7f0b26 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) == "19",+ #expect(try markerContent(cfg) == "20", "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) == "19", "and the open leaves the marker as it found it")+ #expect(try markerContent(cfg) == "20", "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) == "19",+ #expect(try markerContent(cfg) == "20", "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) == "19")+ #expect(try markerContent(cfg) == "20") 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, "19\n")+ try writeMarker(cfg, "20\n") _ = try await LibraryRepository.openForExtension(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["19.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["20.0.0"], "the same store converts once the marker check passes") }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swiftindex e8938b08..976f4056 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("19\n")+ try root.writeMarker("20\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() == "19")+ #expect(try root.markerText() == "20") #expect(try V4RecordedStoreFixture.recordedModelVersions(at: root.configuration.storeURL)- == ["19.0.0"], "the store the arm opened is recorded at the version it converted to")+ == ["20.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() == "19")+ #expect(try root.markerText() == "20") 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() == "19")+ #expect(try root.markerText() == "20") withExtendedLifetime(root) {} } @@ -217,7 +217,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("a diagnosable library must still open, got \(result)") return }- #expect(try root.markerText() == "19")+ #expect(try root.markerText() == "20") #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() == "19")+ #expect(try root.markerText() == "20") let (result, _) = try await LibraryRepository.openForExtension(root.configuration) guard case .ready = result else {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swiftindex d5beb87d..ba131288 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swiftindex 06178919..adb3e363 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swiftindex e081d901..61b385a9 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 == "19")+ #expect(call.markerVersion == "20") #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 == "19")+ #expect(log.calls.first?.markerVersion == "20") #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 == "19")+ #expect(log.calls.first?.markerVersion == "20") #expect(await repository.mirroring.isMirroring) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swiftindex 38e31221..b8a5aa6e 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(AsterismSchemaV19.models.map { String(describing: $0) })+ let declared = Set(AsterismSchemaV20.models.map { String(describing: $0) }) #expect( phased == declared, """@@ -320,7 +320,7 @@ struct ModelContractTests { work.releaseDays = [.sunday, .monday, .sunday] #expect(work.releaseDaysRaw == ["monday", "sunday"], "the setter writes canonical order") - let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let entity = try #require(schema.entities.first { $0.name == "Work" }) #expect(entity.uniquenessConstraints.isEmpty, "Work declares a uniqueness constraint") let attributes = entity.properties.compactMap { $0 as? Schema.Attribute }@@ -374,7 +374,7 @@ struct ModelContractTests { #expect(work.thumbnailShape == nil) #expect(work.thumbnailIdentity == nil) - let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let entity = try #require(schema.entities.first { $0.name == "Work" }) #expect(entity.uniquenessConstraints.isEmpty, "Work declares a uniqueness constraint") // `properties` is `[any SchemaProperty]` and the relationships are in@@ -466,7 +466,7 @@ struct ModelContractTests { // The schema's own view: nothing unique, no relationship on either new // table, and the owner a column rather than a reference.- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) for name in ["Place", "PlaceSuppression"] { guard let entity = schema.entities.first(where: { $0.name == name }) else { Issue.record("the live schema has no \(name) entity")@@ -543,7 +543,7 @@ struct ModelContractTests { // The schema's own view: nothing unique, no relationships on any of the // three, and every foreign reference a column rather than a reference.- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) for name in ["Creator", "CreatorRole", "WorkCredit"] { guard let entity = schema.entities.first(where: { $0.name == name }) else { Issue.record("the live schema has no \(name) entity")@@ -584,7 +584,7 @@ struct ModelContractTests { // The schema's own view: nothing unique, no relationships on either new // table, and the two link ends are UUID columns rather than references.- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) for name in ["Series", "WorkLink"] { guard let entity = schema.entities.first(where: { $0.name == name }) else { Issue.record("the live schema has no \(name) entity")@@ -717,7 +717,7 @@ struct ModelContractTests { /// V8-era half of this pin needed an allowlist and this one does not. @Test("No dropped column is in the live schema") func droppedColumnsAreGoneFromTheSchema() {- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) var propertiesByEntity: [String: Set<String>] = [:] for entity in schema.entities { propertiesByEntity[entity.name, default: []]@@ -798,7 +798,7 @@ struct ModelContractTests { #expect( declaringSnapshots.sorted() == [ "AsterismSchemaV16.swift", "AsterismSchemaV17.swift",- "AsterismSchemaV18.swift", "AsterismSchemaV19.swift",+ "AsterismSchemaV18.swift", "AsterismSchemaV19.swift", "AsterismSchemaV20.swift", ], """ the package declares versioned schemas in \(declaringSnapshots.sorted()); \@@ -1115,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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swiftindex 4846f1d7..bb90ae1d 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", "AsterismSchemaV18Models.swift",+ "AsterismSchemaV16.swift", "AsterismSchemaV17Models.swift", "AsterismSchemaV18Models.swift", "AsterismSchemaV19Models.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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swiftindex 9e5ffd09..37c306b1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift@@ -27,7 +27,7 @@ struct NoEpisodeStorageTests { func indexAndRestart() throws { let url = FileManager.default.temporaryDirectory.appending(path: "NoEpisodeStorage-\(UUID())") defer { try? FileManager.default.removeItem(at: url) }- let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let container = try ModelContainer( for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)]) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryBootstrapTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryBootstrapTests.swiftindex 3cd22026..39699d18 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryBootstrapTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryBootstrapTests.swift@@ -177,10 +177,29 @@ private final class HelperProcess: @unchecked Sendable { } private func helperExecutableURL() throws -> URL {+ // SwiftPM's newer native-host runner lives outside its private product+ // directory. Allow the invoking test environment to name that built helper.+ if let path = ProcessInfo.processInfo.environment["ASTERISM_STORE_TEST_HELPER_PATH"] {+ guard FileManager.default.isExecutableFile(atPath: path) else {+ throw CocoaError(.fileNoSuchFile, userInfo: [NSFilePathErrorKey: path])+ }+ return URL(filePath: path)+ } let packageRoot = URL(filePath: #filePath) .deletingLastPathComponent() .deletingLastPathComponent() .deletingLastPathComponent()+ // A private --scratch-path must locate the helper beside the running+ // test product, instead of borrowing the checkout's shared .build output.+ let products = [URL(filePath: CommandLine.arguments[0]), Bundle.main.bundleURL] + Bundle.allBundles.map(\.bundleURL)+ for product in products {+ var directory = product.deletingLastPathComponent()+ for _ in 0..<6 {+ let candidate = directory.appending(path: "AsterismStoreTestHelper")+ if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate }+ directory.deleteLastPathComponent()+ }+ } let url = packageRoot.appending(path: ".build/debug/AsterismStoreTestHelper") guard FileManager.default.isExecutableFile(atPath: url.path) else { throw CocoaError(.fileNoSuchFile, userInfo: [NSFilePathErrorKey: url.path])
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swiftindex 8af5d185..1ce47dc7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift@@ -339,10 +339,12 @@ struct RepositoryCaptureTests { try await fixture.teachWorkIdentity() // Two entries on one identity key and two application UUIDs: the set the // lookup cannot offer for editing.- _ = try await fixture.captureThroughRules(- title: "A Serial", rawURL: "https://example.com/read?id=42&chapter=2")- _ = try await fixture.captureThroughRules(+ let duplicateSource = try await fixture.captureThroughRules( title: "A Serial", rawURL: "https://example.com/read?id=42&chapter=2")+ // A modern same-page share updates its known chapter. Seed the genuine+ // pre-existing duplicate set this race test is about, instead of asking+ // capture to manufacture one.+ try await seedCaptureDuplicate(configuration: fixture.configuration, entryID: duplicateSource.id) let work = try #require(try await fixture.repository.works().works.first) try await fixture.setReadingStatus(.toRead, of: work) @@ -486,6 +488,25 @@ private final class CaptureTemporaryDirectory { deinit { try? FileManager.default.removeItem(at: url) } } +private func seedCaptureDuplicate(configuration: LibraryConfiguration, entryID: UUID) async throws {+ let lease = try await CrossProcessLibraryLock.acquire(mode: .exclusive, at: configuration.lockURL, timeout: .seconds(1))+ _ = lease+ let container = try makeStoreContainer(configuration)+ let context = ModelContext(container)+ let source = try #require(context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { $0.id == entryID })).first)+ let copy = Entry(captureTitle: source.captureTitle, captureTitleSource: source.captureTitleSource,+ rawURLString: source.rawURLString, canonicalURLString: source.canonicalURLString,+ hostname: source.hostname, entryIdentityKey: source.entryIdentityKey,+ timestamp: source.modifiedAt, note: source.note, rating: source.rating, work: source.work)+ copy.site = source.site+ copy.conservativeIdentityKey = source.conservativeIdentityKey+ copy.identityBasisRaw = source.identityBasisRaw+ copy.chapterTitle = source.chapterTitle; copy.chapterSequence = source.chapterSequence+ copy.citationsData = source.citationsData+ context.insert(copy)+ try context.save()+}+ private func seedWorkAssignment( configuration: LibraryConfiguration, entryID: UUID,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swiftindex 5708c604..1e39f5a6 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryWorksTests.swift@@ -72,7 +72,6 @@ struct RepositoryWorksTests { let fixture = try await WorksRepositoryFixture() for draft in [ NewWorkDraft(displayTitle: " ", hostname: "example.com"),- NewWorkDraft(displayTitle: "Work", hostname: " "), NewWorkDraft(displayTitle: "Work", hostname: "ftp://example.com/x"), NewWorkDraft(displayTitle: "Work", hostname: "example..com"), NewWorkDraft(displayTitle: "Work", hostname: "https://-foo-.com/x"),@@ -80,6 +79,11 @@ struct RepositoryWorksTests { await #expect(throws: LibraryRepositoryError.self) { try await fixture.repository.createWork(draft) } } #expect(try await fixture.repository.debugCounts() == .seededEmpty)+ let unlinked = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Work without a source", hostname: " "))+ #expect(unlinked.memberships.isEmpty)+ #expect(try await fixture.repository.sites().isEmpty)+ #expect(try await fixture.repository.debugCounts().works == 1) } @Test("Works snapshot orders non-empty, empty, and unattached groups deterministically")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swiftindex 96b47b8c..835d3de3 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) return try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swiftindex a8de4cb9..3cfbf4a2 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) self.saveStrategy = saveStrategy ?? saveRecorder
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swiftindex dd37f099..737ba411 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swiftindex c00fdf1b..e47f0168 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) == ["19.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["20.0.0"], "the conversion is committed in the log, so a reader of the log sees it") #expect(StoreMetadata.recordedVersion(at: dir.storeURL) == .atOrAboveV5, "a reader that ignored the log would still have to answer, not refuse")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swiftindex 2dce2594..2dfdbec5 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift@@ -79,7 +79,7 @@ struct ThumbnailBytesReachTests { "Models.swift", "AsterismSchemaV16.swift", "AsterismSchemaV17Models.swift",- "AsterismSchemaV18Models.swift",+ "AsterismSchemaV18Models.swift", "AsterismSchemaV19Models.swift", "GroupOrdering.swift", "Thumbnails/ThumbnailStoreProbe.swift", "LibraryRepository+Thumbnails.swift",
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swiftindex d1d25e41..e2b69969 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: AsterismSchemaV19.self).entities.map(\.name))+ let live = Set(Schema(versionedSchema: AsterismSchemaV20.self).entities.map(\.name)) let frozen = Set(Schema(versionedSchema: AsterismSchemaV16.self).entities.map(\.name)) #expect(live.isDisjoint(with: probeNames)) #expect(frozen.isDisjoint(with: probeNames))
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swiftindex 44d82258..4ebbd8b3 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) container = try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swiftindex acd659d9..8b5007c3 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift@@ -945,7 +945,7 @@ struct URLOptionalSequenceArchiveTests { #expect(decoded.payload == payload) #expect(try Self.combinedRule(of: decoded.payload)?.sequencePresence == .optional) - let schema = Schema(versionedSchema: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swiftindex 6136c794..0b7dbf84 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() == ["19.0.0"])- #expect(try root.markerText() == "19")+ #expect(try root.recordedVersions() == ["20.0.0"])+ #expect(try root.markerText() == "20") #expect(counts.works == 1) #expect(counts.entries == 3) #expect(counts.sites == 1)@@ -393,8 +393,8 @@ struct V16RecordedStoreTests { #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready) let (_, second) = try await LibraryRepository.openForApp(root.configuration) await second.shutdown()- #expect(try root.markerText() == "19")- #expect(try root.recordedVersions() == ["19.0.0"])+ #expect(try root.markerText() == "20")+ #expect(try root.recordedVersions() == ["20.0.0"]) withExtendedLifetime(root) {} } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swiftindex e0ba90b4..28c1dee7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift@@ -40,9 +40,9 @@ struct V17RecordedStoreTests { #expect(facts.2 == 0) #expect(facts.3) #expect(try String(contentsOf: configuration.readinessMarkerURL,- encoding: .utf8) == "19\n")+ encoding: .utf8) == "20\n") #expect(try V4RecordedStoreFixture.recordedModelVersions(- at: configuration.storeURL) == ["19.0.0"])+ at: configuration.storeURL) == ["20.0.0"]) await repository.shutdown() }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swiftindex 8aca1e74..0b3f1c29 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift@@ -44,14 +44,14 @@ struct V18RecordedStoreTests { #expect(facts.4 == confirmation) #expect(facts.5 == thumbnail) #expect(facts.6 == [payload])- #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "19\n")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["19.0.0"])+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "20\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["20.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"])+ arguments: ["16", "17", "18", "19", "20"]) func markerContracts(marker: String) async throws { let root = FileManager.default.temporaryDirectory.appending(path: "Marker19-\(UUID())") defer { try? FileManager.default.removeItem(at: root) }@@ -60,14 +60,14 @@ struct V18RecordedStoreTests { await initial.shutdown() try Data("\(marker)\n".utf8).write(to: configuration.readinessMarkerURL) #expect(try LibraryRepository.classify(configuration, fileManager: .default)- == (marker == "19" ? .ready : .markerLagging(generation: marker)))- if marker != "19" {+ == (marker == "20" ? .ready : .markerLagging(generation: marker)))+ if marker != "20" { 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")+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "20\n") } private func seed(at url: URL, workID: UUID, confirmation: Data, thumbnail: Data,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swiftindex ebb6995a..0f87ef65 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swiftindex 206c5da7..08b0dc30 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swiftindex f137df61..c1da30e8 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swiftindex ab2d3879..e417b38f 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let container = try ModelContainer( for: schema, configurations: [ModelConfiguration(@@ -439,7 +439,7 @@ struct WriteSiteRelationshipTests { let dir = try TempDir("WriteSiteImportFill") let cfg = configuration(dir) let (_, repository) = try await LibraryRepository.openForApp(cfg)- #expect(try markerContent(cfg) == "19",+ #expect(try markerContent(cfg) == "20", "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) == "19", "the import republishes nothing")+ #expect(try markerContent(cfg) == "20", "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) == "19")+ #expect(try markerContent(cfg) == "20") try expectEveryRelationshipPopulated(cfg) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swiftindex e18519a4..e04e334a 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: AsterismSchemaV19.self)+ let schema = Schema(versionedSchema: AsterismSchemaV20.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV19MigrationPlan.self,+ for: schema, migrationPlan: AsterismV20MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/AGENTS.md b/AGENTS.mdindex a1abd6c3..0c382896 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -154,10 +154,11 @@ When adding tests, follow **Writing efficient tests** in `docs/agent-notes/testing.md`: put value rules on the native host, state runtime dependencies explicitly, and review fast-manifest placement with each new suite. -**The live store schema is 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+**The live store schema is V20** (`specs/url-optional-chapter-notes/`), the readiness+marker generation is `"20"`, and the retained migration chain is V16 → V17 →+V18 → V19 → V20. V16–V19 are frozen snapshots; app markers 16–20 remain+accepted, while the extension opens only 20. The current archive generation is+**19/20**, with bounded conversion of predecessor 18/19 archives. The archive envelope test pins its schema version to the live store. `docs/agent-notes/schema-migration.md` is the procedure for moving all four.
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 87b528ba..5b394243 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- **URL-optional works and chapter notes (T-2416):** allow URL-free works and+ manual notes/ratings with optional titles and links. Keep generic untitled+ notes independent, use work-scoped chapter identity across shared/mixed pages,+ and retain content and source links through corrections. Add an editable+ capture default, additive V20 migration, format 19/schema 20 archives and+ predecessor archive conversion. Full Core and signed Mac/native gates pass,+ alongside full iPad acceptance (30/30). The original full phone gate failed+ five tests; all five pass one focused confirmation after repairing actionable+ backup-refusal reporting. Incoming share, saved-combine conflict and Mac form+ rendering remain unverified; the change is prepared as a draft PR.+ - **Export selected day's notes — App increment (T-2404):** add a dated export action to Today's single-day header, using the displayed date, calendar and locale. Reuse native Markdown sharing, explain empty days, suppress
diff --git a/docs/agent-notes/schema-migration.md b/docs/agent-notes/schema-migration.mdindex 6dbc1dd1..424d79f5 100644--- a/docs/agent-notes/schema-migration.md+++ b/docs/agent-notes/schema-migration.md@@ -1,11 +1,13 @@ # Schema migration -Schema **V17** is live (`specs/catch-up-progress/`), with **V16** frozen-beside it as the `from` side of one lightweight stage. The app accepts readiness-markers `"16"` and `"17"`; the extension accepts `"17"` only. V17 adds two optional-`Work` Data columns, `catchUpConfirmationData` and `lastChapterOverrideData`.-Converted V16 rows carry nil in both. The archive is **16/17** and the envelope-contract again asserts the live schema version directly.+Schema **V20** is live (`specs/url-optional-chapter-notes/`), with V16–V19+retained as frozen predecessors. The app accepts readiness markers `"16"`+through `"20"`; the extension accepts `"20"` only. V20 adds optional authored+entry/redirect/resolution metadata, an optional Work capture default and the+relationship-free `EntrySource` table. Converted V19 rows retain nil/default+values without a backfill. The current archive is **19/20**, with bounded+conversion of predecessor **18/19** archives; the envelope contract asserts the+live schema version directly. The app and extension still open through `openForApp` and `openForExtension` respectively, over the same fixed file layout. The detailed V16 account below@@ -13,18 +15,20 @@ is retained as the worked example for the next freeze. ## Current state -- The live classes are nested in `extension AsterismSchemaV17` in `Models.swift`- and reached through top-level typealiases. `AsterismSchemaV16.swift` holds the- one frozen snapshot: stored fields, relationship macros and defaults only.- Its `Work.thumbnailData` keeps `.externalStorage`, and its referenced raw+- The live classes are nested in `extension AsterismSchemaV20` in `Models.swift`+ and reached through top-level typealiases. `AsterismSchemaV16.swift` through+ `AsterismSchemaV19.swift` hold frozen stored fields, relationship macros and+ defaults only. `Work.thumbnailData` keeps `.externalStorage`, and referenced raw spellings and value types stay frozen by reference.-- `AsterismV17MigrationPlan` is `[V16, V17]` with one lightweight stage. The- V16 recorded-store fixture creates, seeds, saves and releases its container+- `AsterismV20MigrationPlan` is `[V16, V17, V18, V19, V20]` with four lightweight+ stages. Keep reachable stages absent the owner's population proof. Each+ recorded-store fixture creates, seeds, saves and releases its container before opening the live schema; this order matters to SwiftData's global- entity registry. The conversion test checks the new raw blobs are nil.+ entity registry. The V19 conversion checks new raw blobs are nil and the+ source table is empty while existing data survives. - A Work group's snapshot elects catch-up confirmation and override across all rows, independently of its authored-content carrier. `CatchUpWriter` writes- only where the decoded value differs. The 16/17 archive exports that elected+ only where the decoded value differs. The current archive exports that elected record and imports it before authored-content recency guards. ## V16 worked example (historical)
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 8b3146d8..befb0acb 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -60,6 +60,7 @@ | [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. |+| [URL-optional Works and Chapter Notes](#url-optional-works-and-chapter-notes) | 2026-10-10 | In Progress | T-2416: URL-free works and manual notes/ratings, optional titles, work-scoped chapter identity and source links across shared/mixed page layouts, preserved corrections and additive migration/archive compatibility. | --- @@ -980,3 +981,14 @@ T2404. Today's selected date controls one Markdown document of notes and ratings - [verification-run.md](export-todays-notes/verification-run.md) - [gate-evidence.json](export-todays-notes/gate-evidence.json) - [implementation.md](export-todays-notes/implementation.md)++## URL-optional Works and Chapter Notes++Approved package `198b65ab`; implementation in progress for T-2416. Retains ordinary serial capture while supporting URL-free works/entries, independent untitled notes, same-page chapters and mixed layouts. T-2417 remains deferred.++- [requirements.md](url-optional-chapter-notes/requirements.md)+- [design.md](url-optional-chapter-notes/design.md)+- [tasks.md](url-optional-chapter-notes/tasks.md)+- [decision_log.md](url-optional-chapter-notes/decision_log.md)+- [review.md](url-optional-chapter-notes/review.md)+- [implementation.md](url-optional-chapter-notes/implementation.md)
diff --git a/specs/url-optional-chapter-notes/decision_log.md b/specs/url-optional-chapter-notes/decision_log.mdnew file mode 100644index 00000000..72a9805a--- /dev/null+++ b/specs/url-optional-chapter-notes/decision_log.md@@ -0,0 +1,176 @@+# Decision log — T-2416++Status: approved for implementation at reviewed package `198b65ab`, with direct implementation/test/commit/draft-PR authorisation recorded below. Full spec route: persisted identity/schema and user-owned capture behaviour trigger the full workflow. The initial specification-only mandate and its restrictions describe the original phase; implementation proceeds under the later approval.++## Quick Decisions++| ID | Date | Decision | Rationale / authority |+|---|---|---|---|+| Q1 | 2026-10-10 | Proposed name `url-optional-chapter-notes`, branch `T-2416/url-optional-chapter-notes` | Derived from supplied scope; naming can be overridden at review. Branch/commit explicitly requested |+| Q2 | 2026-10-10 | Any work type can have no URL; purchase/source links optional | User clarification; no offline type, content import or reader |+| Q3 | 2026-10-10 | Manual titles optional; untitled notes independent; rating-only accepted | Final user clarification supersedes diagram's earlier manual-title implication |+| Q4 | 2026-10-10 | Offer chapter option on unidentified pages regardless of other chapter URLs | Final user clarification supersedes suppressing the option when other chapter URLs exist |+| Q5 | 2026-10-10 | Clear chapter evidence wins in either work default; keep correction | User's chapter-12 example and mixed tthfanfic.org reading layouts |+| Q6 | 2026-10-10 | Future published-book series linking is T-2417 | Supplied historical context resolves latest “2147”; record direction only |+| Q7 | 2026-10-10 | Baseline V19/18–19 archive, app markers 16–19, extension 19 | Source at 6997feed overrides stale V17 prose; preserve reachable chain absent population proof |+| Q8 | 2026-10-10 | No live Transit read or status change claimed | Earlier timeout/cancelled handoff; no callable Transit read discovered here |+| Q9 | 2026-10-10 | Do not materialise supplementary Library diagram | Authoritative supplied text sufficient; no assumed cloud filesystem path |+| Q10 | 2026-10-10 | Isolated worktree, original untracked `specs/general/` untouched | Preserve unrelated work; feature branch explicitly authorised |+| Q11 | 2026-10-10 | Initial spec validation was docs-only; implementation uses targeted development and full final gates | AGENTS.md phase policy; later implementation approval recorded below |+| Q12 | 2026-10-10 | Recall migration nesting and rollback re-fault notes | Obsidian generated knowledge read before design; current repository policy takes precedence over historical note examples |+| Q13 | 2026-10-10 | Clear comparable detected chapters keep automatic ordinary capture | Requirement 3.1 and resolver step 4 take precedence over overlapping step 6 wording; see Decision 5 |++## Decision 1: Entry UUID identity separated from source pages++**Date:** 2026-10-10 +**Status:** Approved in reviewed package `198b65ab`++### Context++Entry already owns an application UUID, immutable capture evidence and one note/rating. Capture keys and duplicate detection treat raw URLs as identity aliases. Allowing multiple chapters on one page with that alias would collapse intentional entries. Replacing raw capture evidence would lose provenance; a separate Chapter entity would add another identity and migration layer for the same one-note-per-chapter experience.++### Decision++Retain Entry as the note/chapter record. Add an authored target blob, UUID-keyed explicit identity and relationship-free EntrySource associations. Legacy rows retain their keys; explicitly selected chapters and manual notes use UUID identity, and their source URLs do not participate in distinct-UUID collapse. Source associations join by UUID and follow established reconcile/export/import/delete machinery.++### Alternatives considered++- Composite page URL plus title: empty titles collide, edited labels change identity, and one chapter at two addresses duplicates.+- Add a Chapter table and Note children: defensible for multiple note histories per chapter, outside this feature's requested scope.+- Store source URLs as an array: concurrent source additions to one entry would overwrite each other and lacks the existing join-table ownership shape.++### Consequences++One new table requires full parity work, but no legacy data pass. Source links can be shared by distinct entries. A title or designation is lookup evidence within a selected work, not a globally unique key. Existing generic notes stay independent.++## Decision 2: Conservative chapter evidence and explicit ambiguity++**Date:** 2026-10-10 +**Status:** Approved in reviewed package `198b65ab`++### Context++Existing capture candidates are raw URL/v2/v3 strings, and `.new` also covers torn or multiple logical matches. `ComposedDeriver.chapterSettled` is presentation evidence; ChapterPlacement is ordering, including site-wide IDs. Neither is a confidence API. Mixed layouts need a choice when existing labels cannot be compared with a new page.++### Decision++Retain evidence origin and work-scoped targets in a resolver. Specific agreeing identity evidence resolves normally; URL associations do not override a specific chapter. Conflicts, unresolved comparability and several source-linked targets require reader selection. A deliberate new chapter bypasses the old same-URL collapse semantics through explicit UUID identity. Corrections override future derived targeting while preserving raw evidence.++### Alternatives considered++- Invent a numeric confidence threshold: no existing support or need in this personal app.+- Equate sorted chapter numbers or all equal display titles: re-teaching and site-wide positions can identify different things.+- Keep `.new` for every ambiguous chapter match: risks duplicating or overwriting during mixed layouts.++### Consequences++Ordinary one-page-per-chapter shares stay simple; difficult cases gain an explicit choice. A background pending-capture drain must set aside selection-required shares until interactive review rather than guessing. No site-wide policy is stored.++## Decision 3: Additive migration and bounded archive compatibility++**Date:** 2026-10-10 +**Status:** Approved in reviewed package `198b65ab`++### Context++The checkout's live schema is V19, with V16–19 stages and 18/19 archives despite stale documentation. SwiftData mirrors to CloudKit; old writers cannot understand authored chapter identities. Existing importer accepts one archive pair. New backup semantics must preserve independent URL-free notes and source associations.++### Decision++Freeze actual V19 and add optional/defaulted facts and EntrySource by lightweight stage; nil/default interprets legacy rows unchanged. Keep reachable old stages and marker acceptance absent positive population proof. Support only the current 18/19 predecessor archive through an explicit converter plus the new 19/20 archive. Coordinate upgrade of all writing installations before rollout; never reset a live store or CloudKit environment to make the feature work.++### Alternatives considered++- Remove older stages to match AGENTS prose: installed population has not been verified.+- Rewrite every legacy entry into authored identity: unnecessary mutation of preserved evidence and sync risk.+- Require new archives only: discards practical restore access to the currently supported backup without necessity.++### Consequences++Early recorded-store and archive tests gate downstream tasks. Device mirroring remains a later owner validation on Development data; this spec does not authorise Personal app runs.++## Decision 4: Learn a default on deliberate second-chapter save++**Date:** 2026-10-10 +**Status:** Approved in reviewed package `198b65ab`++### Context++The discussion established a work that is known to have several chapters per page should default to a chapter draft and that edit-work should allow an override. It did not settle the exact learning trigger or whether an extra confirmation is wanted.++### Decision++Recommend immediate learning when a deliberate chapter save creates a second distinct chapter on an already used source URL. State this in the sheet before Save; stage it with the entry commit. Generic notes and cancellation do not teach the default. Edit-work can reset to ordinary. Another deliberate second-chapter save can teach it again.++### Alternatives considered++- Confirm with a separate prompt: extra interruption, but viable if the reader wants learning to require a separate decision.+- Infer from presence of other chapter URLs: does not identify whole-work pages and violates the final clarification.+- Restrict all future shares to one layout: incompatible with mixed mode reading.++### Consequences++One reviewable product choice remains. The default never changes identity, removes correction or disables a capture path.++## Pre-approval review and validation (historical)++Approval checkpoint required by the current starwave-creating-spec SKILL.md: “Each phase builds on the previous one and requires explicit user approval before proceeding.” This deliverable is a concrete draft of all explicitly requested spec artifacts, not a declaration of those approvals. Present full-spec scope/name and requirements first, then design and tasks for approval. Do not move Transit to ready-for-implementation or start code work.++The explain-like self-validation uses three levels: beginner—one chapter can have several web links, while untitled notes remain separate; intermediate—authoritative UUID targets and authored labels are separate from re-derivable capture evidence; expert—legacy raw-URL collapse must exclude explicit targets, commit matching must recheck under the lock, and source arrivals must tolerate missing targets. This exposed the need for source parity, pending-drain selection and preserving the actually reachable migration chain; all are included in design/tasks.++Knowledge consulted: `SwiftData in-process schema migration without entity-name crashes.md` and `Why SwiftData rollback doesn't restore your @Model properties.md` in the configured Obsidian `03-Notes/Generated` folder. Apply nested schemas, release-before-live-open fixture ordering, repository rollback/re-fault and draft preservation; do not copy historical custom migration recipes.++Design-critic review found four gaps and they were incorporated: protect every same-page chapter create path; explicitly exclude superseded correction keys from automatic matching; use exact work/rule-scoped designation comparison with first association confirmed by selection; retain durable merge redirects for late source arrivals. `LibraryRepository+Redirect.swift` confirms existing collapse mappings are session-only and raw-key fallback cannot safely redirect explicit targets, so a retained UUID redirect column is necessary. This is proposed design, not existing functionality.++Independent local peer validation confirmed the scope and identified a raw-only loser link gap. Combination now materialises loser raw/canonical links on the survivor before commit; a reopen/backup round-trip acceptance example covers A/B preservation. No external Kiro or Codex consultation tool was available, so this was independent local agent validation, not a claimed external review.++Task authoring used Rune batch operations: fourteen pending tasks, seven adjacent red/green pairs, one stream, an acyclic sequential dependency chain. Overview publication and Transit workflow completion are deferred until explicit phase approvals. No build, application run, installation or live data operation was performed.++Final independent validation found no critical contradictions after task authoring. All 22 acceptance criteria are referenced by the 14 pending tasks; Rune renders the adjacent red/green dependencies without warnings. Explicit user phase approvals and Decision 4 remain pending.++## Review completion audit — 2026-10-10++The original design-critic and independent validator reviews actually ran; their exact reports are retained in [review.md](review.md). The initial validator was only one peer perspective, which did not meet the prescribed agent's minimum of two. The current peer-review-validator definition was found at `/Users/arjen/projects/personal/agentic-coding/claude/agents/peer-review-validator.md`. `PERSONAL_PROJECTS=1` selects external-model mode; neither prescribed external MCP reviewer is available here, so its documented subagent fallback is used. The valid first peer is reused and `/root/architecture_peer` supplies the second, with a distinct maintainability/architecture lens. No external-model consultation is claimed.++The architecture peer validated all earlier critic/peer findings and found one additional preservation gap: offline edits to a retained redirected loser could become invisible. Adopted a persisted accepted-content baseline (`mergeResolutionData`) and visible unresolved-content review on mismatch, using existing authored-group conflict handling. Added an arrival-order/backup example and task-3/4 checks. This is required data preservation, not a new product choice. The only outstanding product recommendation remains the default-learning trigger. User has explicitly authorised these review steps before personal review; no intervening approval was requested.++The second peer checked the late-authored-content revision and returned “Review-ready” with no remaining architecture blocker. Full retained reports, dispositions, consultation-mode audit and consensus are in [review.md](review.md). The completed review process now has a valid design-critic review followed by two independent peer perspectives and verification of consequential fixes.++## User approval and implementation authorisation++User message `Sentinel_1affe3cfcb4881918a193589e7937ca1`: “Thanks. I've reviewed the asterism spec and it's approved”. This approves the reviewed requirements/design/tasks/decision package at `198b65ab`, including Decision 4's immediate learning trigger. The follow-up delegation explicitly authorises implementation, coherent feature-branch commits, final pre-push review and a draft PR. T-2417 stays deferred. Earlier statements that phase approvals were pending describe the pre-approval review state and are superseded by this record. Device installs, Personal data runs and merge are not authorised.++The owner subsequently confirmed directly in the implementation task: “I approve implementing T-2416 according to the approved spec, including code changes, tests, commits and a draft P”. This resolved an automatic approval review that had rejected a source-edit/simulator setup command because the previous implementation approval was available only as forwarded transcript evidence. Work resumed under this direct approval; no rejected command was bypassed. “Draft P” is interpreted in the explicit draft-PR context above.++## Decision 5: Ordinary detected chapters retain automatic capture++**Date:** 2026-10-10+**Status:** accepted interpretation of the approved requirements++### Context++The first broad regression run exposed overlapping wording in resolver steps 4 and 6. Requirement 3.1 and the owner's explicit request preserve the ordinary create/update flow when a page clearly identifies a chapter.++### Decision++Step 4 takes precedence: a clear, comparable new chapter uses automatic creation even when other comparable chapters exist. Step 6's deliberate confirmation applies to unidentified or selection-required drafts, including incomparable or conflicting existing evidence. The design wording was clarified accordingly. Ordinary automatic captures retain their existing identity/derivation; every distinct same-page chapter still receives UUID protection and source evidence.++### Alternatives considered++Requiring confirmation for all subsequent chapters would add friction to ordinary serials and contradict Requirement 3.1. Blanket UUID promotion would also remove their existing cross-device duplicate handling.++### Consequences++The implementation must reuse established derived Work/chapter writes and identity citations. Ambiguous captures continue to require review. Focused and full regression checks remain required before completion; this clarification adds no new feature scope.++## Consequential-fix verification++The final source recheck found a late `EntrySource` arrival race in ordinary-new capture and missing cited title-only designation evidence during legacy promotion. Both received genuine red fixtures and focused green verification. Save now compares a fresh chapter projection before ordinary insertion; legacy binding preservation includes the cited nonblank title designation in its existing rule namespace. These enforce the approved freshness and evidence-preservation requirements.++Decision 4's deliberate learning trigger is implemented as an explicit `.newChapter` intent. Automatic detected same-page chapters and corrections do not change the work default. The sheet's pre-Save explanation therefore covers every save that learns it. This aligns the implementation with the approved decision rather than adding a product choice.++The full phone acceptance run exposed a backup-refusal regression: typed export refusals were being wrapped as an unavailable library inside the lock. Reusing the predecessor typed `Result` transport restores the actionable blocker count and Check Library path while preserving unexpected-error handling. Both real snapshot/export variants reproduced the failure before repair and passed after it; fresh full Core verification also passes. This restores an existing contract and adds no product decision.++## Final implementation verification disposition++Fresh full Core, signed Mac/native and full iPad gates pass. The original full phone gate executed all 210 expected declarations: 203 passed, five failed and two skipped. Two failures exposed the backup-refusal regression repaired above; three launch/setup accessibility snapshots did not reproduce in the single five-identifier confirmation, which passed all five. The original full gate remains failed, with no baseline waiver or unchanged broad rerun. Tasks 11/13 and the overview remain In Progress for the named rendered coverage gaps. This supports an explicitly authorised draft PR, not a merge or rollout. No additional product decision or approval checkpoint was introduced.
diff --git a/specs/url-optional-chapter-notes/design.md b/specs/url-optional-chapter-notes/design.mdnew file mode 100644index 00000000..24638f35--- /dev/null+++ b/specs/url-optional-chapter-notes/design.md@@ -0,0 +1,107 @@+# Design — URL-optional works and chapter notes++Status: approved for implementation as part of reviewed package `198b65ab`. Baseline: `6997feed` (2026-10-10). Paths below are repository-relative under `Packages/AsterismCore/Sources/AsterismCore/` unless qualified.++## Repository findings++| Evidence | Consequence |+|---|---|+| `Models.swift`: Entry/Work UUIDs; immutable `captureTitle`, `rawURLString`, hostname and capture times; chapter fields are derived with `EntryCitations` | Keep UUID identity and capture evidence; manual labels/corrections need authored fields rather than rewriting capture fields |+| `LibraryRepository.swift: validatedNewWork/insertWork`, `RepositoryDrafts.swift: NewWorkDraft`; `Asterism/Asterism/Views/NewWorkView.swift` | Work URL itself is optional, but creation still requires a site-or-URL and always creates a Site/membership. Permit truly site-free creation |+| `LibraryRepository+Capture.swift: captureCandidates/captureMatches/lookupDisposition` | Raw URL plus v2 work-identity/sequence and v3 title-derived work-name/sequence candidates; host scoped. Only one non-torn logical UUID group edits. Multiple/torn matches currently become new captures |+| `ComposedDeriver.swift: chapterSettled/composeIdentity` | Chapter title or sequence can settle presentation while identity remains raw-URL v1. This is evidence, not a confidence score or proof that an arbitrary title identifies a chapter |+| `ChapterKeyDerivation.swift`, `ChapterNumber.swift` | Placement is a sorting heuristic: numbered keys and large site-wide positions are different scales. Never use placement equality as identity |+| `LibraryRepository+ReparseCapture.swift: commitCapture`, `CaptureViewModel.swift` | New capture needs a title and HTTP(S) URL; pre-insert race guard redoes key matching. No dedicated URL-free note creation found |+| `LibraryValidator.swift` | Alias must equal raw URL; v1 key must equal raw URL; cited v2/v3 keys replay against rules. New authored identity cases need explicit validator branches |+| `DuplicateScan.swift: entryBucketKey` | Distinct-UUID duplicates currently bucket by hostname + conservative raw URL. It would collapse intentional same-page chapters without a revised predicate |+| `Models.swift`, `AsterismSchemaV19.swift`, `LibraryRepository+Bootstrap.swift`, `BackupV18Types.swift`, `BackupImporter.swift` | Source baseline is V19, migration chain V16→17→18→19; app markers 16–19, extension 19 only; archive 18/19, importer accepts one pair. AGENTS/schema-migration prose stating V17 and a two-version plan is stale |+| `MarkdownExport.swift: formatEntry`, Work/Today presentations and notes exports | Heading is always linked today; URL-free entries need plain headings and absent links, not `[]()` |++No live Transit ticket was read; no callable Transit read tool was available. This design follows the supplied discussion. The diagram is supplementary and was not materialised.++## Identity and data models++An Entry remains the unit containing one editable note/rating. A chapter entry represents one chapter in a work; a generic note represents an independent reaction. Work-level `genericNotes` remains unchanged. Neither optional display titles nor source URLs identify generic notes.++Add these CloudKit-legal facts in the next live schema (V20 if this baseline remains current):++| Fact | Shape and interpretation |+|---|---|+| Work chapter capture default | Defaulted raw string on Work: `ordinary` or `multipleChaptersPerPage`. Synced authored content, edited through WorkMetadataDraft and existing group conflict handling |+| Authored entry target | Optional Codable Data blob on Entry: kind (`note`/`chapter`), optional display title, optional chapter designation. Nil preserves legacy derived presentation/identity. An explicit blob supersedes derived chapter fields for target/display without erasing them |+| Explicit merge redirect | Optional UUID `mergedIntoEntryID` and optional Codable `mergeResolutionData` baseline on Entry; a retained loser becomes a redirect after successful content resolution, preserving identity for late source arrivals and detecting late authored edits |+| Source association | New nested `EntrySource` model: defaulted UUID `id`, UUID `entryID`, HTTP(S) `urlString`, hostname, created/modified timestamps and optional typed matching-evidence/supersession Data blob; no relationships or uniqueness constraints. Reference by Entry UUID only |++The source set is the immutable original raw/canonical capture evidence plus EntrySource associations. Existing rows need no backfill. New manual entries have empty raw URL/hostname, nil Site and fresh UUID; source rows hold optional links without inventing capture evidence. A shared chapter keeps the first raw capture untouched; a subsequent different URL becomes an EntrySource row. Same-URL chapters each retain the page as a source. Source dedupe elects deterministically per `(entryID, exact URL)` and tolerates missing Entry arrivals; it never equates target entries.++For explicitly authored entries, use a UUID-derived entry key and no conservative alias; add a closed identity/citation basis for that case. Generic notes have no chapter key. Explicit chapter designation is an exact reader-owned label (e.g. `12`, `5.07`, `Interlude`), not a guessed ordinal. The manual entry title can supply the label when the reader chooses Chapter; blank titles never supply a key. Duplicate designations within a work are ambiguous, not permission to collapse. A manually selected existing Entry UUID is authoritative.++Designation comparison trims surrounding whitespace and compares exact scalar strings, scoped to the selected Work UUID. Taught `chapterSequence` may compare exactly only within its cited rule's sequence namespace; a title-derived label may compare exactly to an authored label only through an explicitly confirmed designation association. `12`, `Chapter 12` and `012` are not silently equated. Existing number extraction remains for ordering, not matching. A manual chapter first encountered through a web rule requires selection to establish that association; the source and its typed v2/v3 evidence are retained with the EntrySource record (optional Codable evidence blob, no confidence number). Subsequent identical evidence can resolve the selected chapter. A correction marks that association's specific evidence as superseded; raw source URLs remain available for selection but superseded keys are excluded from automatic matching, allowing an actual chapter-12 share to create/select chapter 12 later.++Keep legacy v1/v2/v3 fields/citations intact for legacy rows. Apply their replay validation only to legacy identity cases. A corrected entry's derived keys are evidence for review, not permission to override its authored target. Do not deduplicate by a title, inferred placement or source link. Same-UUID convergence continues; intentional explicit entries are excluded from the distinct-UUID raw-URL collapse bucket. Legacy ordinary captures retain that bucket. Every path that creates a distinct chapter on an already used source page—including ordinary rule-detected chapter creation—promotes the new target to explicit UUID identity before the duplicate pass. Existing legacy records sharing the page remain preserved; no destructive mutation of their capture evidence is required.++## Matching and share flow++Add a read-only `ChapterCaptureResolver` in Core beside the existing capture lookup. Extend snapshots/contracts with evidence and a target choice; this is a new proposed interface, not a currently available confidence API. Preserve rule-derived candidates with their origin (`rawURL`, `v2`, `v3`, parsed chapter label), candidate UUIDs and conflict reason rather than flattening them into strings. Run taught derivation before choosing the sheet, including on re-share; it must not depend on the current lookup's “edit skips title acquisition” shortcut.++1. Resolve the work using existing work projection/matching or reader work selection. Never match chapter labels across works.+2. Treat v2/v3 candidates as specific chapter evidence within that work, subject to authored corrections. A taught chapter title can identify a chapter through exact nonblank designation matching, but a work title alone cannot. Untaught page text is not a chapter classifier. A site-wide numeric URL position is not comparable to a reader's chapter number.+3. Accept an automatic update only for one non-torn target with agreeing evidence. If a specific chapter key says 12 while a shared-page URL points at another chapter, the page association is not a conflicting identity: filter by chapter 12. Conflicting specific keys/designations or multiple surviving candidates require selection.+4. With specific evidence and no existing target, use ordinary create flow and hide “Add another chapter”; expose “Change chapter” to correct it. If the work already contains entries that cannot be compared with that designation (e.g. site-wide IDs or unlabelled chapters), present existing selection before creating; zero key matches is not proof of novelty across layouts.+5. Without specific evidence, ordinary mode preserves the existing one-target saved-URL update and new-URL new-entry defaults. Offer “Add another chapter” regardless of other chapter URLs. Multiple URL-linked entries require choice. Multiple-chapters-per-page mode starts a new chapter draft, with “Choose existing chapter” visible and a generic note alternative.+6. On an unidentified or selection-required new chapter draft, show existing chapters whenever the work has entries; saving requires deliberate new-chapter confirmation or existing selection. Step 4's clear, comparable detected chapter retains the ordinary automatic create flow; having other comparable chapters alone does not add confirmation. Untitled chapters may be deliberately created, but have UUID identity only and cannot be automatically matched by an empty designation. Generic note creation needs no chapter selection.++No mode change restricts capture. Strong evidence wins in either default. The edit-work control is “Pages usually contain” with ordinary/multiple-chapters choices, alongside existing metadata pickers and Save/Cancel. Saving a second distinct chapter associated with a page already used by that work sets the multiple default in the same repository commit; generic notes and cancellation do not. The share sheet tells the reader this default will be remembered. Setting ordinary later leaves links/entries untouched; another deliberate same-page chapter save can teach the multiple default again.++### Commit and correction contracts++Project/commit is the existing pattern: immutable drafts, no writes before Save, one exclusive repository operation for target, note/rating, source association and any learned default. Re-derive matching, current target group, work assignment, rule revision and authored baseline under the lock. A changed target, ambiguous set, torn group or stale baseline returns review-required with the exact draft retained. Existing stale-conflict handling is the baseline; never load over an in-progress draft.++Before Save, “Change chapter” returns to selection without discarding note/rating. After Save, EntryDetail adds an authored title/designation correction and “Use existing chapter”. Reuse duplicate content review for conflicting authored content; combine only after reader selection and successful survivor commit, then re-point EntrySource rows and record a durable UUID redirect on a retained loser Entry when either entry has explicit identity or source associations. The loser is excluded from active notes/counts and resolves to its survivor; this is logical combination, not deleting the only durable identity mapping. Source-free legacy duplicate collapse keeps its existing deletion safeguards. Before committing a combination, materialise every nonblank loser raw/canonical capture URL into survivor-owned EntrySource associations, retaining typed evidence and supersession state. This includes a loser with no existing EntrySource rows. The survivor effective source set, matching, deterministic primary-link selection and Markdown export therefore include those links after reopen and archive restore. The retained loser also keeps its raw evidence. Source reads and writes follow `mergedIntoEntryID` chains to the surviving UUID, independently of the existing session-only `collapseSurvivors` optimisation. Conflicting redirects or cycles require review; unresolved targets remain preserved and backup export refuses them by name rather than dropping sources. Late source rows addressed to a retained loser remain reachable through its redirect. Archive/import preserve redirect rows and references; deletion of a work removes its retained redirects and sources through predicated fetches. A redirect hides a loser only while its effective authored content equals the baseline accepted at content resolution. `mergeResolutionData` stores the accepted loser note, rating, authored title/target and work assignment, excluding the redirect/baseline fields themselves; compare values, not elapsed time or arrival order. Missing/undecodable baselines, differing destination/baseline copies, a torn group or later authored content that differs from the baseline make the loser visible as “Changes after combine” and require conflict review. Preserve the survivor and changed loser content separately; do not automatically forward changes or overwrite the survivor. Source links can follow the recorded redirect, but automatic chapter targeting refuses the unresolved content set. Reuse the existing authored-group/torn-content review to let the reader resolve again; its successful exclusive commit refreshes the baseline, and a refusal retains both drafts. Export/import include redirect and resolution evidence, and refuse unresolved conflicts rather than producing an archive that hides late edits. The baseline never exempts records from existing same-UUID conflict detection.++Correcting a chapter into a generic note clears authored designation and preserves its UUID/sources. A later share of ambiguous or corrected source evidence asks for selection rather than undoing the correction.++The pending-capture spool continues to preserve raw web shares before open; no migration or reconciliation in the extension. A background drain has no reader present: if a capture needs chapter selection, retain it as set aside with a review reason, not silently create/update a target. Carry selected target only in an interactive commit contract, not in an unconfirmed raw spool record. The share extension still requires a web URL; URL-free entry creation belongs in-app.++## Integration and parity audit++| Consumer / existing pattern | Needs equivalent | Required change |+|---|---|---|+| NewWorkDraft, `validatedNewWork`, `insertWork`, NewWorkFormModel/NewWorkView | Yes | Blank site-or-URL produces zero memberships; typed link creates membership as today; optional label and edit support |+| `Work.create`, site/membership helpers, Works/Sites snapshots and `WorkURLPlanner` | Yes | No fake host/Site; add valid link and membership on demand; source/purchase host need not host entries |+| Capture candidates/matches, LookupCaptureViewModel, CaptureViewModel, Capture/ReShareCaptureView, ShareCaptureSession | Yes | Resolver and target selection for new/edit paths, correction and explicit same-page chapter choice |+| `LibraryProviding`, RepositoryDrafts, Contracts/OutcomeComputation, ReparseCapture commit, ReShareUpdate | Yes | Work-scoped read contract and explicit commit intent; retain legacy web input restrictions on web APIs |+| WorkDetailModel/WorkDetailView and EntryDetailModel/EntryDetailView | Yes | “Add note” for every work; optional title, Chapter/Note choice, rating-only save; existing form/checkmark/cancel and rating toggles as baseline |+| `GroupOrdering` authored values, Groups/snapshots, DuplicateScan/Reconciler/Resolution, Redirect, work merge/move/delete | Yes | Include authored targets/defaults; UUID identity cases; source re-pointing/cascades; no URL-only collapse of explicit targets; review chapter collisions after work move/merge |+| ComposedTeaching/reparse and URLIdentity review | Yes | Recompute derived evidence, preserve authored targets and capture evidence; changed rules never undo correction |+| `LibraryValidator`, diagnostics, quarantine and graph baseline | Yes | Valid absent web tuple for manual entry; source validation/orphan tolerance; explicit identity case; hand-review graph baseline |+| PendingCaptureDrain, spool and Settings pending-capture review | Yes | Preserve queue identity/idempotence; set aside ambiguous chapter targets and offer interactive review; no guessed chapter |+| `LibraryRepository+Intents`/AddPageToReadFlow | Yes | Reuse revised web lookup so shared source is not entry identity; add-page intent remains URL-required and creates works, not manual chapters |+| Backup projection/builders/reference checks/exporter/codec/import/confirm-import | Yes | Authored fields and source records, orphan/torn-group refusals as applicable, non-regressing UUID upsert and old-format conversion |+| WorkDetail/Today/Stats/search, ShareWorkContext and catch-up placement, extraction consumers | Yes | Manual entries participate in existing notes/rating counts; authored chapter labels feed ordering/catch-up only through existing valid number rules; generic notes excluded from chapter progress; extraction reads unchanged note content |+| MarkdownExport and selected-day/work exports | Yes | Unlinked headings for absent URL, readable fallback “Note”; linked chapter headings use deterministic primary source; other links listed without changing stored URLs |+| CloudKit sync monitor, repository locks/ExportOwed | No new engine | Include new model in generic registries and ordered existing reconcile; app remains sole mirror |++## Migration, archives and rollout++Freeze the actual V19 shape, preserving referenced Codable types, raw enum spellings and external-storage attributes. Add only optional/defaulted attributes and the new relationship-free source table using a lightweight stage. Preserve existing V16→19 stages and markers until positive owner verification proves they are unreachable; do not follow stale prose by deleting the reachable chain. App accepts the currently supported marker population plus the new marker; extension accepts only the new generation. Fixed store/lock/queue paths do not move. No conversion pass, live-store experiment or database reset is needed for legacy nil/default interpretation.++Advance the archive generation with the live schema (proposed 19/20). Add a bounded decoder/converter for the currently supported 18/19 archive, mapping absent facts to nil/ordinary and no extra source rows; new archives use the new format only. Do not broaden historical archive support. Include EntrySource in all table registries: rollback/re-fault, counts, validation, export/import, deletion, empty-library and fixture coverage. Import remains UUID upsert, never deletes missing rows and never regresses newer authored data. Raw unsupported values remain tolerated on read and refused on export.++Old writers cannot enforce explicit chapter identity or retain new archive semantics. Before actual rollout, require all writing app/extension installations to be upgraded together, with an archive preserved first; no Personal run or CloudKit reset is authorised here. Real cross-device mirroring still needs the owner's isolated Development validation; simulator tests cannot prove it.++## Risks and assumptions++- Risk: lightweight migration with a new source entity and optional redirect/baseline columns fail on a production-shaped recorded store | Verify: tasks 1–2, retained old-container release ordering and raw-field assertions | If wrong: stop schema work and revise design; never fabricate an empty replacement store.+- Risk: new table arrival and re-pointing expose unsupported orphan/duplicate states | Verify: tasks 3–4 with reordered partial hydration, late loser-authored edits and rollback fixtures | If wrong: retain unresolved associations and refuse destructive collapse.+- Risk: dual URL/title lookup contracts and chapter selection race in app/extension | Verify: tasks 5–6 plus pending replay tests | If wrong: return review-required with preserved draft/spool record, no guessed write.++## Testing strategy++Future implementation uses adjacent red/green pairs in tasks.md. Use existing Swift Testing/XCTest facilities; no dependency install. Deterministic generated permutations are appropriate for invariants: independent untitled notes never collapse, same UUID converges, source order does not change target choice, archive round trips retain every source, and taught reparse cannot overwrite authored correction. Match `DuplicatePropertyTests` conventions; keep value properties separate from real SwiftData migration/rollback integration.++During development run affected Core suites using `make test-core CORE_TEST='…'`, `make test-fast`, focused `make test-only TEST=AsterismTests/<Suite>` and named affected UI journeys only. Proposed new suites should cover all acceptance examples plus draft cancellation, commit races, backup/import and partial hydration. Verify selected test identifiers/counts; no zero-test pass. Documentation commits need only document/link/Rune/diff checks. Code commit and pre-push bars follow AGENTS.md; full UI runs belong to pre-push-review, not development. No builds, installs, app launches or tests against live data during this specification task.++## Approved product decision++Recommendation: remember the multiple-chapters-per-page default immediately after the first successful deliberate second-chapter save on the same source, with the share-sheet explanation and edit-work reset described above (Req 4.2). The discussion established a learned default and proposed an override, but did not settle whether learning should instead require a confirmation prompt. The approved design chooses immediate learning; changing that choice affects this one trigger, not chapter identity.
diff --git a/specs/url-optional-chapter-notes/implementation.md b/specs/url-optional-chapter-notes/implementation.mdnew file mode 100644index 00000000..27c33686--- /dev/null+++ b/specs/url-optional-chapter-notes/implementation.md@@ -0,0 +1,96 @@+# T-2416 implementation explanation++This document describes the approved URL-optional work and chapter-note implementation. Final verification is recorded below. Core, signed Mac/native and iPad gates pass; the original full phone gate failed and its five failed identifiers passed one focused confirmation. The implementation is prepared as a draft PR with rendered coverage gaps still open.++## Beginner Level++### What changed++A work can be saved without a website. Its optional URL can point to a source or a purchase page. Inside the work, Add note accepts a note, a rating, or both. A title and source link are optional. Two untitled notes remain two independent entries.++The share sheet distinguishes the chapter being discussed from the page where it was found. A page can contain many chapters, and one chapter can appear on several pages. Existing taught URL/title rules supply chapter evidence first. When that evidence is insufficient or contradictory, the reader chooses an existing chapter or confirms a new one. Clearly detected chapters keep the ordinary create/update flow and offer a correction path.++### Why it matters++Notes about a paper book work alongside notes captured from a website. Switching a serial between individual chapter pages and a whole-work page preserves chapter identity and existing notes. Choosing an existing chapter preserves its saved content unless the reader deliberately chooses conflicting draft content.++### Key concepts++An entry is the saved note/rating target. A source is a link associated with that entry. A work's page-layout setting changes the initial suggestion; it remains editable and never restricts capture. Combining two entries keeps their source links and records where the old entry now points.++## Intermediate Level++### Changes overview++Core adds authored Note/Chapter metadata, a per-work capture default, and relationship-free `EntrySource` records. `ChapterCaptureResolver` projects work-scoped evidence and immutable save intent. Manual capture and correction use repository operations behind one Save boundary. App and share-extension forms bind value drafts, with cancellation and refused saves preserving input.++### Implementation approach++Explicit authored targets use entry UUID identity rather than URL identity. Legacy records keep their existing evidence and matching rules. Source associations preserve verbatim URLs, taught-rule provenance, and superseded evidence. Exact chapter labels are compared within a work and compatible rule scope; titles or site-wide ordering do not invent equivalence.++Save re-derives the projection under repository exclusion and rejects stale identity, authored content, rule, or default assumptions. Pending captures use the same conservative resolver, setting ambiguous captures aside for interactive review rather than guessing. Source-only replay cannot overwrite notes or ratings.++The additive V20 schema freezes V19 and preserves the reachable migration chain. The new backup format carries authored fields, sources, redirects and resolution baselines; bounded predecessor conversion preserves old archives. Markdown uses optional links and the same authored presentation as the app. Generic notes are excluded from chapter-progress calculations.++### Trade-offs++No new work type, reader, content importer, site-wide layout policy or confidence API is introduced. Some chapter matches need deliberate selection. Keeping explicit identity and old capture evidence separate adds small records and conservative refusal paths, but preserves data across mixed layouts and reordered sync arrivals.++## Expert Level++### Technical deep dive++Relationship-free UUID references keep the additive model compatible with CloudKit mirroring. Source convergence is content-based, preserves orphans, and routes late associations through durable entry redirects. Cycles, missing targets, torn ownership and contradictory authored copies remain unresolved rather than being repaired by elapsed time or destructive guessing.++Combining entries stores an accepted loser-content baseline. The loser is hidden only while current authored content matches that baseline. Late offline note/rating changes become visible as Changes after combine, preserve both contents, and block automatic targeting and backup export until reviewed. Markdown can still represent the addressed reviewable content. Non-content routing retains late source links and excludes superseded chapter evidence. Failure paths roll back and re-fault affected models rather than assuming in-memory values were restored.++### Architecture impact++Authored identity participates in duplicate handling, moves, work combination/deletion, exports/imports, extraction, Today presentation and share context. Raw capture evidence remains immutable. Work-level defaults are learned only on a successful deliberate second-chapter save on the same page; generic notes, corrections and cancellation do not teach that default.++### Potential issues++Simulator and host tests exercise storage contracts and reordered arrival fixtures, not live CloudKit delivery. Hardware sync verification remains a separate device-run activity. As specified in the approved rollout plan, preserve an archive and upgrade all writing app/extension installations together before actual rollout; older writers cannot enforce authored chapter identity. Published books joining an existing series remain deferred to T-2417. Full gate failures and any unexecuted checks must stay visible in the final verification record.++## Completeness Assessment++The implementation includes schema, identity/source handling, conservative capture, manual entry and correction operations, archive support, consumer presentation, and app/share forms. Independent source rechecks found no remaining blocker after the consequential fixes below. Fresh full Core and signed Mac/native gates pass. Full iPad passes 30/30. Original full phone acceptance failed 5/210; all five identifiers pass one focused confirmation after the backup repair, which does not replace the original result. Incoming share rendering, the saved-combine conflict journey and Mac form rendering remain coverage gaps. Tasks 11 and 13 remain in progress, so no complete final acceptance claim is made yet.++## Verification++The first signed Mac compile passed with its embedded share extension present (`/tmp/t2416-build-mac3.log`). Four read-only reviews covered reuse, quality, efficiency and specification adherence. Consequential source fixes were rechecked and passed the fresh full Core and native gates.++The first unfiltered Core run failed. Its 78 reported issues were classified from the XML, failing output and fixture source:++| Issues | Classification | Cause and corrective action |+| ---: | --- | --- |+| 32 | Genuine capture regressions | Blanket confirmation blocked ordinary clear chapters; the new path bypassed established derived identity/assignment writes. Restore ordinary automatic flow, legacy identity parity and derived Work/chapter writes. Fixture helpers sometimes translate noncommitted capture into Cocoa error 512; that is not evidence of a move-save regression. |+| 2 | Genuine deletion regressions | Retained-source checks rejected an ordinary torn group after valid disclosure. Preserve disclosed deletion while still refusing unseen retained predecessor changes. |+| 41 | Obsolete or incorrect fixtures | Assertions expected predecessor marker/schema/archive generations, omitted the added model/source registry, rejected now-supported URL-free work creation, or hardcoded the wrong survivor label. Update the contract assertions and retain malformed-input/refusal coverage. |+| 3 | Test infrastructure | Helper executable lookup assumed the default build directory instead of the private scratch product location. Locate the helper relative to the test product. |++No issue from that run has been verified as an unrelated baseline failure. Original evidence is retained outside the worktree in `/tmp/t2416-review-inputs/full1-core.log` and `full1-core-junit-swift-testing.xml`; the original run is not counted as passing verification. Transit subsequently released the shared native lane. Focused correction runs exposed and fixed a stale refreshed projection and missing conservative URL alias, and validated source URLs in committed snapshots. The requested source checkpoint remains labelled WIP and does not waive any gates.++The remaining focused cohort passed with 128 pass markers in nine suites. `make test-fast` verified all 456 declared identifiers and passed: 304 presentation tests in 20 suites and 152 Core native-host tests in 12 suites.++The unfiltered `make test-core` rerun passed (`/tmp/t2416-core-full2.log`). Its structured results contain no failures or errors: ConstellationKit 42, Presentation 304, Intelligence 229 and Core 3,194 passing cases, plus 55 skipped Core cases. The XML therefore contains 3,824 testcase elements, including skips and supporting-product runs. The pre/post source patch was identical. The private scratch run used an explicit validated helper executable path; no dependency install or live data operation was performed.++At this earlier checkpoint, native form/app checks and four new rendered phone journeys passed. Final full acceptance outcomes appear below. Incoming share-sheet rendering has no dedicated isolated harness; Capture/Lookup view-model and repository tests do not establish rendered extension coverage. See `tasks.md` for task state and `review.md` for the approved specification review.++A subsequent read-only recheck found that an ordinary-new fallback could miss an arriving `EntrySource` without a Work timestamp change, and that legacy promotion preserved v2/v3 evidence but omitted cited title-only designation evidence. Genuine red fixtures reproduced both; focused green checks and reviewer source rechecks confirmed the fixes. Only deliberate `.newChapter` saves learn the work default, aligning all learning with the pre-Save explanation.++The fresh unfiltered Core run also passes (`/tmp/t2416-core-full3.log`): 42 ConstellationKit, 304 Presentation, 229 Intelligence and 3,197 Core passing cases, totaling 3,772 passed plus 55 skipped Core cases (3,827 XML testcase elements), with zero failures/errors. The pre/post source patch is identical. Its XML is preserved separately; the later Core4 run supplies the final structured review input.++The first full native run failed three tests: two fixture errors (obsolete export codec and purchase URL pre-seeded as unchanged baseline) plus an Empty Library busy-state failure. The focused confirmation passed 102 declarations / 110 parameterized invocations, including all seven manual-entry and four correction-form declarations and the busy case. No unrelated-baseline classification or waiver is claimed. The fresh unfiltered `make test-quick` gate passes after the Core fixes (`/tmp/t2416-test-quick2.log`): 1,667 passing declarations, 1,710 invocations, zero failures and zero skips. It built the signed Mac app and embedded share extension before iOS app, extensions and test products. The first failed run remains recorded above.++The four new phone UI journeys pass (`/tmp/t2416-ui-focused1.log`, 164.45 seconds): untitled rating-only capture without a source URL, manual cancellation, correction of a saved chapter into an untitled generic note, and adding a purchase link to a URL-free work. These are actual rendered app checks; they do not cover incoming share-extension rendering.++The unfiltered full phone gate completed with all 210 expected declarations: 203 passed, five failed and two skipped (213 invocations: 206 passed, five failed, two skipped). XCTest took 13,623.6 seconds; result finalization added an explicitly bounded 600-second simulator-diagnostic collection. The original result is `/tmp/t2416-ui-phone-full1.xcresult`, with structured inventory in `/tmp/t2416-ui-phone-full1-summary.json` and `-tests.json`. Three failures were accessibility snapshots (`kAXErrorServerNotFound`): untitled rating-only capture, the character-place citation journey, and Today having no search field. Two failures were genuine actionable backup-refusal regressions: the blocker count/Check Library route was replaced by a generic retry message. The current snapshot throws a typed export refusal inside the repository lock, where unknown errors become `libraryUnavailable`; the repair reuses the predecessor typed `Result` transport across that boundary. Both real snapshot/export regression variants failed before the fix and passed after it. The entire chapter-archive suite passed eight declarations / nine cases. The single failed-phone cohort subsequently passed all five exact identifiers. No unrelated-baseline waiver is claimed. Runtime Calendar/CivilDay environment warnings were retained separately from the compiler-warning gate.++The repair catches only `BackupV18ExportError` into `Result<BackupV19Payload, BackupV18ExportError>` inside the lock, then calls `.get()` outside, preserving existing handling for unexpected errors. A narrow independent source review found no blocker. Fresh unfiltered Core verification passes after the repair (`/tmp/t2416-core-full4.log`): 42 ConstellationKit, 304 Presentation, 229 Intelligence and 3,198 Core passing cases, totaling 3,773 passed plus 55 skipped (3,828 XML testcase elements), with zero failures/errors. The pre/post source diff is identical. This is the latest structured review input; earlier full runs remain preserved.++Fresh unfiltered native verification passes after the backup repair (`/tmp/t2416-test-quick3.log`, `/tmp/t2416-unit3.xcresult`): 1,667 passing declarations / 1,710 invocations, zero failures/skips, and zero compiler-warning lines. Signed Mac app and embedded share-extension compilation passed. The original full phone gate remains failed; a focused confirmation does not replace that result.++The single focused confirmation of all five failed phone identifiers passes (`/tmp/t2416-ui-failed-cohort1.xcresult`): five passed, zero failures/skips, XCTest 199.3 seconds (255.7 seconds in the finalized summary). Both actionable backup-refusal assertions verify the repair. The three setup snapshot failures did not reproduce in this one confirmation; they are not classified as an approved baseline. Full phone acceptance remains failed, and no unchanged broad phone rerun was made.++Full iPad acceptance passes (`/tmp/t2416-ui-ipad-full1.xcresult`): all 30 expected declarations, comprising 27 Wide Layout and three Wide Layout Accessibility, zero failures/skips and no missing/unexpected declarations. The new rating-only manual note journey passed in 44.588 seconds. XCTest took 1,158.2 seconds (1,250.5 seconds in the finalized summary). Fourteen Calendar/CivilDay runtime environment warnings are preserved; this is not a warning-free runtime claim. All owned native jobs drained. Tasks 11/13 remain in progress for incoming share-extension rendering, saved-combine conflict UI and Mac form presentation. Live two-device CloudKit verification remains before merge; no Personal-library operation, deployment or merge was performed.
diff --git a/specs/url-optional-chapter-notes/requirements.md b/specs/url-optional-chapter-notes/requirements.mdnew file mode 100644index 00000000..3c012ac9--- /dev/null+++ b/specs/url-optional-chapter-notes/requirements.md@@ -0,0 +1,84 @@+# URL-optional works and chapter notes — T-2416++Status: approved for implementation. The user approved the reviewed package at `198b65ab` in message `Sentinel_1affe3cfcb4881918a193589e7937ca1`: “Thanks. I've reviewed the asterism spec and it's approved”. Implementation is authorised by the subsequent delegation; no device installation or merge is authorised.++## Introduction++Asterism should let the reader record a work and their reactions regardless of whether a web page exists. A page can contain one chapter or many, and the same chapter can appear at several addresses. Capture should preserve these distinctions without making the reader manage a separate offline work type.++## Non-Goals++- Imported book content, a built-in reader, or a separate offline work type.+- Site-wide chapter layout policy, scraping page bodies, or a confidence-scoring service.+- Published-book series linking: future T-2417, without design or implementation here.+- Replacing existing work-level generic notes, introducing multiple note histories per chapter, or automatically merging conflicting reader content.++### 1. Works without URLs++**User Story:** As a reader, I want to create any work without a URL, so that my library includes books and other works I record manually.++1. <a name="1.1"></a>WHEN the reader creates a titled work with no site or URL, the system SHALL save it with the ordinary selectable work types and statuses, and show it in Works. +2. <a name="1.2"></a>WHEN the reader supplies or later adds a valid source or purchase URL, the system SHALL retain it as the work's optional link without requiring chapter pages on that host. +3. <a name="1.3"></a>WHEN the reader cancels work creation or editing, the system SHALL retain the saved library unchanged. ++### 2. Manual notes and chapters++**User Story:** As a reader, I want to add notes or ratings to any work, so that I can record reactions without sharing a page.++1. <a name="2.1"></a>WHEN the reader saves a manual entry containing a note or rating, the system SHALL accept an absent entry URL and absent title; a rating alone SHALL be sufficient. +2. <a name="2.2"></a>WHEN the reader adds multiple untitled generic notes, the system SHALL keep them as distinct entries rather than treating empty titles or absent URLs as a duplicate key. +3. <a name="2.3"></a>WHEN the reader identifies a chapter through an optional title or chapter selection, the system SHALL let them create that chapter or update the chosen existing chapter; a generic note SHALL remain possible without selecting a chapter. +4. <a name="2.4"></a>WHEN a manual entry is saved, the system SHALL show its note or rating in the work, Today and notes exports under the existing inclusion rules, using a readable unlinked heading when no title or URL exists. ++### 3. Share defaults++**User Story:** As a reader, I want sharing to choose a useful default, so that ordinary chapter capture stays simple.++1. <a name="3.1"></a>WHEN current taught URL/title rules identify one chapter in one work without conflicting matches, the system SHALL use the appropriate chapter create/update flow and hide “Add another chapter”, while retaining a correction action. +2. <a name="3.2"></a>WHEN the shared page does not identify a chapter and the work uses the ordinary default, the system SHALL offer “Add another chapter”; a new URL SHALL default to a new entry and a saved URL with one unambiguous target SHALL default to updating that entry. +3. <a name="3.3"></a>WHEN the page does not identify a chapter and the work is known to have multiple chapters per page, the system SHALL default to adding a chapter with the shared source URL and allow choosing an existing chapter instead. +4. <a name="3.4"></a>WHEN several entries share the page or matching evidence disagrees, the system SHALL show a choice of existing chapter, new chapter or generic note without silently updating one candidate or silently creating a second copy of a possibly existing chapter. +5. <a name="3.5"></a>WHEN the work has chapters at other URLs, the system SHALL still offer the chapter option on an unidentified page. ++### 4. Defaults, mixed layouts and corrections++**User Story:** As a reader, I want chapters to remain the same across page layouts, so that changing reading view does not duplicate my notes.++1. <a name="4.1"></a>WHEN the reader edits the work's chapter capture default, the system SHALL apply that default only to unidentified pages for this work and SHALL leave existing entries and source links unchanged. +2. <a name="4.2"></a>WHEN the reader saves a second distinct chapter on an already used source page, the system SHALL remember the multiple-chapters-per-page default for that work; the work editor SHALL allow restoring the ordinary default. +3. <a name="4.3"></a>WHEN the reader changes from individual chapter pages to a whole-work page and back, the system SHALL update the same chosen or unambiguously matched chapter despite a different URL and retain its source links. +4. <a name="4.4"></a>WHEN chapter evidence cannot prove equivalence across addresses, the system SHALL offer chapter selection and SHALL not equate entries solely by display title, sort position or matching page URL. +5. <a name="4.5"></a>WHEN the reader corrects a detected chapter before Save, the system SHALL save to the corrected target and preserve the draft; WHEN correcting a saved entry into an existing chapter with conflicting note or rating, the system SHALL require content resolution and preserve both entries until that resolution succeeds. +6. <a name="4.6"></a>IF a save fails or its target changes concurrently, THEN the system SHALL retain the unsaved draft, explain the failure or changed target, and require renewed selection before writing to a different chapter. ++### 5. Existing data, sync and archives++**User Story:** As a reader, I want my existing library preserved, so that this change does not lose notes or collapse distinct chapters.++1. <a name="5.1"></a>WHEN opening an existing supported library, the system SHALL preserve every record UUID, capture title/URL, note, rating, timestamp, rule citation and work assignment, and SHALL not infer a multiple-chapters-per-page default from other chapter URLs. +2. <a name="5.2"></a>WHEN syncing or importing entries for distinct chapters sharing a URL or independent URL-free notes, the system SHALL retain them as distinct logical entries; copies of one entry UUID SHALL continue to converge as one logical entry. +3. <a name="5.3"></a>WHEN exporting and restoring a new-format backup, the system SHALL retain manual titles, chapter choices, capture defaults and all source links alongside existing data; unsupported formats or values SHALL be refused without a lossy restore. +4. <a name="5.4"></a>WHEN an older supported backup is restored, the system SHALL preserve its original entries and ordinary default without manufacturing chapter labels or source pages. ++## Acceptance examples++| Case | Starting point and action | Expected result |+|---|---|---|+| Ordinary serial | Taught page identifies chapter 12; share it twice | Create then update chapter 12; “Add another chapter” hidden; correction available |+| Unidentified new URL | Ordinary work; share a new URL with only the work title | Normal new-entry flow; chapter option available |+| Unidentified saved URL | Ordinary work; share the sole saved page again | Existing note/rating prefilled; chapter option available |+| Whole-work page | Choose chapter 12 on a saved whole-work URL, then add chapter 13 at the same URL | Two entries, retained URL on each; subsequent unidentified shares default to a chapter draft, with existing selection |+| Mixed layouts | tthfanfic.org-style example: capture chapter 12 on its own page, choose chapter 12 in whole-work view, then return to its individual page | One chapter UUID, updated note/rating and both source links; chapter 13 can be separate on the whole-work URL |+| Mode reset | Restore ordinary default halfway through reading | Existing entries unchanged; clear chapter evidence still wins; saved ambiguous whole-work URL asks for selection |+| URL-free work | Create a novel with a title and no site/URL; later add Amazon purchase URL | Work exists before link; type and manual capture remain ordinary |+| Untitled notes | Add two URL-free notes with no title | Two UUIDs, neither treated as a chapter or duplicate |+| Rating only | Save a manual entry with only a rating | Entry saved and presented/exported under existing rating inclusion rules |+| Incorrect detection | Rule says 12; reader chooses 13 before save | Draft saved to 13; original capture evidence retained; later matching honours correction |+| Saved correction | Wrong saved entry has a different rating from existing chapter 13 | Content review before combination; no silent overwrite or deletion |+| Concurrent change | Chosen chapter deleted or divergent copy arrives before save | Draft retained and target choice refreshed; no fallback write to another chapter |++| Detected same-page chapters | A taught title changes from chapter 12 to chapter 13 at the same URL | Both survive sync/reconciliation, even through ordinary detected-chapter create flow |+| Manual-to-web chapter | Manually label a chapter 12, then select it on its first individual-page share and whole-work share | One UUID and retained associations; “Chapter 12” versus “12” is reviewed instead of silently equated |+| Late source arrival | Combine an incorrectly detected chapter into the chosen survivor; a peer's source row for the loser arrives later | Retained redirect makes source reachable; unresolved references are preserved, never guessed or swept |+| Raw-only correction merge | Loser has original URL A and no source rows; survivor has URL B; combine then reopen and export/restore | A and B remain available on the survivor for selection and export |+| Offline edit after combination | A peer edits the retained loser note/rating while offline, then syncs after combination | Changed content remains visible for conflict review; survivor content is not silently replaced; backup refuses unresolved conflicts |
diff --git a/specs/url-optional-chapter-notes/review.md b/specs/url-optional-chapter-notes/review.mdnew file mode 100644index 00000000..2e0354ca--- /dev/null+++ b/specs/url-optional-chapter-notes/review.md@@ -0,0 +1,90 @@+# Review evidence — T-2416++This records reviews of the specification only. No reviewer ran builds, tests, installations or feature implementation. The reviewed package at `198b65ab` was subsequently approved in message `Sentinel_1affe3cfcb4881918a193589e7937ca1`; the reports below preserve the pre-approval review evidence.++## Workflow audit++- Workflow source: `/Users/arjen/projects/personal/agentic-coding/claude/skills/starwave-creating-spec/SKILL.md`, with its requirements/design skills and `/Users/arjen/projects/personal/agentic-coding/claude/agents/peer-review-validator.md`.+- The earlier design-critic agent `/root/spec_critic` was explicitly instructed to read the current design-critic skill and review requirements/design against source. Its review is valid and reused below.+- The earlier independent agent `/root/spec_validator` reviewed the revised specification, then reviewed all fourteen tasks in a follow-up. Its evidence is valid as one peer perspective, but the original report did not satisfy the validator's minimum of two independent perspectives.+- The validator definition was located during the follow-up audit. `PERSONAL_PROJECTS` was exactly `1`, selecting external-model mode. Neither prescribed `mcp__devtools__codex-agent` nor `mcp__devtools__kiro-agent` is callable in this execution environment. The definition explicitly allows subagents to make up unavailable external perspectives. Local command-line binaries being present does not establish access to those MCP reviewers; no external review is claimed.+- `/root/architecture_peer` supplies the missing independent perspective with an architecture/maintainability lens. The original peer used a correctness/data-preservation lens. Both receive the full specification and prior critic findings. The fallback agents inherit this execution environment's model; they are not claimed as Claude Opus or distinct external models.++## Design-critic report (retained)++Reviewer: `/root/spec_critic`. Inputs: requirements/design drafts based on repository `6997feed` and supplied user discussion. The substantive report was:++> Four gaps should be resolved before approval:+>+> 1. **Same-page protection must cover ordinary detected-chapter captures.** `DuplicateScan.swift` buckets legacy entries by raw URL. The design excludes explicit targets, but only explicitly promotes the “additional chapter” path. A taught page changing from chapter 12 to 13 can create another legacy entry on the same URL and subsequently collapse both. Require protection whenever distinct chapter targets share a source, including normal detected-chapter creation. Add this acceptance example.+>+> 2. **Define correction evidence precisely.** A chapter corrected from detected 12 to selected 13 must not later auto-match chapter 12 through its retained v2/v3 keys. Specify filtering of corrected targets and whether correcting an erroneous detection leaves the original URL eligible for future chapter-12 capture. Recommend retaining raw evidence but excluding superseded identity evidence from automatic target matching.+>+> 3. **Define designation comparison.** “Exact reader-owned label” leaves `12`, `Chapter 12`, and a derived chapter title underspecified. State which existing sequence representation permits exact equivalence; treat title-only or incompatible sequence scales as selection cases. Add a manual chapter-12 → individual page → whole-work page example.+>+> 4. **Specify source handling after corrections and sync arrivals.** Re-pointing source rows before deleting a loser is insufficient when delayed CloudKit rows still reference its UUID. State how existing redirects canonicalise those associations, how unresolved orphans remain preserved, and when export refuses a transient unresolved state. Add reordered-arrival and correction-merge fixtures.+>+> The drafts otherwise cover untitled independent notes, rating-only entries, default reset, mixed layouts and migration preservation. No edits, tests or builds were performed.++Disposition: all four adopted before `f4811047`. All same-page chapter create paths use protected explicit identity; corrections supersede automatic keys; matching is exact and work/rule scoped with selection for unsupported equivalence; retained UUID redirects preserve late source references. The suggested use of existing redirects was checked against `LibraryRepository+Redirect.swift`: its maps are session-only and its fallback is raw-key-based. It cannot safely handle this new case, so the design specifies a durable redirect column rather than asserting existing support.++## Peer perspective 1 — correctness and data preservation (retained)++Reviewer: `/root/spec_validator`. Initial report:++> After combining entries, include the retained loser’s original capture URL in the survivor’s effective source links, matching and Markdown export. Re-pointing `EntrySource` rows alone misses a loser that has only its immutable raw URL. Add an acceptance test covering merge → reopen → export/import with both URLs preserved.+>+> Requirements otherwise reflect the approved scope, including optional manual titles, independent untitled notes, mixed layouts and corrections. Durable redirects address late source arrivals appropriately.+>+> `tasks.md` currently contains only a 10-line draft header; implementation task coverage remains unreviewed. No edits, builds or tests were performed.++Disposition: adopted; raw/canonical loser links are materialised on the survivor before combination succeeds, with the A/B reopen/restore example and task 3 fixture. The reviewer was called again after task authoring and returned:++> Final independent validation passes with no critical contradictions found.+>+> The 14 tasks cover the requirements in seven sequential test/implementation pairs, including migration, identity, corrections, late source arrivals, archives, mixed layouts and manual capture. The raw-only loser URL gap is now explicitly addressed in the design, acceptance examples and tests.+>+> Retained redirects and legacy identity paths are compatible: explicit targets avoid URL-only collapse; legacy captures retain their existing handling; source-bearing combinations preserve durable mappings.+>+> Phase approvals and the recommended automatic-learning trigger remain pending. No edits, tests or builds performed.++This is one independent perspective with a verification follow-up, not two separate peers.++## Peer perspective 2 — architecture and maintainability++Reviewer: `/root/architecture_peer`. Inputs: full requirements/design/decision log/tasks plus prior critic and peer reports, with selective source checks. Its initial outcome was:++> **One actionable gap:** correction merges preserve late source rows, but do not explicitly preserve late **note/rating edits to the retained loser** from an offline peer. Filtering redirected losers out of active entries could hide those edits. Add a persisted content-resolution baseline, or equivalent existing authored-group evidence, so divergent late loser content produces a reviewable conflict rather than automatic forwarding, overwriting or invisibility. Add a focused arrival-order test and backup round-trip example. Existing `EntryGroup.isTorn` and `EntryAuthoredContent` machinery provide a proportionate foundation. This clarification should precede the final review-ready verdict.+>+> I validate the earlier findings:+>+> - Protecting every same-page creation path is necessary because `DuplicateScan` currently buckets by conservative URL identity.+> - Superseded matching evidence and exact work/rule-scoped designations prevent correction reversal and unsupported title equivalence.+> - Durable redirects are justified: existing collapse mappings are explicitly session-only.+> - Materialising raw-only loser URLs before combination fixes a real preservation hole.+>+> Consensus: retain Entry UUID identity, add source associations, reuse repository locking/conflict handling, and preserve additive migration/archive compatibility. This is proportionate to the requested personal app; a separate Chapter/Note hierarchy or confidence service would increase scope unnecessarily.+>+> No divergence with the prior critic or first peer. Recommend proceeding after the late-authored-content clarification. Immediate default learning remains the single stated product recommendation for user review.++Disposition: adopted. Optional `mergeResolutionData` stores the accepted loser authored content. Redirects hide a loser only while content matches the baseline; late edits, missing evidence and torn/conflicting groups surface for review without replacing survivor content. New acceptance example and tasks 1–4 cover migration defaults, arrival permutations and archive preservation.++The same peer checked this revision and returned:++> **Review-ready.** The consequential revision resolves my late-authored-content finding.+>+> The persisted resolution baseline now distinguishes accepted loser content from later edits, preserves both conflicting contents, exposes “Changes after combine,” and blocks automatic targeting until renewed review. Missing, malformed or conflicting evidence fails safely. Source redirects still preserve late links.+>+> The acceptance example and tasks 1–4 cover schema defaults, offline edits, arrival order, torn copies and archive preservation. This reuses existing conflict machinery without introducing another entity or sync engine.+>+> No remaining architecture blocker. Default learning remains the existing product recommendation for the user’s review. No builds, tests or edits performed.++## Synthesis and review-ready verdict++Consensus: every same-page chapter creation path needs protected identity; correction evidence must not reverse a reader's choice; ambiguous labels need selection; source links and late authored changes must survive combination and sync. Both peers validate the critic's consequential findings. No conflicting peer recommendations remain.++The first peer added raw-only link preservation; the second added late-authored-content preservation. Both are adopted because they protect existing reader data with the same repository conflict machinery. A separate Chapter/Note hierarchy, site-wide defaults and a confidence service remain out of scope; the second peer explicitly found the Entry/source design proportionate.++Verdict: review-ready specification, not approved or implemented. No remaining technical review blocker was found. Immediate learning of the multiple-chapters default after a deliberate second-chapter save is still the one product recommendation for the reader to approve or change. User phase review follows these completed critic/peer steps; no approval request was inserted before running them.++Validation: Rune renders 14 pending tasks in seven adjacent red/green pairs, one stream and an acyclic dependency chain. All 22 numbered acceptance criteria have task references. Documentation checks cover links/anchors and whitespace while allowing the requirements skill's Markdown line-break spaces. No application tests or builds ran.
diff --git a/specs/url-optional-chapter-notes/tasks.md b/specs/url-optional-chapter-notes/tasks.mdnew file mode 100644index 00000000..27e47174--- /dev/null+++ b/specs/url-optional-chapter-notes/tasks.md@@ -0,0 +1,115 @@+---+references:+ - specs/url-optional-chapter-notes/requirements.md+ - specs/url-optional-chapter-notes/design.md+ - specs/url-optional-chapter-notes/decision_log.md+metadata:+ status: approved+---+# T-2416 implementation tasks — approved++- [x] 1. Write recorded-store and model contract tests for additive capture metadata migration <!-- id:3ioqj3s -->+ - Seed populated V19 store, release frozen container before live open; assert raw nil/default fields, UUIDs, evidence, citations, statuses and timestamps remain.+ - ModelContractTests: optional/defaulted Entry target/redirect and Work default; EntrySource has no relationships/uniqueness; preserve reachable V16–19 path.+ - Assert optional mergeResolutionData baseline column in the additive model delta and recorded-store raw defaults.+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1)++- [x] 2. Implement the schema and marker transition to pass migration tests <!-- id:3ioqj3t -->+ - Models.swift/AsterismSchemaV19.swift: freeze actual live shape, add next live version and lightweight stage; Bootstrap markers and schema registries together.+ - Do not retire reachable stages absent population proof; never move fixed store/lock paths or run a live conversion.+ - Include mergeResolutionData in schema freeze/delta, using optional Codable Data with no migration backfill.+ - Blocked-by: 3ioqj3s (Write recorded-store and model contract tests for additive capture metadata migration)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1)++- [x] 3. Write identity, source convergence and correction integration tests <!-- id:3ioqj3u -->+ - Test same-URL distinct chapters in every create path, two untitled URL-free notes, same UUID convergence, generated source/arrival permutations.+ - Test failed-save re-fault, retained explicit loser redirects, late source arrivals, cycles/conflicts, work merge/move/delete and generic-note correction.+ - Include raw-only loser URL A and survivor URL B; combination, reopen and backup restore retain both sources.+ - Late offline loser note/rating edits after a resolved combine remain visible as conflicts; vary arrival order, missing baseline and torn copies; archive round trip must not hide them.+ - Blocked-by: 3ioqj3t (Implement the schema and marker transition to pass migration tests)+ - Stream: 1+ - Requirements: [2.2](requirements.md#2.2), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [5.2](requirements.md#5.2)++- [x] 4. Implement authored targets, source ownership and durable correction redirects <!-- id:3ioqj3v -->+ - GroupOrdering/Groups/LibraryValidator/DuplicateScan/Reconciler/Resolution/Redirect: explicit UUID basis, authored target/default fields and redirect handling.+ - New EntrySource model/helpers in Core: source evidence and supersession blob, deterministic source dedupe integrated into repository reconcile; orphan tolerance, cascades, counts, rollback/empty-library registries.+ - Reparse/ComposedTeaching preserve authored correction; source-bearing or explicit losers retain redirect rows after resolved logical combination.+ - Persist accepted loser authored-content baseline on combination; mismatch shows Changes after combine, preserves both contents and disables automatic chapter targeting until renewed review.+ - Blocked-by: 3ioqj3u (Write identity, source convergence and correction integration tests)+ - Stream: 1+ - Requirements: [2.2](requirements.md#2.2), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [5.2](requirements.md#5.2)++- [x] 5. Write chapter resolver and commit-race tests for mixed page layouts <!-- id:3ioqj3w -->+ - Extend RepositoryCaptureTests, ComposedCaptureTests, LogicalRecordCaptureTests and new ChapterCaptureResolverTests: evidence provenance, title-only v1, exact designation, conflicting v2/v3, corrections and incomparable site-wide positions.+ - PendingCaptureDrainTests: selection-required capture set aside, replay idempotence; save races retain draft; ordinary saved/new URL defaults and automatic learned-default atomicity.+ - Blocked-by: 3ioqj3v (Implement authored targets, source ownership and durable correction redirects)+ - Stream: 1+ - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.6](requirements.md#4.6)++- [x] 6. Implement work-scoped chapter resolver and capture commit intent <!-- id:3ioqj3x -->+ - LibraryRepository+Capture/ReparseCapture, Contracts/OutcomeComputation, LibraryProviding and RepositoryDrafts: new read-only resolver, target choice and commit recheck.+ - No placement-as-identity or guessed confidence; protect every detected/explicit same-page chapter; existing selection confirmed before new chapter in ambiguous layouts.+ - PendingCaptureDrain/Settings review and add-page intent reuse revised lookup; extension remains web-only and migration/reconcile-free.+ - Blocked-by: 3ioqj3w (Write chapter resolver and commit-race tests for mixed page layouts)+ - Stream: 1+ - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.6](requirements.md#4.6)++- [x] 7. Write backup import/export and unlinked notes export tests <!-- id:3ioqj3y -->+ - New-format round trip with URL-free rating-only entries, source associations, corrections/redirects and ordinary/multiple defaults; restore current 18/19 archive with no fabricated facts.+ - Generated ordering/idempotence cases plus stale/newer local authored data, torn group and unresolved redirect refusal; MarkdownExport plain Note headings and deterministic primary/all source links.+ - Blocked-by: 3ioqj3x (Implement work-scoped chapter resolver and capture commit intent)+ - Stream: 1+ - Requirements: [2.4](requirements.md#2.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)++- [x] 8. Implement new archive records, predecessor conversion and notes formatting <!-- id:3ioqj3z -->+ - BackupV18 successors, projection/builders/reference checks/exporter/codec/import/confirm-import: proposed archive 19/20 with bounded 18/19 conversion only.+ - All new fields/table records and durable redirects included in wire format and non-regressing UUID upsert. Unknown values refused on export.+ - MarkdownExport/selected-day/work exports: unlinked absent URLs; preserve note/rating inclusion rules and source URLs verbatim.+ - Blocked-by: 3ioqj3y (Write backup import/export and unlinked notes export tests)+ - Stream: 1+ - Requirements: [2.4](requirements.md#2.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)++- [x] 9. Write URL-free work and manual entry repository tests <!-- id:3ioqj40 -->+ - Work create with no membership, each ordinary type/status, later source/purchase URL and membership; malformed nonblank links refused with draft retained.+ - Manual note with absent title/URL, rating-only, explicitly chosen chapter and generic note; cancellation writes nothing; Today/Stats/search/extraction/catch-up consumers honour kind and existing inclusion rules.+ - Blocked-by: 3ioqj3z (Implement new archive records, predecessor conversion and notes formatting)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [4.1](requirements.md#4.1), [4.6](requirements.md#4.6)++- [x] 10. Implement site-free work creation and manual entry repository operations <!-- id:3ioqj41 -->+ - LibraryRepository.swift/NewWorkDraft: blank site allowed without Site; optional source/purchase link maintained through WorkURL membership flow.+ - Dedicated Core manual-entry projection/commit accepts note or rating; blank title allowed; explicit Chapter/Note and optional source. WorkMetadataDraft includes capture default; one Save boundary.+ - WorkDetail/Today/Stats/search/ShareWorkContext snapshots and extraction use effective authored labels; generic notes excluded from chapter progress; manual capture retains applicable to-read promotion.+ - Blocked-by: 3ioqj40 (Write URL-free work and manual entry repository tests)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [4.1](requirements.md#4.1), [4.6](requirements.md#4.6)++- [-] 11. Write focused capture view-model and share-surface tests <!-- id:3ioqj42 -->+ - CaptureStateTests/LookupFirstCaptureStateTests/ShareCaptureFlowTests and focused app integration: clear detection hides extra-chapter action, correction preserves draft; re-share also projects evidence.+ - Add narrow simulator UI journeys for ordinary, whole-work and tthfanfic.org-style switches, default reset, selected existing chapter and failed save. Declare expected identifiers/counts; no full development UI run.+ - Blocked-by: 3ioqj41 (Implement site-free work creation and manual entry repository operations)+ - Stream: 1+ - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [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)++- [x] 12. Implement shared chapter selection, correction and work-default controls <!-- id:3ioqj43 -->+ - CaptureViewModel/LookupCaptureViewModel, extension CaptureView/ReShareCaptureView/ShareCaptureSession: target picker and draft-preserving correction on both branches.+ - WorkDetailModel/View: Pages usually contain picker staged with existing metadata Save; sheet explains automatic learning only when deliberate same-page save will teach it.+ - Blocked-by: 3ioqj42 (Write focused capture view-model and share-surface tests)+ - Stream: 1+ - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [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)++- [-] 13. Write manual entry forms and presentation integration tests <!-- id:3ioqj44 -->+ - NewWorkFormModel and new manual-entry form model: optional site/title/URL, note-or-rating validation, Choose existing chapter, untouched saved state on Cancel and retained draft on failure.+ - Targeted Works/EntryDetail/Today rendered journeys: untitled notes, rating-only, URL-free work later linked to Amazon, saved correction conflicts and supported phone/iPad/Mac form presentation.+ - Blocked-by: 3ioqj43 (Implement shared chapter selection, correction and work-default controls)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6)++- [x] 14. Implement manual capture and saved correction forms <!-- id:3ioqj45 -->+ - NewWorkView/FormModel optional site label; WorkDetail Add note, new value-draft manual capture form following existing checkmark/cancel/rating toggles.+ - EntryDetailModel/View: authored label/kind correction and Use existing chapter content review; do not write before Save or load over refused drafts.+ - Blocked-by: 3ioqj44 (Write manual entry forms and presentation integration tests)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6)
Host/simulator fixtures do not certify live CloudKit delivery. The approved rollout plan requires a preserved archive and coordinated upgrade of all writing app/extension installations; old writers cannot enforce authored identity. No Personal app install, launch, real-library mutation or merge was performed.
The JUnit file comes from the required unfiltered Makefile Core gate using a private scratch/helper path. Its provenance records the actual pre-commit dirty snapshot. Native and UI outcomes are stated separately. The generic ecosystem detector misses the nested Package.swift; no coverage or forge baseline was collected.
Repository and Capture/Lookup view-model checks cover ordinary, whole-page and mixed-layout behavior. They do not render the incoming extension. Mac compilation certifies the app and embedded extension build, not form presentation. Tasks 11/13 retain these uncompleted rendered subparts.