Rebased onto merged PR105/main fba443e9. Current reviewed fixes and all historical acceptance limits retained.
Optional-read notice survives empty and partial series offers without invalidating membership Save.
Series availability reads skip destination/later members and retain complete predecessor ordering evidence.
Choice labels include visible Voice Control titles; two exact UI selectors updated without assertion changes.
Unchanged inherited cover adapter moved into the existing platform seam; no allowlist widening.
Four delta reviewers clean; existing warnings arise from unchanged installed-source files. Transit full-read timeouts prevented guarded checkpoint mutation.
Source reviewed; qualified draft
Core3875 declarations/native1756 declarations (1832 invocations) pass, the456 fast identifiers reconcile, all17 selected phone identities pass across the preserved15-pass/2-failure run and exact2-case rerun, and focused iPad5 passes. All historical full-phone failures/skips/interrupted evidence remain explicit; there is no green full-phone gate. No merge or new physical install. Follow-up UI/UX IdeaT2451 is separate.
45242dbaf75e3735d78acc529be0ef127a445f39 Rebased reviewed PR107 + offer notice/accessibility/platform seam fixes Choose names and places, review the destination, then explicitly copy. A cancelled review changes no records. After adding a book to a series, a suggested earlier book opens the same review with nothing selected.
Immutable previews and planned UUIDs feed one locked mixed-kind transaction. App value drafts retain stale/refused selections. Typed membership receipts feed a save-local coordinator only after full editor success.
Whole-ID sibling checks protect owner/key consistency; payload-only stale bases exclude facts. Exact planned identities distinguish uncertain outcomes without automatic retry. Partial-save membership basis preserves confirmed nil; generation guards and presentation revalidation retire stale offers. No persisted history or schema addition.
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swift
Why it matters. One revalidated transaction creates both kinds without modifying source records or work metadata.
What to look at. commitRecordCopy; inspectRecordCopyOutcome
Asterism/Asterism/ViewModels/RecordCopyFlow.swift
Why it matters. Manual copying and post-save offers share one sheet and ordinary copy session.
What to look at. RecordCopyFlow; RecordCopyOfferCoordinator
Asterism/Asterism/ViewModels/WorkDetailModel.swift
Why it matters. Only confirmed joins offer review; partial editor failures retain intent until success.
What to look at. rememberRecordCopyTransition; commitEditing
Asterism/Asterism/ViewModels/RecordCopyReviewHostState.swift
Why it matters. Phone/wide layouts can return from Check Library with selections and planned IDs intact.
What to look at. resume; discard; originating typed diagnostics route
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| minor | optional offers | Read failure explanation was cleared during retire/selection | Separate coordinator notice shown in hosts/sheet; two regression declarations |
| minor | series offer efficiency | Record reads included destination and future members | Count only strictly preceding members; retain order evidence |
| minor | Voice Control | Accessibility label omitted visible action title | Include visible title and selected trait; correct two exact test selectors preserving assertions |
| major | inherited platform seam | Main PR105 adapter violated unchanged seam guard | Relocate unchanged body to existing PlatformModifiers; assertions unchanged; full Core passes |
| minor | notice lifetime | Prior-event notice clears when next deferred Save event is admitted | Current event-scoped policy; cross-event notice history is unspecified. Retained nonblocking follow-up. |
| minor | offer accessibility | Offer choices expose selection in labels without selected trait | Reasonable nonblocking polish; labels convey state. Retained, not represented as fixed. |
| minor | earlier-member reads | Availability reads still include all preceding members | Further nearest-bucket optimisation deferred; no performance budget failure or measurement established. |
| minor | import order | Foundation import differs from existing order | Cosmetic; no required source change. |
Source: local run at 2026-10-13T09:18:05.086597+00:00 · snapshot 45242dbaf75e3735d78acc529be0ef127a445f39
Baseline: none
Execution: failed (partial results) · JUnit: 10 files · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 7721 passed · 5 failed · 58 skipped · 0 errored · 0 flaky
| Suite | Test | Job or artifact | Message |
|---|---|---|---|
| AsterismUITests/WorkRecordCopyUITests | testInformationalOverlapWithSkippedPeerDoesNotRequireKeepSeparate | — | Failed |
| AsterismUITests/WorkRecordCopyUITests | testRepeatedCopyDefaultsSkipAndRequiresKeepSeparateWarning | — | Failed |
| AccessibilityJourneyUITests | testTheSeriesAndLinkControlsStayReachableAtLargestDynamicType() [execution 12] | — | Observed All Works accessibility reachability failure before copying |
| CharacterExtractionUITests | testACitationInTheFactGutterOpensTheCitedNote() [run timed-out phone continuation] | — | Original raw XCTest execution failed; preserved log assertion kept alias is a chip beside the name |
| CharacterExtractionUITests | testACitationInTheFactGutterOpensTheCitedNote() [run asterism-t2439-final-phone-tail-retry] | — | Original xcresult Failed; see preserved bundle and raw log |
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 bdbae0d5afc94ee61c1a073375107311fbbcbc07.
65 files: 46 code · 19 docs. Click to expand.
diff --git a/Asterism/Asterism/Layout/AppNavigation.swift b/Asterism/Asterism/Layout/AppNavigation.swiftindex 772e997d..1d62e5b5 100644--- a/Asterism/Asterism/Layout/AppNavigation.swift+++ b/Asterism/Asterism/Layout/AppNavigation.swift@@ -137,6 +137,7 @@ final class AppNavigation { private var hasLibraryDestination = false var selectedSidebarItem: SidebarItem = .today { didSet {+ if selectedSidebarItem.tab != oldValue.tab { discardCopyReviewHosts() } if case .library(let destination) = selectedSidebarItem { lastLibraryDestination = destination } if selectedSidebarItem != oldValue { noteReaderNavigation() } }@@ -224,6 +225,7 @@ final class AppNavigation { var todayPath: [WorksRoute] = [] { didSet { if todayPath.isEmpty { todayFocusedEntryID = nil }+ validateCopyReviewHost(on: .today) if todayPath != oldValue { noteReaderNavigation() } } }@@ -255,7 +257,7 @@ final class AppNavigation { /// here rather than in either tree, Req 2.3's layout crossing preserves a /// series screen exactly as it preserves a work. var worksPath: [WorksRoute] = [] {- didSet { if worksPath != oldValue { noteReaderNavigation() } }+ didSet { validateCopyReviewHost(on: .works); if worksPath != oldValue { noteReaderNavigation() } } } /// Which work the Works tab is *about* — the last `.work` on the path.@@ -289,7 +291,7 @@ final class AppNavigation { switch worksPath.last { case .work(let workID): workID case .chapter: selectedWorkID- case .destination, .series, .seriesList, .creator, .creatorList, .none: nil+ case .destination, .series, .seriesList, .creator, .creatorList, .diagnostics, .none: nil } } @@ -657,6 +659,35 @@ final class AppNavigation { append(.seriesList, on: .works) } + /// A copy correction returns to its originating Work on this same stack.+ /// Today's legacy dashboard flag is not a route from Library.+ func showCheckLibrary(on stack: RouteStack) {+ guard path(on: stack).last != .diagnostics else { return }+ append(.diagnostics, on: stack)+ }++ @ObservationIgnored private var copyReviewHosts: [RouteStack: RecordCopyReviewHostState] = [:]+ func recordCopyReviewHost(for workID: UUID, on stack: RouteStack) -> RecordCopyReviewHostState {+ recordCopyReviewHost(for: .work(workID), on: stack)+ }+ func recordCopyReviewHost(for route: WorksRoute, on stack: RouteStack) -> RecordCopyReviewHostState {+ if let host = copyReviewHosts[stack], host.route == route { return host }+ copyReviewHosts[stack]?.discard()+ let host = RecordCopyReviewHostState(route: route)+ copyReviewHosts[stack] = host+ return host+ }+ private func validateCopyReviewHost(on stack: RouteStack) {+ guard let host = copyReviewHosts[stack] else { return }+ let top = path(on: stack).last+ let returning = top == host.route+ let correcting = host.isVisitingResolution && top == .diagnostics && path(on: stack).dropLast().last == host.route+ if !returning && !correcting { host.discard() }+ }+ private func discardCopyReviewHosts() {+ for host in copyReviewHosts.values { host.discard() }+ }+ /// The creator screen, carrying the work it was opened from where there is /// one — `work-creators` Req 4.3's "Current work" marker is that field and /// nothing else. `showSeries`' shape, for its reason: a creator screen and a@@ -1138,6 +1169,7 @@ nonisolated struct IntentRoute: Equatable, Sendable { /// isolation and a main-actor `Hashable` conformance is rejected outright — and /// `NavigationStack(path:)` needs `Hashable` from any context. nonisolated enum WorksRoute: Hashable, Sendable, Codable {+ case diagnostics case work(UUID) /// An entry opened from a work's chapter list. Only ever after a `.work`. case chapter(entryID: UUID)
diff --git a/Asterism/Asterism/Layout/AppScreens.swift b/Asterism/Asterism/Layout/AppScreens.swiftindex 9deac48f..897f617f 100644--- a/Asterism/Asterism/Layout/AppScreens.swift+++ b/Asterism/Asterism/Layout/AppScreens.swift@@ -178,6 +178,8 @@ struct AppScreens { creatorList(on: stack) case .creator(let creatorID, let originWorkID): creator(creatorID, origin: originWorkID, on: stack)+ case .diagnostics:+ diagnostics(on: stack) } } @@ -286,12 +288,14 @@ struct AppScreens { WorkDetailView( model: detailModel, focusedEntryID: stack == .today ? navigation.todayFocusedEntryID : nil,+ copyReviewHost: navigation.recordCopyReviewHost(for: workID, on: stack), currentDay: model.currentDay, calendar: model.calendar, lastSavedLatestWorkID: navigation.lastSavedLatestWorkID, latestSaveGeneration: navigation.latestSaveGeneration, onResolveDuplicate: navigation.resolveRoute( for: workID, type: .work, workload: { model.todayPresentation.duplicateWorkload }),+ onCheckLibrary: { navigation.showCheckLibrary(on: stack) }, onSelectEntry: { navigation.showChapter($0, on: stack) }, onSetLatest: { navigation.presentedSetLatest = SetLatestRoute(workID: $0) }, // Req 4.6: the merge deleted the Work this route is showing, so@@ -359,6 +363,8 @@ struct AppScreens { if let detailModel = model.seriesDetailModel(for: seriesID, originWorkID: origin) { SeriesDetailView( model: detailModel,+ copyReviewHost: navigation.recordCopyReviewHost(for: .series(id: seriesID, originWorkID: origin), on: stack),+ onCheckLibrary: { navigation.showCheckLibrary(on: stack) }, snapshotGeneration: model.snapshotGeneration, showsSky: showsSky, // Q49: a member row **pushes**, so Back returns to the series@@ -427,7 +433,7 @@ struct AppScreens { /// long as the reader stays on the listing — which is exactly where they /// resolve the sets that re-derive it. @ViewBuilder- func diagnostics() -> some View {+ func diagnostics(on stack: RouteStack = .works) -> some View { if let diagnosticsModel = model.libraryDiagnosticsModel( onReteach: { hostname in navigation.showingTeachingForHostname = PendingReteach(hostname: hostname)@@ -436,7 +442,7 @@ struct AppScreens { // T-2289: the Works tab's own push, which carries every route a Work // can need — the merge-blocked sheet deliberately has none, and a // Work opened from here may itself be torn.- onOpenWork: { navigation.showWork($0) }+ onOpenWork: { navigation.showWork($0, on: stack) } ) { LibraryDiagnosticsView(model: diagnosticsModel, showsSky: showsSky) }
diff --git a/Asterism/Asterism/Layout/WideRootView.swift b/Asterism/Asterism/Layout/WideRootView.swiftindex 0da71b15..3129523d 100644--- a/Asterism/Asterism/Layout/WideRootView.swift+++ b/Asterism/Asterism/Layout/WideRootView.swift@@ -451,6 +451,8 @@ struct WideRootView: View { return "Creators" case .creator: return "Creator"+ case .diagnostics:+ return "Check Library" case .chapter, .none: // A chapter is never underneath anything — it is dropped before a // route is appended — and nothing underneath at all means the route@@ -496,6 +498,8 @@ struct WideRootView: View { // The creator screen names itself in its navigation title, from the // name the read resolved; the route carries an identifier alone. return "Creator"+ case .diagnostics:+ return "Check Library" case .none: switch stack { case .works: return entryTitle(navigation.selectedWorksEntryID)
diff --git a/Asterism/Asterism/Support/PlatformModifiers.swift b/Asterism/Asterism/Support/PlatformModifiers.swiftindex 5091c5d7..4b2983db 100644--- a/Asterism/Asterism/Support/PlatformModifiers.swift+++ b/Asterism/Asterism/Support/PlatformModifiers.swift@@ -1,3 +1,4 @@+import Foundation import AsterismPresentation import AsterismCore import ConstellationKit@@ -941,3 +942,110 @@ extension View { #endif } }++// MARK: - Cover drop platform adapter++/// Keep the Cover field's layout and Menu. Native iOS List hosting does not+/// route SwiftUI's nested onDrop; use a native interaction over this field.+struct CoverDropTarget: ViewModifier {+ let canAccept: Bool+ @Binding var isTargeted: Bool+ let accept: ([NSItemProvider]) -> Bool++ func body(content: Content) -> some View {+ #if os(iOS)+ content.overlay {+ CoverDropAdapter(canAccept: canAccept, isTargeted: $isTargeted, accept: accept)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .accessibilityHidden(true)+ }+ #else+ content.onDrop(of: WorkDetailModel.coverDropTypes, isTargeted: $isTargeted, perform: accept)+ #endif+ }+}++#if os(iOS)+private struct CoverDropAdapter: UIViewRepresentable {+ let canAccept: Bool+ @Binding var isTargeted: Bool+ let accept: ([NSItemProvider]) -> Bool++ func makeUIView(context: Context) -> CoverDropSurface {+ CoverDropSurface(frame: .zero)+ }++ func updateUIView(_ view: CoverDropSurface, context: Context) {+ view.canAccept = canAccept+ view.updateTarget = { isTargeted = $0 }+ view.accept = accept+ }+}++final class CoverDropSurface: UIView, UIDropInteractionDelegate {+ var canAccept = false+ var updateTarget: (Bool) -> Void = { _ in }+ var accept: ([NSItemProvider]) -> Bool = { _ in false }+ private var targeted = false++ override init(frame: CGRect) {+ super.init(frame: frame)+ backgroundColor = .clear+ accessibilityElementsHidden = true+ addInteraction(UIDropInteraction(delegate: self))+ }++ @available(*, unavailable)+ required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }++ // Preserve the Menu's ordinary input; let UIKit hit-test its interaction+ // events (including native drag targeting) against this drop surface.+ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {+ if let event {+ switch event.type {+ case .touches, .motion, .remoteControl, .presses, .scroll, .hover, .transform:+ return nil+ @unknown default:+ break+ }+ }+ return super.hitTest(point, with: event)+ }++ private func setTargeted(_ value: Bool) {+ guard targeted != value else { return }+ targeted = value+ updateTarget(value)+ }++ private func canHandle(_ session: UIDropSession) -> Bool {+ canAccept && session.items.contains {+ WorkDetailModel.hasCoverDropRepresentation($0.itemProvider)+ }+ }++ func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {+ canHandle(session)+ }++ func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {+ let accepts = canHandle(session) && bounds.contains(session.location(in: self))+ setTargeted(accepts)+ return UIDropProposal(operation: accepts ? .copy : .forbidden)+ }++ func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {+ defer { setTargeted(false) }+ guard canHandle(session), bounds.contains(session.location(in: self)) else { return }+ _ = accept(session.items.map(\.itemProvider))+ }++ func dropInteraction(_ interaction: UIDropInteraction, sessionDidExit session: UIDropSession) {+ setTargeted(false)+ }++ func dropInteraction(_ interaction: UIDropInteraction, sessionDidEnd session: UIDropSession) {+ setTargeted(false)+ }+}+#endif
diff --git a/Asterism/Asterism/UITestLaunchSupport.swift b/Asterism/Asterism/UITestLaunchSupport.swiftindex 2d487a14..5fc4336e 100644--- a/Asterism/Asterism/UITestLaunchSupport.swift+++ b/Asterism/Asterism/UITestLaunchSupport.swift@@ -77,6 +77,7 @@ enum UITestFixtureKind: Equatable { /// row holds and a link to a work no row holds. `seeded-works-options` is /// left alone: its suites assert exact orders that a sixth work would move. case series+ case recordCopy /// A small legal library the creators list, the creator screen, the credits /// section and editor, the creator filter and the roles settings have /// something to say about (`work-creators`): four works, three creators —@@ -169,6 +170,7 @@ enum UITestLaunchSupport { static let seededHiatusHistoryScenario = "seeded-hiatus-history" /// The five works, three series and two links the series journeys run over. static let seededSeriesScenario = "seeded-series"+ static let seededRecordCopyScenario = "seeded-record-copy" /// The four works, three creators, five roles and six credits the creator /// journeys run over. static let seededCreatorsScenario = "seeded-creators"@@ -455,6 +457,8 @@ enum UITestLaunchSupport { fixture = .hiatusHistory case seededSeriesScenario: fixture = .series+ case seededRecordCopyScenario:+ fixture = .recordCopy case seededCreatorsScenario: fixture = .creators case seededCoveredWorkScenario:
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex cd1ffb72..a7cfd48a 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -3731,6 +3731,55 @@ public final class AppLibraryModel { Self.logger.debug("Seeded the series UI test fixture") } + /// Isolated copy fixtures use only ordinary repository writes. URL-free+ /// books carry no imported contents; the one unrelated capture populates+ /// the landing list without changing these works' source links.+ private func seedRecordCopyFixture(in repo: LibraryRepository) async throws {+ _ = try await repo.capture(CaptureDraft(captureTitle: "Fixture note", captureTitleSource: .host,+ rawURLString: "https://copy-fixture.test/note"))+ let series = try await repo.createSeries(name: "Copy cycle", notes: "")+ let ties = try await repo.createSeries(name: "Tied cycle", notes: "")+ let offers = try await repo.createSeries(name: "Offer cycle", notes: "")+ var ids: [String: UUID] = [:]+ for (title, membership) in [+ ("Book one", SeriesMembership(seriesID: series, position: 1)),+ ("Book two", SeriesMembership(seriesID: series, position: 2)),+ ("Book three", nil), ("Book four", nil),+ ("Tied source", SeriesMembership(seriesID: ties, position: 1)),+ ("Empty tied peer", SeriesMembership(seriesID: ties, position: 1)),+ ("Tied addition", nil),+ ("Offer source", SeriesMembership(seriesID: offers, position: 1)),+ ("Offer addition", nil), ("Offer second addition", nil)+ ] as [(String, SeriesMembership?)] {+ let work = try await repo.createWork(.init(displayTitle: title, hostname: ""))+ ids[title] = work.id+ _ = try await repo.updateWork(id: work.id, basis: WorkEditBasis(work: work),+ draft: WorkMetadataDraft(displayTitle: title, typeAssignment: work.typeDisplay.assignment,+ genreTags: [], genericNotes: "Ada keeps the lighthouse.", publicationEdit: .unchanged,+ readingStatus: work.readingStatus, verdict: "", releaseDays: work.releaseDays,+ membership: membership, thumbnail: .keep), calendar: calendar)+ }+ for title in ["Book one", "Tied source", "Offer source"] {+ guard let id = ids[title] else { continue }+ _ = try await repo.commitRecordEdits(workID: id, operations: [+ .create(.init(kind: .character, name: "Ada", note: "A secret", aliases: ["Nightjar"],+ facts: [.init(statement: "Keeps the lighthouse", quote: "Ada keeps the lighthouse.", nameKey: "ada", source: .genericNotes)])),+ .create(.init(kind: .place, name: "Harbour", note: "A setting")),+ .create(.init(kind: .character, name: "Nightjar", note: "A different person"))+ ])+ }+ // A staged addition has its own records: the next newly added member+ // remains the nearest predecessor without copying anything automatically.+ if let id = ids["Offer addition"] {+ _ = try await repo.commitRecordEdits(workID: id, operations: [+ .create(.init(kind: .character, name: "Reader", note: "An existing addition record"))+ ])+ }+ if let first = ids["Book one"], let second = ids["Book two"] {+ _ = try await repo.addLink(between: first, and: second, type: "sequel")+ }+ }+ /// One work of that fixture: a capture, a work on the same site, the move /// that puts one under the other, and the membership the series screens read. ///@@ -4060,6 +4109,10 @@ public final class AppLibraryModel { try await seedSeriesFixture(in: repository) return }+ if fixture == .recordCopy {+ try await seedRecordCopyFixture(in: repository)+ return+ } if fixture == .creators { try await seedCreatorsFixture(in: repository)
diff --git a/Asterism/Asterism/ViewModels/RecordCopyFlow.swift b/Asterism/Asterism/ViewModels/RecordCopyFlow.swiftnew file mode 100644index 00000000..a1c90aa0--- /dev/null+++ b/Asterism/Asterism/ViewModels/RecordCopyFlow.swift@@ -0,0 +1,26 @@+import Foundation++/// One presentation owner for manual copying and a confirmed-save review.+@MainActor+enum RecordCopyFlow: Identifiable {+ case manual(WorkRecordCopyModel)+ case offered(RecordCopyOfferCoordinator)+ var id: String {+ switch self {+ case .manual(let model): "manual-" + model.id.uuidString+ case .offered(let coordinator): "offer-" + coordinator.id.uuidString+ }+ }+ var copyModel: WorkRecordCopyModel? {+ switch self {+ case .manual(let model): model+ case .offered(let coordinator): coordinator.copyModel+ }+ }+ func close() {+ switch self {+ case .manual(let model): model.close()+ case .offered(let coordinator): coordinator.consume()+ }+ }+}
diff --git a/Asterism/Asterism/ViewModels/RecordCopyOfferCoordinator.swift b/Asterism/Asterism/ViewModels/RecordCopyOfferCoordinator.swiftnew file mode 100644index 00000000..83fd7954--- /dev/null+++ b/Asterism/Asterism/ViewModels/RecordCopyOfferCoordinator.swift@@ -0,0 +1,206 @@+import AsterismCore+import Foundation+import Observation++/// A reader Save creates one local event. Reads and sync never recreate it.+@MainActor @Observable+final class RecordCopyOfferCoordinator: Identifiable {+ let id = UUID()+ private(set) var eventID: UUID?+ private(set) var offers: [RecordCopySeriesOffer] = []+ private(set) var selectedDestinationID: UUID?+ private(set) var selectedSourceID: UUID?+ private(set) var copyModel: WorkRecordCopyModel?+ private(set) var message: String?+ /// A saved membership remains successful when its optional review cannot be read.+ private(set) var offerReadNotice: String?+ private static let offerReadFailureNotice =+ "The work was saved. Copy review is unavailable right now; use Copy characters and places from a work later."+ private(set) var isReading = false+ private let library: any LibraryProviding+ private let onMutation: @Sendable () async -> Void+ private var consumed: Set<UUID> = []+ private var generation = 0+ private struct DeferredEvent {+ let id: UUID+ let transitions: [WorkMembershipTransition]+ }+ private var deferredEvents: [DeferredEvent] = []+ init(library: any LibraryProviding, onMutation: @escaping @Sendable () async -> Void) {+ self.library = library+ self.onMutation = onMutation+ }+ var selectedOffer: RecordCopySeriesOffer? {+ offers.first { $0.destination.id == selectedDestinationID }+ }+ var hasOffer: Bool { !offers.isEmpty && copyModel == nil }+ func enqueue(eventID: UUID, transitions: [WorkMembershipTransition]) async {+ guard !consumed.contains(eventID), self.eventID != eventID,+ !deferredEvents.contains(where: { $0.id == eventID })+ else { return }+ if self.eventID != nil || copyModel != nil || isReading {+ deferredEvents.append(.init(id: eventID, transitions: transitions))+ return+ }+ consume()+ self.eventID = eventID+ generation += 1+ let token = generation+ isReading = true+ message = nil+ offerReadNotice = nil+ var destinations: [UUID: UUID] = [:]+ for transition in transitions where transition.isJoin {+ destinations[transition.resolvedWorkID] = transition.after?.seriesID+ }+ var result: [RecordCopySeriesOffer] = []+ for destination in destinations.keys.sorted(by: { $0.uuidString < $1.uuidString }) {+ guard token == generation else { return }+ do {+ if let seriesID = destinations[destination],+ let offer = try await library.recordCopyOffer(+ destinationWorkID: destination, seriesID: seriesID)+ {+ result.append(offer)+ }+ } catch {+ // The membership is already committed. A failed optional offer+ // does not turn that Save into a failure or undo its membership.+ guard token == generation else { return }+ offerReadNotice = Self.offerReadFailureNotice+ }+ }+ guard token == generation else { return }+ isReading = false+ offers = result+ if result.count == 1 { selectDestination(result[0].destination.id) }+ if result.isEmpty {+ consume()+ await advanceDeferredEvents()+ }+ }+ /// Re-read saved membership after an obstructing editor/picker closes.+ /// A retired host cannot publish the result of this read.+ func prepareForPresentation() async -> Bool {+ guard hasOffer, !isReading else { return false }+ let token = generation+ isReading = true+ var freshOffers: [RecordCopySeriesOffer] = []+ for offer in offers {+ do {+ if let fresh = try await library.recordCopyOffer(+ destinationWorkID: offer.destination.id, seriesID: offer.series.id) {+ freshOffers.append(fresh)+ }+ } catch {+ guard token == generation else { return false }+ offerReadNotice = Self.offerReadFailureNotice+ }+ guard token == generation else { return false }+ }+ isReading = false+ offers = freshOffers+ selectedDestinationID = nil+ selectedSourceID = nil+ if offers.count == 1 { selectDestination(offers[0].destination.id) }+ if offers.isEmpty { consume(); return false }+ return true+ }+ func selectDestination(_ id: UUID) {+ guard !isReading, copyModel == nil, let offer = offers.first(where: { $0.destination.id == id })+ else { return }+ selectedDestinationID = id+ selectedSourceID = offer.requiresSourceChoice ? nil : offer.sources.first?.id+ message = nil+ }+ func selectSource(_ id: UUID) {+ guard !isReading, copyModel == nil,+ selectedOffer?.sources.contains(where: { $0.id == id && $0.unavailableReason == nil }) == true+ else { return }+ selectedSourceID = id+ }+ private struct Signature: Equatable {+ let destination: UUID+ let series: UUID+ let position: Double+ let predecessorPosition: Double+ let bucket: Set<UUID>+ let available: Set<UUID>+ init(_ offer: RecordCopySeriesOffer) {+ destination = offer.destination.id+ series = offer.series.id+ position = offer.basis.destinationPosition+ predecessorPosition = offer.precedingPosition+ bucket = Set(offer.basis.bucket.map { $0.work.id })+ available = Set(offer.sources.map(\.id))+ }+ }+ func review() async {+ guard !isReading, copyModel == nil, let previous = selectedOffer, let source = selectedSourceID+ else { return }+ let token = generation+ isReading = true+ defer { if token == generation { isReading = false } }+ do {+ guard+ let fresh = try await library.recordCopyOffer(+ destinationWorkID: previous.destination.id, seriesID: previous.series.id)+ else {+ guard token == generation else { return }+ offers.removeAll { $0.destination.id == previous.destination.id }+ selectedDestinationID = nil+ selectedSourceID = nil+ message =+ "The saved series order or available records changed. This offer is no longer available."+ return+ }+ guard token == generation else { return }+ guard Signature(fresh) == Signature(previous),+ fresh.sources.contains(where: { $0.id == source })+ else {+ if let index = offers.firstIndex(where: { $0.destination.id == fresh.destination.id }) {+ offers[index] = fresh+ }+ selectedSourceID = fresh.requiresSourceChoice ? nil : fresh.sources.first?.id+ message =+ "The saved series order or source choices changed. Review the updated offer before continuing."+ return+ }+ copyModel = WorkRecordCopyModel(+ sourceWorkID: source, library: library, onMutation: onMutation,+ destinationID: fresh.destination.id)+ } catch {+ guard token == generation else { return }+ message =+ "Could not refresh this saved series offer. Try Review again or close it and use manual copying later."+ }+ }+ func consume() {+ guard copyModel?.isSubmitting != true else { return }+ retireCurrentEvent()+ }+ private func retireCurrentEvent() {+ if let eventID { consumed.insert(eventID) }+ generation += 1+ eventID = nil+ offers = []+ selectedDestinationID = nil+ selectedSourceID = nil+ message = nil+ isReading = false+ copyModel?.close()+ copyModel = nil+ }+ /// The presenter calls this only after its current sheet has fully closed.+ func advanceDeferredEvents() async {+ guard eventID == nil, copyModel == nil, !isReading, !deferredEvents.isEmpty else { return }+ let next = deferredEvents.removeFirst()+ await enqueue(eventID: next.id, transitions: next.transitions)+ }+ func cancelHost() {+ offerReadNotice = nil+ consumed.formUnion(deferredEvents.map(\.id))+ deferredEvents = []+ retireCurrentEvent()+ }+}
diff --git a/Asterism/Asterism/ViewModels/RecordCopyReviewHostState.swift b/Asterism/Asterism/ViewModels/RecordCopyReviewHostState.swiftnew file mode 100644index 00000000..035814a4--- /dev/null+++ b/Asterism/Asterism/ViewModels/RecordCopyReviewHostState.swift@@ -0,0 +1,32 @@+import Foundation+import Observation++/// A transient correction draft survives the wide pane replacing its Work+/// view with Check Library. Navigation owns this, never defaults or the store.+@MainActor @Observable+final class RecordCopyReviewHostState {+ let route: WorksRoute+ var suspendedModel: WorkRecordCopyModel?+ var generation = 0+ var isResuming = false+ var isVisitingResolution = false+ init(sourceRouteID: UUID) { self.route = .work(sourceRouteID) }+ init(route: WorksRoute) { self.route = route }+ func discard() {+ generation += 1+ isResuming = false+ isVisitingResolution = false+ suspendedModel?.discardSuspendedSession()+ suspendedModel = nil+ }+ func resume() async -> WorkRecordCopyModel? {+ guard !isResuming, let model = suspendedModel else { return nil }+ let token = generation+ isResuming = true+ await model.resumeAfterResolution()+ guard token == generation, suspendedModel === model, model.state != .closed else { return nil }+ suspendedModel = nil+ isResuming = false+ return model+ }+}
diff --git a/Asterism/Asterism/ViewModels/SeriesModels.swift b/Asterism/Asterism/ViewModels/SeriesModels.swiftindex 370b5c90..803a09d3 100644--- a/Asterism/Asterism/ViewModels/SeriesModels.swift+++ b/Asterism/Asterism/ViewModels/SeriesModels.swift@@ -266,6 +266,9 @@ public final class SeriesDetailModel { /// export locale. private let locale: Locale private let onMutation: @Sendable () async -> Void+ let recordCopyOffers: RecordCopyOfferCoordinator+ private var recordCopySaveEventID: UUID? = UUID()+ private var recordCopySaveGeneration = 0 private var positionDrafts: [UUID: String] = [:] /// The member whose position the last save refused, if any (Req 2.2). private var refusedPositionRowID: UUID?@@ -283,6 +286,7 @@ public final class SeriesDetailModel { self.library = library self.locale = locale self.onMutation = onMutation+ self.recordCopyOffers = RecordCopyOfferCoordinator(library: library, onMutation: onMutation) } // MARK: - Reading (Reqs 3.1–3.3)@@ -349,6 +353,9 @@ public final class SeriesDetailModel { public func beginEditing() { guard state == .ready else { return }+ recordCopyOffers.consume()+ recordCopySaveGeneration += 1+ recordCopySaveEventID = UUID() message = nil refusedPositionRowID = nil stagedRemovals = []@@ -360,6 +367,7 @@ public final class SeriesDetailModel { } public func cancelEditing() {+ discardRecordCopyOffers() isEditing = false // A refusal belongs to the editing session that earned it: the sentence // under the row's field goes out with the mode, as the mark does.@@ -537,10 +545,14 @@ public final class SeriesDetailModel { return } + let additionIDs = Set(stagedAdditions.map(\.id))+ let offerEvent = recordCopySaveEventID+ let offerGeneration = recordCopySaveGeneration+ var joined: [WorkMembershipTransition] = [] do {- let outcome = try await library.commitSeriesEdits(+ let receipt = try await library.commitSeriesEditsWithMembershipReceipt( seriesID: seriesID, name: draftName, notes: draftNotes, members: edits)- if case .conflict(let conflict) = outcome {+ if case .conflict(let conflict) = receipt.outcome { // Req 2.4's refusal, and nothing was written: the drafts stay // exactly as the reader left them, as they do in the work // editor (Q68 — never a `load()` here, which would reassign@@ -548,6 +560,9 @@ public final class SeriesDetailModel { message = EntryDetailModel.conflictMessage(conflict) return }+ joined = receipt.transitions.filter { transition in+ transition.isJoin && !additionIDs.isDisjoint(with: transition.addressedWorkIDs)+ } } catch { message = SeriesRefusalPresentation.sentence(for: error) Self.logger.error(@@ -559,6 +574,17 @@ public final class SeriesDetailModel { stagedAdditions = [] isEditing = false await committed()+ guard offerGeneration == recordCopySaveGeneration, offerEvent == recordCopySaveEventID else { return }+ recordCopySaveEventID = nil+ if !joined.isEmpty, let offerEvent {+ await recordCopyOffers.enqueue(eventID: offerEvent, transitions: joined)+ }+ }++ func discardRecordCopyOffers() {+ recordCopySaveGeneration += 1+ recordCopySaveEventID = nil+ recordCopyOffers.cancelHost() } // MARK: - Membership (Reqs 2.5, 2.6, 2.8)
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel.swift b/Asterism/Asterism/ViewModels/WorkDetailModel.swiftindex 66def043..060d73d9 100644--- a/Asterism/Asterism/ViewModels/WorkDetailModel.swift+++ b/Asterism/Asterism/ViewModels/WorkDetailModel.swift@@ -2,6 +2,7 @@ import AsterismPresentation import AsterismCore import CoreGraphics import Foundation+import ImageIO import Observation import OSLog import UniformTypeIdentifiers@@ -470,6 +471,10 @@ public final class WorkDetailModel { private let nowSource: @Sendable () -> Date private var calendar: Calendar { calendarSource?() ?? initialCalendar } private let onMutation: @Sendable () async -> Void+ let recordCopyOffers: RecordCopyOfferCoordinator+ private var recordCopySaveEventID: UUID?+ private var recordCopySaveGeneration = 0+ private var pendingRecordCopyJoin: WorkMembershipTransition? /// Where a refused write goes (Req 2.10, Q47): the draft stays here, the /// conflict goes to the model that owns the banner and the listing. private let onConflict: @Sendable (WriteConflict) async -> Void@@ -503,6 +508,7 @@ public final class WorkDetailModel { self.capabilities = capabilities self.coverFetcher = coverFetcher self.onMutation = onMutation+ self.recordCopyOffers = RecordCopyOfferCoordinator(library: library, onMutation: onMutation) self.onConflict = onConflict self.onEditingChange = onEditingChange }@@ -772,8 +778,10 @@ public final class WorkDetailModel { /// offered, so the refusal has somewhere to be said. private var hasUnsavedSeriesChange: Bool { switch seriesDraft {- case .invalidPosition: true- case .membership(let membership): membership != work?.membership+ case .invalidPosition: return true+ case .membership(let membership):+ if let basis = editorWorkBasis { return membership != basis.membership }+ return membership != work?.membership } } @@ -1136,6 +1144,126 @@ public final class WorkDetailModel { thumbnailMessage = nil } + var canAcceptCoverDrop: Bool { isEditing && !isReadOnly && !isSubmitting }+ private var coverDropAdmission = UUID()++ static let coverDropTypes: [UTType] = [.jpeg, .png, .heic, .gif, .webP, .image, .fileURL]++ /// Reject links/text without opening a pick session. Unlike paste, a drop+ /// never follows a remote URL. Actual file bytes stay inside their grant.+ func beginCoverDrop(_ providers: [NSItemProvider]) -> Task<Bool, Never>? {+ guard canAcceptCoverDrop, providers.contains(where: Self.hasCoverDropRepresentation) else { return nil }+ // Capture before scheduling: navigation or a newer pick can retire the+ // request even before its first asynchronous step starts.+ let admissionToken = thumbnailSessionToken+ let admission = UUID()+ coverDropAdmission = admission+ return Task { await acceptDroppedProviders(providers, admissionToken: admissionToken, admission: admission) }+ }++ static func hasCoverDropRepresentation(_ provider: NSItemProvider) -> Bool {+ coverDropTypes.contains { hasCoverDropRepresentation(provider, type: $0) }+ }++ private static func hasCoverDropRepresentation(_ provider: NSItemProvider, type: UTType) -> Bool {+ // A generic advertisement needs decoding; a known unsupported subtype+ // must not retire the current crop merely because it conforms to image.+ if type == .image { return provider.registeredTypeIdentifiers.contains(type.identifier) }+ return provider.hasItemConformingToTypeIdentifier(type.identifier)+ }++ /// Provider order is reader order. Decode before choosing a winner, so an+ /// unreadable representation does not mask a later usable image.+ @discardableResult+ func acceptDroppedProviders(_ providers: [NSItemProvider]) async -> Bool {+ guard canAcceptCoverDrop, providers.contains(where: Self.hasCoverDropRepresentation) else { return false }+ let admission = UUID()+ coverDropAdmission = admission+ return await acceptDroppedProviders(providers, admissionToken: thumbnailSessionToken, admission: admission)+ }++ private func acceptDroppedProviders(_ providers: [NSItemProvider], admissionToken initialToken: UUID, admission: UUID) async -> Bool {+ guard canAcceptCoverDrop, admission == coverDropAdmission, initialToken == thumbnailSessionToken else { return false }+ var token: UUID?+ for provider in providers {+ guard canAcceptCoverDrop, admission == coverDropAdmission,+ thumbnailSessionToken == (token ?? initialToken) else { return token != nil }+ let imageTypes = Self.coverDropTypes.dropLast().filter {+ Self.hasCoverDropRepresentation(provider, type: $0)+ }+ if !imageTypes.isEmpty && token == nil { token = beginThumbnailPick() }+ for type in imageTypes {+ guard canAcceptCoverDrop, admission == coverDropAdmission, token == thumbnailSessionToken else { return token != nil }+ if let data = await imageData(from: provider, typeIdentifier: type.identifier),+ await acceptDroppedImage(data, token: token!, admission: admission) { return true }+ guard canAcceptCoverDrop, admission == coverDropAdmission, token == thumbnailSessionToken else { return true }+ // Consume the provider's temporary image file before returning+ // its callback; a URL retained beyond it is no longer granted.+ let fileData: Data? = await withCheckedContinuation { continuation in+ provider.loadFileRepresentation(forTypeIdentifier: type.identifier) { url, _ in+ continuation.resume(returning: url.flatMap(Self.readDroppedFile))+ }+ }+ if let fileData, await acceptDroppedImage(fileData, token: token!, admission: admission) { return true }+ }+ // A public.url or plain-text web link is intentionally not eligible.+ if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier),+ let url = await droppedFileURL(from: provider), url.isFileURL {+ guard canAcceptCoverDrop, admission == coverDropAdmission,+ thumbnailSessionToken == (token ?? initialToken) else { return token != nil }+ if token == nil { token = beginThumbnailPick() }+ let data = await Task.detached(priority: .userInitiated) {+ Self.readDroppedFile(url)+ }.value+ if let data, await acceptDroppedImage(data, token: token!, admission: admission) { return true }+ }+ }+ guard let token, canAcceptCoverDrop, admission == coverDropAdmission, token == thumbnailSessionToken else { return token != nil }+ thumbnailMessage = ThumbnailSource.file.failureMessage+ return true+ }++ private func acceptDroppedImage(_ data: Data, token: UUID, admission: UUID) async -> Bool {+ guard canAcceptCoverDrop, admission == coverDropAdmission, token == thumbnailSessionToken else { return false }+ let decoded = await Task.detached(priority: .userInitiated) {+ guard let source = CGImageSourceCreateWithData(data as CFData, nil),+ let identifier = CGImageSourceGetType(source), let type = UTType(identifier as String),+ [UTType.jpeg, .png, .heic, .gif, .webP].contains(where: { type.conforms(to: $0) }) else { return Optional<DecodedThumbnail>.none }+ return ThumbnailCodec.workingImage(from: data).map(DecodedThumbnail.init)+ }.value+ guard canAcceptCoverDrop, admission == coverDropAdmission, token == thumbnailSessionToken, let decoded else { return false }+ thumbnailMessage = nil+ pendingCrop = ThumbnailCropSource(id: token, image: decoded.image)+ return true+ }++ nonisolated private static func readDroppedFile(_ url: URL) -> Data? {+ guard url.isFileURL else { return nil }+ let scoped = url.startAccessingSecurityScopedResource()+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }+ return try? Data(contentsOf: url)+ }++ private func droppedFileURL(from provider: NSItemProvider) async -> URL? {+ await withCheckedContinuation { continuation in+ provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier) { item, _ in+ switch item {+ case let url as URL: continuation.resume(returning: url)+ case let data as Data: continuation.resume(returning: URL(dataRepresentation: data, relativeTo: nil))+ case let text as String: continuation.resume(returning: URL(string: text))+ default: continuation.resume(returning: nil)+ }+ }+ }+ }++ /// A pushed-away editor can still be editing in memory. Retire the session+ /// explicitly so a delayed provider cannot present a crop on return.+ func retireThumbnailPresentation() {+ cancelCoverFetch()+ cancelThumbnailPick()+ }+ /// Req 3.3's paste, as `PasteButton` delivers it. /// /// The first payload that carries image bytes wins and goes to the crop@@ -2048,6 +2176,14 @@ public final class WorkDetailModel { ) } + /// The loaded projection may resolve a redirected address to a survivor.+ /// Start a new explicit copy from that saved identity, never the old route.+ public func recordCopyModel(destinationID: UUID? = nil) -> WorkRecordCopyModel? {+ guard let work, !isEditing else { return nil }+ return WorkRecordCopyModel(sourceWorkID: work.id, library: library,+ onMutation: onMutation, destinationID: destinationID)+ }+ /// Whether the *metadata* drafts differ from the loaded snapshot. The URL /// field has its own check (`hasUnsavedWorkURLChange`) because it commits /// through its own contract, not through `updateWork`.@@ -2106,6 +2242,10 @@ public final class WorkDetailModel { /// repository would refuse the write, and the notice already says so. public func beginEditing() { guard state == .ready, !isReadOnly else { return }+ recordCopyOffers.consume()+ recordCopySaveGeneration += 1+ recordCopySaveEventID = UUID()+ pendingRecordCopyJoin = nil clearLastRefusal() // `work-thumbnails` Req 2.1: the Cover field opens on what the work // holds. Seeded here as well as at the load, because the load is what@@ -2142,6 +2282,7 @@ public final class WorkDetailModel { /// a draft like any other, so a cancel puts back what the last projection /// gave the field. public func cancelEditing() {+ discardRecordCopyOffers() // The mode goes first: the X *is* the reader's discard, and // `adoptRecordDrafts` refuses to replace the drafts of a session that // is still open.@@ -2173,6 +2314,8 @@ public final class WorkDetailModel { /// the URL after it would be committing a draft that had just been /// overwritten. public func commitEditing() async {+ let offerEvent = recordCopySaveEventID+ let offerGeneration = recordCopySaveGeneration // Req 3.4, and **first**: ahead of the URL step and every other write, // so a cancel at the dialog leaves every draft exactly as it was (Q37). if let prompt = finishedReadingCommitPrompt() {@@ -2249,6 +2392,53 @@ public final class WorkDetailModel { || (committedURL && !hadMetadataChanges) { await load() }+ guard offerGeneration == recordCopySaveGeneration, offerEvent == recordCopySaveEventID else { return }+ let event = offerEvent+ let join = pendingRecordCopyJoin+ recordCopySaveEventID = nil+ pendingRecordCopyJoin = nil+ if let event, let join {+ await recordCopyOffers.enqueue(eventID: event, transitions: [join])+ }+ }++ /// Navigation/cancel retires intent without undoing a metadata save that+ /// already joined the series before another editor step refused.+ func discardRecordCopyOffers() {+ recordCopySaveGeneration += 1+ recordCopySaveEventID = nil+ pendingRecordCopyJoin = nil+ recordCopyOffers.cancelHost()+ }++ private func rememberRecordCopyTransition(_ receipt: MembershipWriteReceipt, event: UUID?, generation: Int) {+ guard event != nil, event == recordCopySaveEventID, generation == recordCopySaveGeneration else { return }+ for transition in receipt.transitions where transition.addressedWorkIDs.contains(workID)+ || transition.resolvedWorkID == work?.id {+ // Metadata may have committed before a later editor step refused.+ // Advance only its confirmed membership basis; retain the other+ // fields' original conflict protection and all reader drafts.+ if let basis = editorWorkBasis {+ editorWorkBasis = WorkEditBasis(+ displayTitle: basis.displayTitle, typeAssignment: basis.typeAssignment,+ genreTags: basis.genreTags, genericNotes: basis.genericNotes,+ memberships: basis.memberships, lastParsedTitle: basis.lastParsedTitle,+ titleProvenance: basis.titleProvenance, workStatus: basis.workStatus,+ readingStatus: basis.readingStatus, verdict: basis.verdict,+ membership: transition.after, thumbnail: basis.thumbnail,+ releaseDays: basis.releaseDays, publicationStateData: basis.publicationStateData,+ chapterCaptureDefault: basis.chapterCaptureDefault)+ }+ if transition.isJoin {+ pendingRecordCopyJoin = transition+ } else if transition.after == nil {+ pendingRecordCopyJoin = nil+ } else if let pending = pendingRecordCopyJoin,+ pending.resolvedWorkID != transition.resolvedWorkID+ || pending.after?.seriesID != transition.after?.seriesID {+ pendingRecordCopyJoin = nil+ }+ } } private func restoreDraftsFromSnapshot() {@@ -2743,6 +2933,8 @@ public final class WorkDetailModel { /// `workDetail` reads for one confirmation is one too many. private func save(reloading: Bool) async { guard !isSubmitting else { return }+ let offerEvent = recordCopySaveEventID+ let offerGeneration = recordCopySaveGeneration let selectedReturn: CivilDay? switch publicationEdit { case .unchanged: selectedReturn = nil@@ -2769,6 +2961,7 @@ public final class WorkDetailModel { didRefusePosition = false isSubmitting = true state = .submitting+ cancelThumbnailPick() errorMessage = nil do { let draft = WorkMetadataDraft(@@ -2832,9 +3025,9 @@ public final class WorkDetailModel { // with no loaded snapshot, where the toggles are what the // editor showed. releaseDays: ReleaseDay.canonical(draftReleaseDays))- let outcome = try await library.updateWork(+ let receipt = try await library.updateWorkWithMembershipReceipt( id: workID, basis: basis, draft: draft, calendar: calendar)- if case .conflict(let conflict) = outcome {+ if case .conflict(let conflict) = receipt.outcome { // No optimistic mutation and no draft reset: the edit is the // only copy of itself until the reader resolves the conflict. let message = EntryDetailModel.conflictMessage(conflict)@@ -2895,6 +3088,7 @@ public final class WorkDetailModel { isSubmitting = false return }+ rememberRecordCopyTransition(receipt, event: offerEvent, generation: offerGeneration) await onMutation() if reloading { await load(preservingDrafts: false)
diff --git a/Asterism/Asterism/ViewModels/WorkRecordCopyModel.swift b/Asterism/Asterism/ViewModels/WorkRecordCopyModel.swiftnew file mode 100644index 00000000..990410c5--- /dev/null+++ b/Asterism/Asterism/ViewModels/WorkRecordCopyModel.swift@@ -0,0 +1,338 @@+import AsterismCore+import Foundation+import Observation++/// One value-draft session. Selection reads never write and planned UUIDs survive+/// refreshes and lost responses. Kind is part of every source identity.+@MainActor @Observable+public final class WorkRecordCopyModel: Identifiable {+ public let id = UUID()+ public enum State: Equatable {+ case loading, editing, previewing, submitting, checkingOutcome, blocked, committed, closed,+ suspended+ }+ public struct Success: Identifiable {+ public let id = UUID()+ public let destination: WorkSnapshot+ public let createdCount: Int+ public let skippedCount: Int+ }+ public private(set) var state: State = .loading+ public private(set) var source: WorkPickerCandidate?+ public private(set) var destinations: [WorkPickerCandidate] = []+ public private(set) var records: [RecordCopyRecord] = []+ public private(set) var selectedIdentities: Set<RecordCopyIdentity> = []+ public private(set) var destinationID: UUID?+ public private(set) var includeNotes = false+ public private(set) var preview: RecordCopyPreview?+ public private(set) var message: String?+ public private(set) var success: Success?+ public private(set) var retryNeedsConfirmation = false+ private let sourceWorkID: UUID+ private let presetDestinationID: UUID?+ private let library: any LibraryProviding+ private let onMutation: @Sendable () async -> Void+ private var plannedIDs: [RecordCopyIdentity: UUID] = [:]+ private var linkedIDs: Set<UUID> = []+ private var generation = 0+ private var needsRefresh = false+ private var uncertainPreview: RecordCopyPreview?+ private var selectionNotice: String?+ private var stateBeforeSuspension: State?+ private var hasStarted = false++ public init(+ sourceWorkID: UUID, library: any LibraryProviding,+ onMutation: @escaping @Sendable () async -> Void, destinationID: UUID? = nil+ ) {+ self.sourceWorkID = sourceWorkID+ self.library = library+ self.onMutation = onMutation+ self.presetDestinationID = destinationID+ }+ public var isSubmitting: Bool { state == .submitting || state == .checkingOutcome }+ private var canEdit: Bool {+ !isSubmitting && state != .closed && state != .committed && state != .blocked+ && state != .suspended+ }+ public var plannedCount: Int { preview?.rows.filter { $0.choice == .copy }.count ?? 0 }+ public var canAccept: Bool {+ guard state == .editing, !needsRefresh, !retryNeedsConfirmation,+ source?.unavailableReason == nil, let preview, plannedCount > 0,+ destinations.contains(where: { $0.id == destinationID && $0.unavailableReason == nil })+ else { return false }+ return RecordCopyPlanning.unacknowledgedClashes(+ preview.rows, destination: preview.basis.destination+ ).isEmpty+ }+ public func relationshipLabel(for destination: WorkPickerCandidate) -> String {+ let linked = linkedIDs.contains(destination.id)+ let series =+ source?.work.membership.map { $0.seriesID == destination.work.membership?.seriesID } ?? false+ return linked && series+ ? "Linked work and series peer"+ : series ? "Series peer" : linked ? "Linked work" : "Relationship changed; refresh choices"+ }+ public func start() async {+ guard !hasStarted, state != .closed else { return }+ hasStarted = true+ await refreshChoices()+ if let presetDestinationID, canEdit { await selectDestination(presetDestinationID) }+ }+ public func refreshChoices() async {+ guard canEdit else { return }+ generation += 1+ let token = generation+ state = .loading+ do {+ async let contextRead = library.recordCopyContext(sourceWorkID: sourceWorkID)+ async let detailRead = library.workDetail(id: sourceWorkID)+ let (context, detail) = try await (contextRead, detailRead)+ guard token == generation, state != .closed else { return }+ source = context.source+ destinations = context.destinations+ records = context.records+ linkedIDs = Set(detail.links.map(\.otherWorkID))+ let available = Set(records.filter { $0.unavailableReason == nil }.map(\.identity))+ let removed = selectedIdentities.subtracting(available)+ selectedIdentities.formIntersection(available)+ state = .editing+ selectionNotice =+ removed.isEmpty+ ? nil : "Some selected records are unavailable. Other selections have been kept."+ message = selectionNotice+ if let destinationID,+ !destinations.contains(where: { $0.id == destinationID && $0.unavailableReason == nil })+ {+ preview = nil+ needsRefresh = true+ message = "The destination is unavailable. Your record selections have been kept."+ } else if destinationID != nil {+ await refreshPreview()+ }+ } catch {+ guard token == generation, state != .closed else { return }+ state = .editing+ preview = nil+ needsRefresh = true+ message = error.localizedDescription+ }+ }+ public func selectDestination(_ id: UUID) async {+ guard canEdit else { return }+ destinationID = id+ preview = nil+ await refreshPreview()+ }+ public func toggleSelection(_ identity: RecordCopyIdentity) async {+ guard canEdit,+ records.contains(where: { $0.identity == identity && $0.unavailableReason == nil })+ else { return }+ if !selectedIdentities.insert(identity).inserted { selectedIdentities.remove(identity) }+ await refreshPreview()+ }+ public func selectAll(_ kind: RecordKind) async {+ guard canEdit else { return }+ selectedIdentities.formUnion(+ records.filter { $0.kind == kind && $0.unavailableReason == nil }.map(\.identity))+ await refreshPreview()+ }+ public func clear(_ kind: RecordKind) async {+ guard canEdit else { return }+ selectedIdentities = selectedIdentities.filter { $0.kind != kind }+ await refreshPreview()+ }+ public func setIncludeNotes(_ value: Bool) async {+ guard canEdit else { return }+ includeNotes = value+ await refreshPreview()+ }+ public func refreshPreview() async {+ guard canEdit, let destinationID else { return }+ generation += 1+ let token = generation+ let old = preview+ state = .previewing+ needsRefresh = true+ let selections = records.filter { selectedIdentities.contains($0.identity) }.map { record in+ let copyID = plannedIDs[record.identity] ?? UUID()+ plannedIDs[record.identity] = copyID+ return RecordCopySelection(kind: record.kind, sourceID: record.id, destinationID: copyID)+ }+ do {+ var fresh = try await library.previewRecordCopy(+ sourceWorkID: sourceWorkID, destinationWorkID: destinationID, selections: selections,+ includeNotes: includeNotes)+ guard token == generation, state != .closed else { return }+ // Keep explicit decisions only against the same concrete overlaps.+ // New overlaps clear consent; informational Skip overlaps stay visible.+ if old?.destinationWorkID == fresh.destinationWorkID {+ for index in fresh.rows.indices {+ if let prior = old?.rows.first(where: {+ $0.kind == fresh.rows[index].kind && $0.sourceID == fresh.rows[index].sourceID+ }) {+ fresh.rows[index].choice = prior.choice+ fresh.rows[index].acknowledgedClashes = prior.acknowledgedClashes+ }+ }+ // A formerly automatic Copy must not silently carry across a newly+ // discovered destination clash. A selected-but-Skip peer contributes+ // information without inventing an actual planned duplicate.+ let newlyClashing = fresh.rows.filter { row in+ guard row.choice == .copy,+ let previous = old?.rows.first(where: {+ $0.kind == row.kind && $0.sourceID == row.sourceID+ }),+ let old+ else { return false }+ let before = RecordCopyPlanning.actualClashes(+ for: previous, in: old.rows, destination: old.basis.destination)+ let after = RecordCopyPlanning.actualClashes(+ for: row, in: fresh.rows, destination: fresh.basis.destination)+ return !after.isSubset(of: before)+ }.map { RecordCopyIdentity(kind: $0.kind, id: $0.sourceID) }+ for index in fresh.rows.indices+ where newlyClashing.contains(+ .init(kind: fresh.rows[index].kind, id: fresh.rows[index].sourceID))+ {+ fresh.rows[index].choice = .skip+ fresh.rows[index].acknowledgedClashes = []+ }+ invalidateConsent(&fresh)+ }+ preview = fresh+ state = .editing+ needsRefresh = false+ if !retryNeedsConfirmation { message = selectionNotice }+ } catch {+ guard token == generation, state != .closed else { return }+ preview = nil+ state = .editing+ message = error.localizedDescription+ }+ }+ private func invalidateConsent(_ preview: inout RecordCopyPreview) {+ for index in preview.rows.indices {+ let actual = RecordCopyPlanning.actualClashes(+ for: preview.rows[index], in: preview.rows, destination: preview.basis.destination)+ if !actual.isSubset(of: preview.rows[index].acknowledgedClashes) {+ preview.rows[index].acknowledgedClashes = []+ }+ }+ }+ public func setChoice(_ choice: RecordCopyChoice, for identity: RecordCopyIdentity) {+ guard state == .editing, var fresh = preview,+ let index = fresh.rows.firstIndex(where: {+ $0.kind == identity.kind && $0.sourceID == identity.id+ })+ else { return }+ fresh.rows[index].choice = choice+ invalidateConsent(&fresh)+ preview = fresh+ }+ public func acknowledge(_ identity: RecordCopyIdentity) {+ guard state == .editing, var fresh = preview,+ let index = fresh.rows.firstIndex(where: {+ $0.kind == identity.kind && $0.sourceID == identity.id+ })+ else { return }+ fresh.rows[index].acknowledgedClashes = RecordCopyPlanning.actualClashes(+ for: fresh.rows[index], in: fresh.rows, destination: fresh.basis.destination)+ preview = fresh+ }+ public func confirmRetry() {+ guard canEdit else { return }+ retryNeedsConfirmation = false+ }+ public func accept() async {+ guard canAccept, let contract = preview else { return }+ state = .submitting+ message = nil+ do {+ switch try await library.commitRecordCopy(contract) {+ case .committed(let ids, let skipped):+ await finish(contract, count: ids.count, skipped: skipped)+ case .refused(let reason):+ state = .editing+ needsRefresh = true+ message = reason+ }+ } catch {+ uncertainPreview = contract+ await inspectOutcome()+ }+ }+ /// Inspection retries never submit. A partial result remains blocked; only+ /// absence allows an explicitly confirmed retry using the same UUIDs.+ public func inspectOutcome() async {+ guard let contract = uncertainPreview, state != .closed, state != .committed,+ state != .checkingOutcome+ else { return }+ state = .checkingOutcome+ message = "Checking whether copying completed…"+ do {+ switch try await library.inspectRecordCopyOutcome(contract) {+ case .committed:+ await finish(+ contract, count: contract.rows.filter { $0.choice == .copy }.count,+ skipped: contract.rows.filter { $0.choice == .skip }.count)+ case .absent:+ uncertainPreview = nil+ state = .editing+ retryNeedsConfirmation = true+ await refreshPreview()+ message =+ "No planned copies were found. An explicit retry may recreate a copy deleted elsewhere. Review before retrying."+ case .conflicting:+ state = .blocked+ message =+ "Some planned copies are missing or differ. Check the destination before continuing."+ }+ } catch {+ state = .blocked+ message =+ "Could not check whether copying completed. Retry the check before copying again. \(error.localizedDescription)"+ }+ }+ private func finish(_ contract: RecordCopyPreview, count: Int, skipped: Int) async {+ guard let destination = destinations.first(where: { $0.id == contract.destinationWorkID })?.work+ else {+ state = .blocked+ return+ }+ success = Success(destination: destination, createdCount: count, skippedCount: skipped)+ uncertainPreview = nil+ state = .committed+ await onMutation()+ }+ public func close() {+ guard !isSubmitting, state != .suspended else { return }+ generation += 1+ state = .closed+ }+ public func suspendForResolution() {+ guard !isSubmitting, state != .closed, state != .committed else { return }+ stateBeforeSuspension = state+ generation += 1+ state = .suspended+ }+ public func resumeAfterResolution() async {+ guard state == .suspended else { return }+ if uncertainPreview != nil || stateBeforeSuspension == .blocked {+ stateBeforeSuspension = nil+ state = .blocked+ return+ }+ stateBeforeSuspension = nil+ state = .editing+ await refreshChoices()+ }+ public func discardSuspendedSession() {+ guard state == .suspended else {+ close()+ return+ }+ generation += 1+ state = .closed+ }+}
diff --git a/Asterism/Asterism/Views/RecordCopyOfferView.swift b/Asterism/Asterism/Views/RecordCopyOfferView.swiftnew file mode 100644index 00000000..1526f38d--- /dev/null+++ b/Asterism/Asterism/Views/RecordCopyOfferView.swift@@ -0,0 +1,139 @@+import AsterismCore+import AsterismPresentation+import ConstellationKit+import SwiftUI++struct RecordCopyOfferView: View {+ @State var coordinator: RecordCopyOfferCoordinator+ let onSuccess: (WorkRecordCopyModel.Success) -> Void+ var onCheckLibrary: ((WorkRecordCopyModel) -> Void)? = nil+ @Environment(\.dismiss) private var dismiss+ @Environment(\.locale) private var locale+ @Environment(\.siteNames) private var siteNames++ var body: some View {+ Group {+ if let model = coordinator.copyModel {+ WorkRecordCopyView(+ model: model, onSuccess: onSuccess,+ onCancel: {+ coordinator.consume()+ dismiss()+ },+ onCheckLibrary: onCheckLibrary.map { callback in { callback(model) } })+ } else {+ NavigationStack { reviewList }+ }+ }+ .onDisappear { coordinator.consume() }+ }+ private var reviewList: some View {+ List {+ if coordinator.offers.count > 1 {+ Section {+ Text(+ "Review one added work. Closing this review dismisses the offer for the whole batch; the other additions remain available through Copy characters and places on a work."+ )+ .accessibilityIdentifier("record-copy-offer-batch-explanation")+ }+ }+ Section("Saved additions") {+ ForEach(coordinator.offers, id: \.destination.id) { offer in+ Button {+ coordinator.selectDestination(offer.destination.id)+ } label: {+ VStack(alignment: .leading, spacing: 6) {+ WorkRow(work: offer.destination.work, showsAllSites: true)+ Text(+ "Saved in \(offer.series.label) at \(SeriesPosition.format(offer.basis.destinationPosition, locale: locale))"+ ).font(.caption)+ if coordinator.selectedDestinationID == offer.destination.id {+ Label("Reviewing this addition", systemImage: "checkmark")+ }+ }+ }+ .disabled(coordinator.isReading)+ .accessibilityIdentifier(+ "record-copy-offer-destination-\(offer.destination.id.uuidString)"+ )+ .accessibilityLabel(+ "Review addition \(workContext(offer.destination.work)), \(offer.series.label), position \(SeriesPosition.format(offer.basis.destinationPosition, locale: locale))"+ )+ }+ }+ if let offer = coordinator.selectedOffer {+ Section("Earlier work") {+ if offer.requiresSourceChoice {+ Text(+ "Position \(SeriesPosition.format(offer.precedingPosition, locale: locale)) has more than one earlier work. Choose the source deliberately, including when only one is currently available."+ )+ .accessibilityIdentifier("record-copy-offer-tie")+ }+ ForEach(offer.sources) { source in+ Button {+ coordinator.selectSource(source.id)+ } label: {+ VStack(alignment: .leading) {+ WorkRow(work: source.work, showsAllSites: true)+ if coordinator.selectedSourceID == source.id {+ Label("Selected source", systemImage: "checkmark")+ }+ }+ }+ .disabled(coordinator.isReading)+ .accessibilityIdentifier("record-copy-offer-source-\(source.id.uuidString)")+ .accessibilityLabel(+ "\(workContext(source.work)), \(offer.series.label), position \(SeriesPosition.format(offer.precedingPosition, locale: locale)), \(coordinator.selectedSourceID == source.id ? "selected" : "not selected")"+ )+ }+ ForEach(offer.unavailablePredecessors) { source in+ Text(+ "\(source.work.displayTitle): \(source.unavailableReason ?? "Unavailable for copying")"+ )+ .font(.caption).accessibilityIdentifier(+ "record-copy-offer-unavailable-\(source.id.uuidString)")+ }+ }+ let source = offer.sources.first { $0.id == coordinator.selectedSourceID }+ Button(+ source.map { "Review characters and places from \($0.work.displayTitle)" }+ ?? "Choose an earlier source to review"+ ) {+ Task { await coordinator.review() }+ }+ .disabled(source == nil || coordinator.isReading)+ .accessibilityIdentifier("record-copy-offer-review")+ Text(+ "Review opens ordinary copying with no records selected. Nothing is copied until its final Copy button."+ ).font(.caption)+ }+ if let notice = coordinator.offerReadNotice {+ Text(notice).font(.caption).accessibilityIdentifier("record-copy-offer-read-notice")+ }+ if let message = coordinator.message {+ Text(message).accessibilityIdentifier("record-copy-offer-message")+ }+ if coordinator.isReading { ProgressView("Refreshing saved series order…") }+ }+ .scrollContentBackground(.hidden).macListChrome()+ .navigationTitle("Review characters and places")+ .accessibilityIdentifier("record-copy-offer")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Not now") {+ coordinator.consume()+ dismiss()+ }+ .keyboardShortcut(.cancelAction).accessibilityIdentifier("record-copy-offer-decline")+ }+ }+ }+ private func workContext(_ work: WorkSnapshot) -> String {+ var context = [work.displayTitle]+ context += work.memberships.map { siteNames.label(for: $0.hostname) }+ if let type = work.typeDisplay.name { context.append(type) }+ context += work.credits.map { $0.creator.label }+ return context.joined(separator: ", ")+ }++}
diff --git a/Asterism/Asterism/Views/RecordCopySuccessPresentation.swift b/Asterism/Asterism/Views/RecordCopySuccessPresentation.swiftnew file mode 100644index 00000000..d0441ba2--- /dev/null+++ b/Asterism/Asterism/Views/RecordCopySuccessPresentation.swift@@ -0,0 +1,22 @@+import AsterismCore+import SwiftUI++/// The host raises this only from the sheet's completed dismissal callback.+struct RecordCopySuccessPresentation: ViewModifier {+ @Binding var success: WorkRecordCopyModel.Success?+ let onSelectWork: ((UUID) -> Void)?+ func body(content: Content) -> some View {+ content.alert(+ "Copied characters and places",+ isPresented: Binding(+ get: { success != nil }, set: { if !$0 { success = nil } }), presenting: success+ ) { result in+ if let onSelectWork { Button("Open destination") { onSelectWork(result.destination.id) } }+ Button("Done", role: .cancel) {}+ } message: { result in+ Text(+ "\(result.createdCount) copied, \(result.skippedCount) skipped in \(result.destination.displayTitle)."+ )+ }+ }+}
diff --git a/Asterism/Asterism/Views/SeriesDetailView.swift b/Asterism/Asterism/Views/SeriesDetailView.swiftindex 082c78b5..d22226ea 100644--- a/Asterism/Asterism/Views/SeriesDetailView.swift+++ b/Asterism/Asterism/Views/SeriesDetailView.swift@@ -12,6 +12,12 @@ import SwiftUI /// membership and the series itself are changed (Q53). struct SeriesDetailView: View { @State private var model: SeriesDetailModel+ @State private var copyReviewHost: RecordCopyReviewHostState+ @State private var activeRecordCopyFlow: RecordCopyFlow?+ @State private var pendingCopySuccess: WorkRecordCopyModel.Success?+ @State private var copySuccess: WorkRecordCopyModel.Success?+ @State private var shouldResolveCopy = false+ private let onCheckLibrary: (() -> Void)? /// `AppLibraryModel.snapshotGeneration`: a member or a rename arriving /// through sync bumps it, and the screen re-reads on the bump (Req 11.2). let snapshotGeneration: Int@@ -36,12 +42,16 @@ struct SeriesDetailView: View { init( model: SeriesDetailModel,+ copyReviewHost: RecordCopyReviewHostState? = nil,+ onCheckLibrary: (() -> Void)? = nil, snapshotGeneration: Int, showsSky: Bool, onSelectWork: @escaping (UUID) -> Void, onDeleted: @escaping () -> Void ) { _model = State(initialValue: model)+ _copyReviewHost = State(initialValue: copyReviewHost ?? RecordCopyReviewHostState(route: .series(id: model.seriesID, originWorkID: model.originWorkID)))+ self.onCheckLibrary = onCheckLibrary self.snapshotGeneration = snapshotGeneration self.showsSky = showsSky self.onSelectWork = onSelectWork@@ -113,11 +123,18 @@ struct SeriesDetailView: View { .accessibilityIdentifier("series-detail-error") case .ready: headerSection- if !model.isEditing { progressSection }+ if !model.isEditing { progressSection; resumeCopySection } membersSection if model.isEditing { manageSection } } + if !model.isEditing, let notice = model.recordCopyOffers.offerReadNotice {+ Section {+ Text(notice).font(.caption).foregroundStyle(.secondary)+ .constellationListRow()+ .accessibilityIdentifier("series-detail-copy-offer-read-notice")+ }+ } if let message = model.message { Section { // Q37 of `work-detail`: a refusal is amber, not system red —@@ -143,7 +160,7 @@ struct SeriesDetailView: View { .hidesBackButton(model.isEditing) // `app-intents` Req 4.5: edit mode and the member picker hold the // reader's place against an open intent.- .intentEditSession(active: model.isEditing || isPresentingPicker)+ .intentEditSession(active: model.isEditing || presentsCopyObstruction) .screenSky(showsSky) .accessibilityIdentifier("series-detail") .toolbar { toolbarItems }@@ -162,6 +179,37 @@ struct SeriesDetailView: View { Task { await model.addMember(workID) } }) }+ .sheet(item: $activeRecordCopyFlow, onDismiss: {+ model.recordCopyOffers.consume()+ copySuccess = pendingCopySuccess; pendingCopySuccess = nil+ if shouldResolveCopy {+ shouldResolveCopy = false; copyReviewHost.isVisitingResolution = true; onCheckLibrary?()+ }+ Task {+ await model.load()+ await model.recordCopyOffers.advanceDeferredEvents()+ presentRecordCopyOfferIfReady()+ }+ }) { flow in+ switch flow {+ case .manual(let copy):+ WorkRecordCopyView(model: copy, onSuccess: { pendingCopySuccess = $0 },+ onCheckLibrary: onCheckLibrary.map { _ in { suspendCopyForResolution(copy) } })+ case .offered(let coordinator):+ RecordCopyOfferView(coordinator: coordinator, onSuccess: { pendingCopySuccess = $0 },+ onCheckLibrary: onCheckLibrary.map { _ in { copy in suspendCopyForResolution(copy) } })+ }+ }+ .modifier(RecordCopySuccessPresentation(success: $copySuccess, onSelectWork: onSelectWork))+ .onChange(of: model.recordCopyOffers.hasOffer) { _, _ in presentRecordCopyOfferIfReady() }+ .onChange(of: model.isEditing) { _, _ in presentRecordCopyOfferIfReady() }+ .onChange(of: model.isSubmitting) { _, _ in presentRecordCopyOfferIfReady() }+ .onChange(of: presentsCopyObstruction) { _, _ in presentRecordCopyOfferIfReady() }+ .onAppear { copyReviewHost.isVisitingResolution = false }+ .onDisappear {+ guard !copyReviewHost.isVisitingResolution else { return }+ shouldResolveCopy = false; copyReviewHost.discard(); model.discardRecordCopyOffers()+ } .confirmationDialog( "Delete this series?", isPresented: Binding(@@ -185,6 +233,34 @@ struct SeriesDetailView: View { // MARK: - Header (Reqs 1.1, 1.2, 3.1) + private var presentsCopyObstruction: Bool {+ isPresentingPicker || activeRecordCopyFlow != nil || model.deletionPrompt != nil+ }+ private func presentRecordCopyOfferIfReady() {+ guard !model.isEditing, !model.isSubmitting, !presentsCopyObstruction,+ !copyReviewHost.isVisitingResolution, copyReviewHost.suspendedModel == nil,+ model.recordCopyOffers.hasOffer else { return }+ Task {+ guard await model.recordCopyOffers.prepareForPresentation() else { return }+ guard !model.isEditing, !model.isSubmitting, !presentsCopyObstruction,+ !copyReviewHost.isVisitingResolution, copyReviewHost.suspendedModel == nil else { return }+ activeRecordCopyFlow = .offered(model.recordCopyOffers)+ }+ }+ private func suspendCopyForResolution(_ copy: WorkRecordCopyModel) {+ copyReviewHost.suspendedModel = copy; shouldResolveCopy = true+ }+ @ViewBuilder private var resumeCopySection: some View {+ if copyReviewHost.suspendedModel != nil {+ Section {+ Button("Resume copy review") {+ Task { if let copy = await copyReviewHost.resume() { activeRecordCopyFlow = .manual(copy) } }+ }.disabled(copyReviewHost.isResuming).accessibilityIdentifier("series-detail-resume-copy")+ Button("Discard copy review") { copyReviewHost.discard() }+ }+ }+ }+ @ViewBuilder private var headerSection: some View { Section {
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex 05510c07..0879be41 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -39,6 +39,11 @@ struct WorkDetailView: View { /// spell their sites. The site row itself gets this from `SiteLabel`. @Environment(\.siteNames) private var siteNames @State private var activeMergeModel: WorkMergeModel?+ @State private var activeRecordCopyFlow: RecordCopyFlow?+ @State private var pendingCopySuccess: WorkRecordCopyModel.Success?+ @State private var copySuccess: WorkRecordCopyModel.Success?+ @State private var copyReviewHost: RecordCopyReviewHostState+ @State private var shouldResolveCopy = false /// Which site the URL-identity review is being opened for, or nil when no /// review is up. A hostname rather than a flag because the sheet is per site /// (Q33) and a multi-site Work chooses one from a menu.@@ -57,6 +62,7 @@ struct WorkDetailView: View { /// Req 9.2's route out of a torn Work, or nil where the caller has no sheet /// to open. Entry detail's shape, for the same reason it has one. let onResolveDuplicate: (() -> Void)?+ let onCheckLibrary: (() -> Void)? /// Where a tapped chapter row goes, or nil where the host has no entry /// route to push onto. Navigation is `ContentView`'s (the house rule), so /// the screen reports the tap rather than resolving a destination.@@ -141,15 +147,18 @@ struct WorkDetailView: View { /// a result that arrives after the reader cancelled or picked again is /// carrying a token the model has already retired. @State private var coverPickToken = UUID()+ @State private var isCoverDropTargeted = false init( model: WorkDetailModel, focusedEntryID: UUID? = nil,+ copyReviewHost: RecordCopyReviewHostState? = nil, currentDay: CivilDay, calendar: Calendar, lastSavedLatestWorkID: UUID? = nil, latestSaveGeneration: Int = 0, onResolveDuplicate: (() -> Void)? = nil,+ onCheckLibrary: (() -> Void)? = nil, onSelectEntry: ((UUID) -> Void)? = nil, onSetLatest: ((UUID) -> Void)? = nil, onMergeCommitted: ((UUID) -> Void)? = nil,@@ -162,12 +171,14 @@ struct WorkDetailView: View { ) { self.focusedEntryID = focusedEntryID _model = State(initialValue: model)+ _copyReviewHost = State(initialValue: copyReviewHost ?? RecordCopyReviewHostState(sourceRouteID: model.work?.id ?? UUID())) self.currentDay = currentDay self.calendar = calendar self.lastSavedLatestWorkID = lastSavedLatestWorkID self.latestSaveGeneration = latestSaveGeneration _exportModel = State(initialValue: exportModel) self.onResolveDuplicate = onResolveDuplicate+ self.onCheckLibrary = onCheckLibrary self.onSelectEntry = onSelectEntry self.onSetLatest = onSetLatest self.onMergeCommitted = onMergeCommitted@@ -192,7 +203,7 @@ struct WorkDetailView: View { /// them are raised only in edit mode, which counts already; they are listed /// anyway, so the guard does not rest on that staying true. private var presentsSheet: Bool {- reviewModel != nil || activeMergeModel != nil || reviewingIdentityHostname != nil+ reviewModel != nil || activeMergeModel != nil || activeRecordCopyFlow != nil || showingManualEntry || reviewingIdentityHostname != nil || showingURLReteach || isPresentingLinkPicker || pendingLinkTarget != nil || editingLink != nil || isNamingSeries || isPresentingCreatorPicker || editingCredit != nil || expandedEditCharacterID != nil@@ -270,6 +281,37 @@ struct WorkDetailView: View { ManualEntryView(model: model.manualEntryForm()) } .sheet(isPresented: $isPickingReturnDate) { returnDatePicker }+ .modifier(RecordCopySuccessPresentation(success: $copySuccess, onSelectWork: onSelectWork))+ .sheet(item: $activeRecordCopyFlow, onDismiss: {+ model.recordCopyOffers.consume()+ copySuccess = pendingCopySuccess+ pendingCopySuccess = nil+ if shouldResolveCopy {+ shouldResolveCopy = false; copyReviewHost.isVisitingResolution = true; onCheckLibrary?()+ }+ Task {+ await model.load()+ await model.recordCopyOffers.advanceDeferredEvents()+ presentRecordCopyOfferIfReady()+ }+ }) { flow in+ switch flow {+ case .manual(let copy):+ WorkRecordCopyView(model: copy, onSuccess: { pendingCopySuccess = $0 },+ onCheckLibrary: onCheckLibrary.map { _ in { suspendCopyForResolution(copy) } })+ case .offered(let coordinator):+ RecordCopyOfferView(coordinator: coordinator, onSuccess: { pendingCopySuccess = $0 },+ onCheckLibrary: onCheckLibrary.map { _ in { copy in suspendCopyForResolution(copy) } })+ }+ }+ .onChange(of: model.recordCopyOffers.hasOffer) { _, _ in presentRecordCopyOfferIfReady() }+ .onChange(of: model.isEditing) { _, _ in presentRecordCopyOfferIfReady() }+ .onChange(of: presentsSheet) { _, _ in presentRecordCopyOfferIfReady() }+ .onDisappear {+ guard !copyReviewHost.isVisitingResolution else { return }+ shouldResolveCopy = false; copyReviewHost.discard(); model.discardRecordCopyOffers()+ }+ .onAppear { copyReviewHost.isVisitingResolution = false } } // MARK: - The §6 layout@@ -457,6 +499,7 @@ struct WorkDetailView: View { @ViewBuilder private func readingSections(_ work: WorkSnapshot) -> some View { viewHeaderSection(work)+ copyRecordsSection progressCard(work) seriesSection openLastNotedSection@@ -507,6 +550,7 @@ struct WorkDetailView: View { HStack(alignment: .top, spacing: 32) { VStack(alignment: .leading, spacing: 20) { wideIdentity(work)+ copyRecordsSection progressCard(work) wideMetadata(work) openLastNotedSection@@ -662,6 +706,47 @@ struct WorkDetailView: View { .finishedReadingDialog(model) } + private func suspendCopyForResolution(_ copy: WorkRecordCopyModel) {+ copyReviewHost.suspendedModel = copy+ shouldResolveCopy = true+ }+ private func presentRecordCopyOfferIfReady() {+ guard !model.isEditing, !presentsSheet, !copyReviewHost.isVisitingResolution,+ copyReviewHost.suspendedModel == nil, model.recordCopyOffers.hasOffer else { return }+ Task {+ guard await model.recordCopyOffers.prepareForPresentation() else { return }+ guard !model.isEditing, !presentsSheet, !copyReviewHost.isVisitingResolution,+ copyReviewHost.suspendedModel == nil else { return }+ activeRecordCopyFlow = .offered(model.recordCopyOffers)+ }+ }++ private var copyRecordsSection: some View {+ Section {+ if copyReviewHost.suspendedModel != nil {+ Button("Resume copy review") {+ Task {+ if let resumed = await copyReviewHost.resume() { activeRecordCopyFlow = .manual(resumed) }+ }+ }.disabled(copyReviewHost.isResuming).accessibilityIdentifier("work-detail-resume-copy")+ Button("Discard copy review") {+ copyReviewHost.discard()+ }+ }+ ConstellationFooterButton(title: "Copy characters and places…", systemImage: "doc.on.doc") {+ if let copy = model.recordCopyModel() { activeRecordCopyFlow = .manual(copy) }+ }+ .constellationListRow()+ .accessibilityIdentifier("work-detail-copy-records")+ .disabled(copyReviewHost.isResuming || copyReviewHost.suspendedModel != nil)+ if let notice = model.recordCopyOffers.offerReadNotice {+ Text(notice).font(.caption).foregroundStyle(.secondary)+ .constellationListRow()+ .accessibilityIdentifier("work-detail-copy-offer-read-notice")+ }+ }+ }+ // MARK: - View mode /// View mode's header (`work-detail-reading-redesign`): the work's full@@ -1211,6 +1296,18 @@ struct WorkDetailView: View { } } .constellationCaptionedField("Cover")+ .overlay {+ if isCoverDropTargeted && model.canAcceptCoverDrop {+ RoundedRectangle(cornerRadius: 8)+ .stroke(AsterismColors.amberText, lineWidth: 2)+ .allowsHitTesting(false)+ .accessibilityHidden(true)+ }+ }+ .modifier(CoverDropTarget(+ canAccept: model.canAcceptCoverDrop,+ isTargeted: $isCoverDropTargeted,+ accept: { model.beginCoverDrop($0) != nil })) } /// What the menu is worn by: the draft's cover at slot size, or the site@@ -3007,7 +3104,7 @@ private struct WorkThumbnailPresentations: ViewModifier { // Req 4.11: the run stops when the sheet goes, and it stops again // when the page does — a push away from the editor is not a // dismissal and would otherwise leave the requests running.- .onDisappear { model.cancelCoverFetch() }+ .onDisappear { model.retireThumbnailPresentation() } .sheet( isPresented: Binding( get: { model.isPresentingCoverCandidates },
diff --git a/Asterism/Asterism/Views/WorkRecordCopyView.swift b/Asterism/Asterism/Views/WorkRecordCopyView.swiftnew file mode 100644index 00000000..dcc138c4--- /dev/null+++ b/Asterism/Asterism/Views/WorkRecordCopyView.swift@@ -0,0 +1,254 @@+import AsterismCore+import AsterismPresentation+import ConstellationKit+import SwiftUI++struct WorkRecordCopyView: View {+ @State var model: WorkRecordCopyModel+ let onSuccess: (WorkRecordCopyModel.Success) -> Void+ var onCancel: (() -> Void)? = nil+ var onCheckLibrary: (() -> Void)? = nil+ @Environment(\.dismiss) private var dismiss+ @Environment(\.siteNames) private var siteNames+ @Environment(\.locale) private var locale+ @State private var confirmingIdentity: RecordCopyIdentity?++ var body: some View {+ NavigationStack {+ List {+ if let source = model.source {+ Section("From") { WorkRow(work: source.work, showsAllSites: true) }+ if let reason = source.unavailableReason { Text(reason).foregroundStyle(.secondary) }+ }+ destinations+ ForEach(RecordKind.allCases, id: \.rawValue) { kind in selectionSection(kind) }+ Section("Content") {+ Toggle(+ "Include record notes",+ isOn: Binding(+ get: { model.includeNotes },+ set: { value in Task { await model.setIncludeNotes(value) } })+ )+ .disabled(model.isSubmitting || model.state == .blocked)+ .accessibilityIdentifier("record-copy-notes")+ Text(+ "Names and explicit aliases are copied. Earlier names travel only when listed as aliases."+ ).font(.caption)+ Text(+ "Facts, quotes and citations, extraction coverage and suppression decisions are not copied. Entries, work notes, ratings, progress and other work details stay where they are."+ )+ .font(.caption).accessibilityIdentifier("record-copy-exclusions")+ }+ if let preview = model.preview {+ Section("Preview") {+ ForEach(preview.rows) { row in previewRow(row, preview: preview) }+ }+ }+ if let message = model.message {+ Section { Text(message).accessibilityIdentifier("record-copy-message") }+ }+ if let onCheckLibrary {+ Button("Check Library") {+ model.suspendForResolution()+ onCheckLibrary()+ dismiss()+ }+ .disabled(model.isSubmitting).accessibilityIdentifier("record-copy-resolve")+ Text(+ "Your copy selections stay here. Return to the work and resume this review after checking the library."+ ).font(.caption)+ } else if model.source?.unavailableReason != nil+ || model.records.contains(where: { $0.unavailableReason != nil })+ || model.state == .blocked+ {+ Text(+ "Cancel this preview and open Check Library from the main library to resolve unavailable records."+ ).font(.caption)+ }+ if model.state == .loading || model.state == .previewing || model.isSubmitting {+ ProgressView(+ model.state == .checkingOutcome+ ? "Checking whether copying completed…" : "Preparing copies…")+ }+ if model.state == .blocked {+ Button("Retry outcome check") { Task { await model.inspectOutcome() } }+ .accessibilityIdentifier("record-copy-inspect")+ } else if model.retryNeedsConfirmation {+ Button("I understand; allow retry") { model.confirmRetry() }+ .accessibilityIdentifier("record-copy-confirm-retry")+ } else if model.message != nil, !model.isSubmitting {+ Button("Refresh choices and preview") { Task { await model.refreshChoices() } }+ .accessibilityIdentifier("record-copy-refresh")+ }+ }+ .scrollContentBackground(.hidden).macListChrome()+ .navigationTitle("Copy characters and places")+ .accessibilityIdentifier("record-copy")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Cancel") {+ model.close()+ if let onCancel { onCancel() } else { dismiss() }+ }+ .disabled(model.isSubmitting).keyboardShortcut(.cancelAction)+ .accessibilityIdentifier("record-copy-cancel")+ }+ ToolbarItem(placement: .confirmationAction) {+ Button("Copy \(model.plannedCount)") { Task { await model.accept() } }+ .disabled(!model.canAccept).keyboardShortcut(.defaultAction)+ .accessibilityIdentifier("record-copy-accept")+ }+ }+ .task { await model.start() }+ .interactiveDismissDisabled(model.isSubmitting)+ .onChange(of: model.state) { _, state in+ if state == .committed, let success = model.success {+ onSuccess(success)+ dismiss()+ }+ }+ .onDisappear { model.close() }+ .alert(+ "Keep separate?",+ isPresented: Binding(+ get: { confirmingIdentity != nil }, set: { if !$0 { confirmingIdentity = nil } }),+ presenting: confirmingIdentity+ ) { identity in+ Button("Keep separate") {+ model.setChoice(.copy, for: identity)+ model.acknowledge(identity)+ }+ Button("Cancel", role: .cancel) {}+ } message: { _ in+ Text(+ "These matching names may represent different records. Existing records will stay unchanged. Future extracted facts can route to either same-name record according to the existing matching rules."+ )+ }+ }+ }+ private var destinations: some View {+ Section("Destination") {+ if model.destinations.isEmpty, model.state != .loading {+ Text(+ "Save a related-work link or shared series membership first. Copying does not create relationships."+ )+ }+ ForEach(model.destinations) { candidate in+ Button {+ Task { await model.selectDestination(candidate.id) }+ } label: {+ VStack(alignment: .leading) {+ WorkRow(work: candidate.work, showsAllSites: true)+ Text(model.relationshipLabel(for: candidate)).font(.caption)+ if let reason = candidate.unavailableReason { Text(reason).font(.caption) }+ if model.destinationID == candidate.id {+ Label("Selected destination", systemImage: "checkmark")+ }+ }+ }+ .disabled(+ candidate.unavailableReason != nil || model.isSubmitting || model.state == .blocked+ )+ .accessibilityIdentifier("record-copy-destination-\(candidate.id.uuidString)")+ .accessibilityLabel(destinationLabel(candidate))+ }+ }+ }+ private func destinationLabel(_ candidate: WorkPickerCandidate) -> String {+ let work = candidate.work+ var context = [work.displayTitle, model.relationshipLabel(for: candidate),+ model.destinationID == candidate.id ? "selected destination" : "not selected"]+ context += work.memberships.map { siteNames.label(for: $0.hostname) }+ if let type = work.typeDisplay.name { context.append(type) }+ if let series = SeriesPresentation.rowText(work, locale: locale) { context.append(series) }+ context += work.credits.map { $0.creator.label }+ if let reason = candidate.unavailableReason { context.append(reason) }+ return context.joined(separator: ", ")+ }+ private func selectionSection(_ kind: RecordKind) -> some View {+ Section(RecordKindPresentation.collection(kind)) {+ HStack {+ Button("Select all \(RecordKindPresentation.plural(kind))") {+ Task { await model.selectAll(kind) }+ }+ .accessibilityIdentifier("record-copy-all-\(kind.rawValue)")+ Spacer()+ Button("Clear") { Task { await model.clear(kind) } }+ .accessibilityIdentifier("record-copy-clear-\(kind.rawValue)")+ }+ // Each action owns its tap; automatic List row buttons would invoke both.+ .buttonStyle(.borderless)+ .disabled(model.isSubmitting || model.state == .blocked)+ ForEach(model.records.filter { $0.kind == kind }, id: \.id) { record in+ Button {+ Task { await model.toggleSelection(record.identity) }+ } label: {+ VStack(alignment: .leading, spacing: 4) {+ Label(+ record.name,+ systemImage: model.selectedIdentities.contains(record.identity)+ ? "checkmark.circle.fill" : "circle")+ if !record.aliases.isEmpty {+ Text(record.aliases.joined(separator: ", ")).font(.caption)+ }+ if !record.note.isEmpty {+ Text(record.note).font(.caption).fixedSize(horizontal: false, vertical: true)+ }+ if let reason = record.unavailableReason { Text(reason).font(.caption) }+ }+ }+ .disabled(record.unavailableReason != nil || model.isSubmitting || model.state == .blocked)+ .accessibilityIdentifier("record-copy-select-\(kind.rawValue)-\(record.id.uuidString)")+ .accessibilityAddTraits(model.selectedIdentities.contains(record.identity) ? .isSelected : [])+ .accessibilityLabel(+ "\(record.name), \(RecordKindPresentation.name(kind)), \(model.selectedIdentities.contains(record.identity) ? "selected" : "not selected")\(record.unavailableReason.map { ", \($0)" } ?? "")"+ )+ }+ }+ }+ private func previewRow(_ row: RecordCopyPlannedRow, preview: RecordCopyPreview) -> some View {+ let identity = RecordCopyIdentity(kind: row.kind, id: row.sourceID)+ var prospectiveRow = row+ prospectiveRow.choice = .copy+ let prospectiveRows = preview.rows.map {+ $0.kind == row.kind && $0.sourceID == row.sourceID ? prospectiveRow : $0+ }+ let prospectiveClashes = RecordCopyPlanning.actualClashes(+ for: prospectiveRow, in: prospectiveRows, destination: preview.basis.destination)+ return VStack(alignment: .leading, spacing: 8) {+ Text(+ "\(row.payload.name) · \(RecordKindPresentation.name(row.kind)) · \(row.choice == .copy ? "Copy" : "Skip")"+ )+ if model.includeNotes, !row.payload.note.isEmpty {+ Text(row.payload.note).font(.caption)+ .accessibilityIdentifier("record-copy-preview-note-\(row.kind.rawValue)-\(row.sourceID.uuidString)")+ }+ if !row.informationalClashes.isEmpty {+ Text(+ "Possible matches: "+ + row.informationalClashes.map {+ "\($0.name) (\($0.keys.sorted().joined(separator: ", ")))"+ }.sorted().joined(separator: "; ")+ ).font(.caption)+ if !prospectiveClashes.isEmpty {+ Button("Keep separate") { confirmingIdentity = identity }+ .accessibilityIdentifier(+ "record-copy-keep-\(row.kind.rawValue)-\(row.sourceID.uuidString)")+ }+ }+ Button(row.choice == .copy ? "Skip this record" : "Copy this record") {+ if row.choice == .copy {+ model.setChoice(.skip, for: identity)+ } else if prospectiveClashes.isEmpty {+ model.setChoice(.copy, for: identity)+ } else {+ confirmingIdentity = identity+ }+ }+ .accessibilityIdentifier("record-copy-choice-\(row.kind.rawValue)-\(row.sourceID.uuidString)")+ .accessibilityLabel("\(row.choice == .copy ? "Skip this record" : "Copy this record"), \(row.payload.name)")+ }+ .buttonStyle(.borderless)+ .disabled(model.state != .editing)+ }+}
diff --git a/Asterism/AsterismShareExtension/ChapterCaptureChoicesView.swift b/Asterism/AsterismShareExtension/ChapterCaptureChoicesView.swiftindex 0514cd17..78edebda 100644--- a/Asterism/AsterismShareExtension/ChapterCaptureChoicesView.swift+++ b/Asterism/AsterismShareExtension/ChapterCaptureChoicesView.swift@@ -5,37 +5,33 @@ import SwiftUI 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?+ @State private var expandedAlternatives = false 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- }+ private var showsChoices: Bool {+ projection.showsChapterChoicesInitially || expandedAlternatives } var body: some View { VStack(alignment: .leading, spacing: 12) { if case .chooseChapter(_, let reason) = projection.resolution { Text(reason) }- if projection.offersAnotherChapter || needsChoice || isCorrecting {+ if projection.offersAnotherChapter && !showsChoices {+ Button("Choose chapter") { expandedAlternatives = true }+ .accessibilityIdentifier("capture.choose-chapter")+ }+ if showsChoices { 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)) }+ choose(.existing(entry.id)) choiceMessage = "Updating the selected entry" } .accessibilityIdentifier("capture.chapter-existing-\(entry.id.uuidString.lowercased())")@@ -44,30 +40,26 @@ struct ChapterCaptureChoicesView: View { .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+ Button(projection.evidence.isEmpty ? "Add another chapter" : "Confirm new chapter") {+ choseNewChapter = true; 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(projection.evidence.isEmpty ? "capture.add-another-chapter" : "capture.confirm-new-chapter")+ Button("Save a separate note") { choseNewChapter = false; selectedExisting = nil; choose(.genericNote); choiceMessage = "Saving a separate note" } .accessibilityIdentifier("capture.generic-note")- if choseNewChapter && !isCorrecting && projection.captureDefault == .ordinary,+ if choseNewChapter && 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)) }+ Button("Keep my draft note and rating") { choose(.existing(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)) }+ Button("Keep existing chapter note and rating") { choose(.existing(id, contentChoice: .destination)) } .accessibilityIdentifier("capture.correction-keep-existing") } if let choiceMessage { Text(choiceMessage).font(.caption).accessibilityIdentifier("capture.chapter-choice") }@@ -79,7 +71,7 @@ struct ChapterCaptureChoicesView: View { private func updateNewChapter() { if choseNewChapter { let target = AuthoredEntryTarget(kind: .chapter, title: title, designation: designation)- choose(isCorrecting ? .correctedNewChapter(target) : .newChapter(target, confirmedNew: true))+ choose(.newChapter(target, confirmedNew: true)) } } }
diff --git a/Asterism/AsterismTests/AppLibraryModelTests.swift b/Asterism/AsterismTests/AppLibraryModelTests.swiftindex 46901438..32b21a9e 100644--- a/Asterism/AsterismTests/AppLibraryModelTests.swift+++ b/Asterism/AsterismTests/AppLibraryModelTests.swift@@ -14,6 +14,36 @@ struct AppLibraryModelTests { /// project; nothing in a test may restate one (lint check 5). private static let fixtureAppGroup = "group.example.fixture" + @Test("Concurrent work reloads and mutation markers retain every mock call and stable snapshots")+ func sharedMockRecorderPreservesConcurrentCallsAndSnapshots() async throws {+ let mock = MockLibraryProvider()+ let work = TestFixtures.makeWork(displayTitle: "Concurrent reloads")+ mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: work))+ let workers = 8+ let reloadsPerWorker = 64+ try await withThrowingTaskGroup(of: Void.self) { group in+ for _ in 0..<workers {+ group.addTask {+ for _ in 0..<reloadsPerWorker {+ _ = try await mock.workDetail(id: work.id)+ mock.callLog.append("mutation")+ let snapshot = mock.callLog+ let count = snapshot.count+ await Task.yield()+ #expect(snapshot.count == count)+ }+ }+ }+ try await group.waitForAll()+ }+ let expected = workers * reloadsPerWorker+ let calls = mock.callLog+ #expect(mock.workDetailCallCount == expected)+ #expect(calls.count == expected * 2)+ #expect(calls.filter { $0 == "workDetail" }.count == expected)+ #expect(calls.filter { $0 == "mutation" }.count == expected)+ }+ @Test("Daily exporter factory freezes the displayed date, calendar and explicit locale") @MainActor func selectedDayExportFactoryFreezesDisplayedContext() async throws { let root = FileManager.default.temporaryDirectory.appending(path: "day-export-factory-\(UUID())")
diff --git a/Asterism/AsterismTests/CoverDropSurfaceTests.swift b/Asterism/AsterismTests/CoverDropSurfaceTests.swiftnew file mode 100644index 00000000..598ac98f--- /dev/null+++ b/Asterism/AsterismTests/CoverDropSurfaceTests.swift@@ -0,0 +1,38 @@+#if os(iOS)+import Testing+import UIKit+@testable import Asterism++@MainActor+@Suite("Native Cover drop surface preserves ordinary controls")+struct CoverDropSurfaceTests {+ private final class InputEvent: UIEvent {+ let inputType: UIEvent.EventType+ init(_ inputType: UIEvent.EventType) {+ self.inputType = inputType+ super.init()+ }+ override var type: UIEvent.EventType { inputType }+ }++ @Test(arguments: [UIEvent.EventType.touches, .motion, .remoteControl, .presses, .scroll, .hover, .transform])+ func ordinaryInputPassesThroughToTheMenu(_ type: UIEvent.EventType) {+ let surface = CoverDropSurface(frame: CGRect(x: 0, y: 0, width: 100, height: 80))+ #expect(surface.hitTest(CGPoint(x: 40, y: 40), with: InputEvent(type)) == nil)+ }++ @Test func nativeDragTargetingIsRestrictedToTheField() {+ let surface = CoverDropSurface(frame: CGRect(x: 0, y: 0, width: 100, height: 80))+ #expect(surface.hitTest(CGPoint(x: 40, y: 40), with: nil) === surface)+ #expect(surface.hitTest(CGPoint(x: 101, y: 40), with: nil) == nil)+ #expect(surface.hitTest(CGPoint(x: 40, y: 81), with: nil) == nil)+ }++ @Test func nativeSurfaceAddsNoAccessibilityElement() {+ let surface = CoverDropSurface(frame: .zero)+ #expect(!surface.isAccessibilityElement)+ #expect(surface.accessibilityElementsHidden)+ #expect(surface.interactions.contains { $0 is UIDropInteraction })+ }+}+#endif
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex b7e2b6e7..b07fe5b8 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -4,6 +4,69 @@ import Foundation /// Test double for LibraryProviding that records calls and returns preset results. final class MockLibraryProvider: LibraryProviding, @unchecked Sendable {+ var updateWorkReceiptTransitions: [WorkMembershipTransition] = []+ var seriesReceiptTransitions: [WorkMembershipTransition] = []+ var recordCopyOfferResultByDestinationID: [UUID: Result<RecordCopySeriesOffer?, Error>] = [:]+ var recordCopyOfferHold: SubmissionGate?+ private var storedRecordCopyOfferCalls: [(destinationID: UUID, seriesID: UUID)] = []+ var recordCopyOfferCalls: [(destinationID: UUID, seriesID: UUID)] {+ recorderLock.withLock { storedRecordCopyOfferCalls }+ }+ func updateWorkWithMembershipReceipt(id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar) async throws -> MembershipWriteReceipt {+ let outcome = try await updateWork(id: id, basis: basis, draft: draft, calendar: calendar)+ let transitions: [WorkMembershipTransition]+ if case .committed = outcome { transitions = updateWorkReceiptTransitions } else { transitions = [] }+ return MembershipWriteReceipt(outcome: outcome, transitions: transitions)+ }+ func commitSeriesEditsWithMembershipReceipt(seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit]) async throws -> MembershipWriteReceipt {+ let outcome = try await commitSeriesEdits(seriesID: seriesID, name: name, notes: notes, members: members)+ let transitions: [WorkMembershipTransition]+ if case .committed = outcome { transitions = seriesReceiptTransitions } else { transitions = [] }+ return MembershipWriteReceipt(outcome: outcome, transitions: transitions)+ }+ func recordCopyOffer(destinationWorkID: UUID, seriesID: UUID) async throws -> RecordCopySeriesOffer? {+ recorderLock.withLock { storedRecordCopyOfferCalls.append((destinationWorkID, seriesID)) }+ guard let result = recordCopyOfferResultByDestinationID[destinationWorkID] else { throw MockError.notConfigured }+ await recordCopyOfferHold?.wait()+ return try result.get()+ }+ var recordCopyContextResult: Result<RecordCopyContext, Error> = .failure(MockError.notConfigured)+ var recordCopyPreviewHandler: (@Sendable (UUID, UUID, [RecordCopySelection], Bool) async throws -> RecordCopyPreview)?+ var recordCopyCommitResult: Result<RecordCopyOutcome, Error> = .failure(MockError.notConfigured)+ var recordCopyInspectionResult: Result<RecordCopyInspection, Error> = .failure(MockError.notConfigured)+ var recordCopyContextHold: SubmissionGate?+ var recordCopyCommitHold: SubmissionGate?+ var recordCopyInspectionHold: SubmissionGate?+ private var storedCopyContextCount = 0+ private var storedCopyContextSourceIDs: [UUID] = []+ private var storedCopyCommits: [RecordCopyPreview] = []+ private var storedCopyInspections: [RecordCopyPreview] = []+ var recordCopyContextCallCount: Int { recorderLock.withLock { storedCopyContextCount } }+ var recordCopyContextSourceIDs: [UUID] { recorderLock.withLock { storedCopyContextSourceIDs } }+ var recordCopyCommits: [RecordCopyPreview] { recorderLock.withLock { storedCopyCommits } }+ var recordCopyInspections: [RecordCopyPreview] { recorderLock.withLock { storedCopyInspections } }+ func recordCopyContext(sourceWorkID: UUID) async throws -> RecordCopyContext {+ recorderLock.withLock { storedCopyContextCount += 1; storedCopyContextSourceIDs.append(sourceWorkID) }+ let result = recordCopyContextResult+ await recordCopyContextHold?.wait()+ return try result.get()+ }+ func previewRecordCopy(sourceWorkID: UUID, destinationWorkID: UUID, selections: [RecordCopySelection], includeNotes: Bool) async throws -> RecordCopyPreview {+ guard let handler = recordCopyPreviewHandler else { throw MockError.notConfigured }+ return try await handler(sourceWorkID, destinationWorkID, selections, includeNotes)+ }+ func commitRecordCopy(_ preview: RecordCopyPreview) async throws -> RecordCopyOutcome {+ recorderLock.withLock { storedCopyCommits.append(preview) }+ let result = recordCopyCommitResult+ await recordCopyCommitHold?.wait()+ return try result.get()+ }+ func inspectRecordCopyOutcome(_ preview: RecordCopyPreview) async throws -> RecordCopyInspection {+ recorderLock.withLock { storedCopyInspections.append(preview) }+ let result = recordCopyInspectionResult+ await recordCopyInspectionHold?.wait()+ return try result.get()+ } var manualProjectionResult: Result<ChapterCaptureProjection, Error> = .failure(MockError.notConfigured) var manualCommitResult: Result<ChapterCaptureCommitOutcome, Error> = .failure(MockError.notConfigured) var manualCommitDrafts: [ManualEntryDraft] = []@@ -31,7 +94,21 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { /// The order calls arrived in, for the assertions counts cannot make — the /// diagnosis refresh has to run *before* the snapshot refresh, since Recent /// is built from the diagnoses (`AppLibraryModel.refreshDiagnosesAndSnapshots`).- var callLog: [String] = []+ /// All callers share this array, including asynchronous reloads and tests+ /// appending mutation markers. Hold the lock across an entire mutation:+ /// separate locked get/set would still lose concurrent append operations.+ /// This lock is separate because several writers already hold recorderLock.+ var callLog: [String] {+ get { callLogLock.withLock { storedCallLog } }+ set { callLogLock.withLock { storedCallLog = newValue } }+ _modify {+ callLogLock.lock()+ defer { callLogLock.unlock() }+ yield &storedCallLog+ }+ }+ private let callLogLock = NSLock()+ private var storedCallLog: [String] = [] var todayPresentationCallCount = 0 var prepareNoEpisodeNotesCallCount = 0@@ -244,6 +321,7 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { /// sequence refusing while its neighbours commit is what the position /// commits' stop-at-the-first-conflict rule is about. var updateWorkResultsByWorkID: [UUID: Result<LibraryWriteOutcome, Error>] = [:]+ var updateWorkHold: (@Sendable () async -> Void)? func updateWork( id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar@@ -253,6 +331,7 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { lastUpdateWorkCalendar = calendar lastUpdateWorkDraft = draft updateWorkCalls.append((id, basis, draft))+ await updateWorkHold?() return try (updateWorkResultsByWorkID[id] ?? updateWorkResult).get() } @@ -295,7 +374,10 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { var sitesCallCount = 0 var siteNamesCallCount = 0- var workDetailCallCount = 0+ var workDetailCallCount: Int {+ recorderLock.withLock { storedWorkDetailCallCount }+ }+ private var storedWorkDetailCallCount = 0 var entryExportInputCallCount = 0 var workExportInputCallCount = 0 var dayExportInputCallCount = 0@@ -538,8 +620,10 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { } func workDetail(id: UUID) async throws -> WorkDetailPresentation {- workDetailCallCount += 1- callLog.append("workDetail")+ recorderLock.withLock {+ storedWorkDetailCallCount += 1+ callLog.append("workDetail")+ } return try workDetailResult.get() }
diff --git a/Asterism/AsterismTests/RecordCopyNavigationTests.swift b/Asterism/AsterismTests/RecordCopyNavigationTests.swiftnew file mode 100644index 00000000..6fe5e8a0--- /dev/null+++ b/Asterism/AsterismTests/RecordCopyNavigationTests.swift@@ -0,0 +1,172 @@+import AsterismCore+import AsterismTestSupport+import Foundation+import Testing++@testable import Asterism++@Suite("Copy correction navigation")+@MainActor+struct RecordCopyNavigationTests {+ @Test(+ "Check Library appends on the originating stack and Back returns to its Work",+ arguments: [RouteStack.today, .works])+ func correctStack(_ stack: RouteStack) {+ let source = UUID()+ let other = UUID()+ let navigation = AppNavigation()+ navigation.todayPath = [.work(source)]+ navigation.worksPath = [.work(other)]+ let original = navigation.path(on: stack)+ let untouched = navigation.path(on: stack == .today ? .works : .today)+ navigation.showCheckLibrary(on: stack)+ #expect(navigation.path(on: stack) == original + [.diagnostics])+ #expect(navigation.path(on: stack == .today ? .works : .today) == untouched)+ #expect(!navigation.showingDiagnostics)+ navigation.showCheckLibrary(on: stack)+ #expect(navigation.path(on: stack).count == original.count + 1)+ if stack == .today {+ navigation.todayPath.removeLast()+ } else {+ navigation.worksPath.removeLast()+ }+ #expect(navigation.path(on: stack) == original)+ }++ @Test("Typed correction route preserves existing work identity through ordinary path encoding")+ func correctionRouteEncoding() {+ let id = UUID()+ let path: [WorksRoute] = [.work(id), .diagnostics]+ #expect(AppNavigation.decodePath(AppNavigation.encodePath(path)) == path)+ #expect(path[0].workID == id && path[1].workID == nil)+ }++ @Test(+ "Navigation-owned suspended review survives intentional diagnostics and wide host recreation",+ arguments: [RouteStack.today, .works])+ func retainedCorrectionHost(_ stack: RouteStack) {+ let id = UUID()+ let navigation = AppNavigation()+ navigation.selectedTab = stack == .today ? .today : .works+ navigation.showWork(id, on: stack)+ let host = navigation.recordCopyReviewHost(for: id, on: stack)+ let copy = WorkRecordCopyModel(sourceWorkID: id, library: MockLibraryProvider(), onMutation: {})+ copy.suspendForResolution()+ host.suspendedModel = copy+ host.isVisitingResolution = true+ navigation.showCheckLibrary(on: stack)+ #expect(copy.state == .suspended && host.suspendedModel === copy)+ navigation.back()+ let recreated = navigation.recordCopyReviewHost(for: id, on: stack)+ #expect(recreated === host && recreated.suspendedModel === copy)+ }++ @Test(+ "Opening another Work from correction keeps its stack and retires the old host",+ arguments: [RouteStack.today, .works])+ func anotherWorkRetiresHost(_ stack: RouteStack) {+ let id = UUID()+ let destination = UUID()+ let navigation = AppNavigation()+ navigation.selectedTab = stack == .today ? .today : .works+ navigation.showWork(id, on: stack)+ let host = navigation.recordCopyReviewHost(for: id, on: stack)+ let copy = WorkRecordCopyModel(sourceWorkID: id, library: MockLibraryProvider(), onMutation: {})+ copy.suspendForResolution()+ host.suspendedModel = copy+ host.isVisitingResolution = true+ navigation.showCheckLibrary(on: stack)+ navigation.showWork(destination, on: stack)+ #expect(navigation.path(on: stack) == [.work(destination)])+ #expect(navigation.selectedTab == (stack == .today ? .today : .works))+ #expect(host.suspendedModel == nil && copy.state == .closed)+ }++ @Test(+ "Tab departure and unrelated route changes discard suspended review",+ arguments: ["tab", "series", "empty"])+ func unrelatedNavigationDiscards(_ mode: String) {+ let id = UUID()+ let navigation = AppNavigation()+ navigation.showWork(id)+ let host = navigation.recordCopyReviewHost(for: id, on: .works)+ let copy = WorkRecordCopyModel(sourceWorkID: id, library: MockLibraryProvider(), onMutation: {})+ copy.suspendForResolution()+ host.suspendedModel = copy+ host.isVisitingResolution = true+ navigation.showCheckLibrary(on: .works)+ switch mode {+ case "tab": navigation.selectedTab = .stats+ case "series": navigation.showSeries(UUID())+ default: navigation.worksPath = []+ }+ #expect(host.suspendedModel == nil && copy.state == .closed)+ }++ @Test("Late resume cannot present after source navigation retires the owning host")+ func lateResumeRetiredHost() async throws {+ let source = TestFixtures.makeWork(displayTitle: "Original", memberships: [])+ let mock = MockLibraryProvider()+ let navigation = AppNavigation()+ mock.recordCopyContextResult = .success(+ .init(source: .init(work: source, unavailableReason: nil), destinations: [], records: []))+ mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: source))+ let copy = WorkRecordCopyModel(sourceWorkID: source.id, library: mock, onMutation: {})+ await copy.start()+ copy.suspendForResolution()+ navigation.showWork(source.id)+ let host = navigation.recordCopyReviewHost(for: source.id, on: .works)+ host.suspendedModel = copy+ let reads = mock.recordCopyContextCallCount+ let gate = SubmissionGate()+ mock.recordCopyContextHold = gate+ let pending = Task { await host.resume() }+ defer {+ gate.open()+ pending.cancel()+ }+ for _ in 0..<10000 where mock.recordCopyContextCallCount == reads { await Task.yield() }+ try #require(mock.recordCopyContextCallCount == reads + 1)+ navigation.showWork(UUID())+ gate.open()+ #expect(await pending.value == nil)+ #expect(host.suspendedModel == nil && copy.state == .closed && mock.recordCopyCommits.isEmpty)+ }+ @Test("A Series offer review survives intentional correction and wide host recreation",+ arguments: [RouteStack.today, .works])+ func seriesCorrectionRetainsHost(_ stack: RouteStack) {+ let navigation = AppNavigation()+ navigation.selectedTab = stack == .today ? .today : .works+ let route = WorksRoute.series(id: UUID(), originWorkID: nil)+ if stack == .today { navigation.todayPath = [route] }+ else { navigation.worksPath = [route] }+ let host = navigation.recordCopyReviewHost(for: route, on: stack)+ let copy = WorkRecordCopyModel(sourceWorkID: UUID(), library: MockLibraryProvider(), onMutation: {})+ copy.suspendForResolution()+ host.suspendedModel = copy+ host.isVisitingResolution = true+ navigation.showCheckLibrary(on: stack)+ #expect(navigation.path(on: stack) == [route, .diagnostics])+ navigation.back()+ #expect(navigation.recordCopyReviewHost(for: route, on: stack) === host)+ #expect(host.suspendedModel === copy && copy.state == .suspended)+ }++ @Test("Reader departure retires a Series-owned copy session",+ arguments: ["tab", "work"])+ func seriesDepartureRetiresHost(_ mode: String) {+ let navigation = AppNavigation()+ navigation.selectedTab = .works+ let route = WorksRoute.series(id: UUID(), originWorkID: nil)+ navigation.worksPath = [route]+ let host = navigation.recordCopyReviewHost(for: route, on: .works)+ let copy = WorkRecordCopyModel(sourceWorkID: UUID(), library: MockLibraryProvider(), onMutation: {})+ copy.suspendForResolution(); host.suspendedModel = copy+ host.isVisitingResolution = true+ navigation.showCheckLibrary(on: .works)+ if mode == "tab" { navigation.selectedTab = .stats }+ else { navigation.showWork(UUID()) }+ #expect(host.suspendedModel == nil && copy.state == .closed)+ }++}
diff --git a/Asterism/AsterismTests/RecordCopyOfferCoordinatorTests.swift b/Asterism/AsterismTests/RecordCopyOfferCoordinatorTests.swiftnew file mode 100644index 00000000..44f4e69f--- /dev/null+++ b/Asterism/AsterismTests/RecordCopyOfferCoordinatorTests.swift@@ -0,0 +1,323 @@+import AsterismCore+import AsterismTestSupport+import Foundation+import Testing++@testable import Asterism++@Suite("Save-scoped record copy offers")+@MainActor+struct RecordCopyOfferCoordinatorTests {+ private func offer(+ destinationID: UUID = UUID(), sourceID: UUID = UUID(), seriesID: UUID = UUID(),+ tied: Bool = false+ ) -> RecordCopySeriesOffer {+ RecordCopyOfferTestFixtures.offer(+ destinationID: destinationID, sourceID: sourceID, seriesID: seriesID, tied: tied)+ }++ private func join(_ offer: RecordCopySeriesOffer, addressed: [UUID]? = nil)+ -> WorkMembershipTransition+ {+ .init(+ addressedWorkIDs: addressed ?? [offer.destination.id], resolvedWorkID: offer.destination.id,+ before: nil, after: offer.destination.work.membership)+ }+ private func sut(_ offers: [RecordCopySeriesOffer]) -> (+ RecordCopyOfferCoordinator, MockLibraryProvider+ ) {+ let mock = MockLibraryProvider()+ for offer in offers {+ mock.recordCopyOfferResultByDestinationID[offer.destination.id] = .success(offer)+ }+ return (RecordCopyOfferCoordinator(library: mock, onMutation: {}), mock)+ }++ @Test("Only explicit confirmed reader join events produce a review, never copying or selections")+ func confirmedJoinOnly() async {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ #expect(coordinator.offers.isEmpty && mock.recordCopyOfferCalls.isEmpty)+ await coordinator.enqueue(eventID: UUID(), transitions: [join(projection)])+ #expect(coordinator.offers.count == 1 && coordinator.copyModel == nil)+ await coordinator.review()+ #expect(+ coordinator.copyModel?.selectedIdentities.isEmpty == true && mock.recordCopyCommits.isEmpty)+ }++ @Test("A failed optional offer read leaves a nonblocking notice after the event retires")+ func failedOfferReadKeepsNotice() async {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ mock.recordCopyOfferResultByDestinationID[projection.destination.id] =+ .failure(MockLibraryProvider.MockError.notConfigured)+ let event = UUID()+ await coordinator.enqueue(eventID: event, transitions: [join(projection)])+ #expect(!coordinator.hasOffer && coordinator.eventID == nil)+ #expect(coordinator.offerReadNotice != nil && coordinator.message == nil)+ #expect(mock.recordCopyCommits.isEmpty)+ await coordinator.enqueue(eventID: event, transitions: [join(projection)])+ #expect(mock.recordCopyOfferCalls.count == 1 && coordinator.offerReadNotice != nil)+ coordinator.cancelHost()+ #expect(coordinator.offerReadNotice == nil)+ }++ @Test("A partial batch and automatic destination selection preserve its read notice")+ func partialBatchKeepsNotice() async {+ let available = offer()+ let unavailable = offer(seriesID: available.series.id)+ let (coordinator, mock) = sut([available, unavailable])+ mock.recordCopyOfferResultByDestinationID[unavailable.destination.id] =+ .failure(MockLibraryProvider.MockError.notConfigured)+ await coordinator.enqueue(+ eventID: UUID(), transitions: [join(available), join(unavailable)])+ #expect(coordinator.offers.count == 1)+ #expect(coordinator.selectedDestinationID == available.destination.id)+ #expect(coordinator.offerReadNotice != nil && coordinator.copyModel == nil)+ #expect(mock.recordCopyCommits.isEmpty)+ coordinator.selectDestination(available.destination.id)+ #expect(coordinator.offerReadNotice != nil)+ mock.recordCopyOfferResultByDestinationID[available.destination.id] =+ .failure(MockLibraryProvider.MockError.notConfigured)+ #expect(await coordinator.prepareForPresentation() == false)+ #expect(!coordinator.hasOffer && coordinator.offerReadNotice != nil)+ }++ @Test("Same-series edits and leaving a series create no offer reads")+ func nonJoinReceiptsOmit() async {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ let membership = projection.destination.work.membership+ await coordinator.enqueue(+ eventID: UUID(),+ transitions: [+ .init(+ addressedWorkIDs: [projection.destination.id], resolvedWorkID: projection.destination.id,+ before: membership, after: membership),+ .init(+ addressedWorkIDs: [projection.destination.id], resolvedWorkID: projection.destination.id,+ before: membership, after: nil),+ ])+ #expect(coordinator.offers.isEmpty && mock.recordCopyOfferCalls.isEmpty)+ }++ @Test("Decline consumes the save event; repeated callbacks cannot recreate it")+ func consumedEventCannotReopen() async {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ let event = UUID()+ await coordinator.enqueue(eventID: event, transitions: [join(projection)])+ coordinator.consume()+ await coordinator.enqueue(eventID: event, transitions: [join(projection)])+ #expect(coordinator.offers.isEmpty && mock.recordCopyOfferCalls.count == 1)+ }++ @Test("A deliberate later leave/rejoin is a new event and can offer again")+ func newEventCanOfferAgain() async {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ await coordinator.enqueue(eventID: UUID(), transitions: [join(projection)])+ coordinator.consume()+ await coordinator.enqueue(eventID: UUID(), transitions: [join(projection)])+ #expect(coordinator.offers.count == 1 && mock.recordCopyOfferCalls.count == 2)+ }++ @Test("A tied bucket requires explicit choice even with only one available source")+ func tiedUnavailablePeerRequiresChoice() async {+ let projection = offer(tied: true)+ let (coordinator, _) = sut([projection])+ await coordinator.enqueue(eventID: UUID(), transitions: [join(projection)])+ #expect(+ coordinator.selectedSourceID == nil+ && coordinator.selectedOffer?.unavailablePredecessors.count == 1)+ await coordinator.review()+ #expect(coordinator.copyModel == nil)+ coordinator.selectSource(projection.sources[0].id)+ await coordinator.review()+ #expect(coordinator.copyModel != nil)+ }++ @Test("Batch joins deduplicate resolved identities; closing one review consumes the whole batch")+ func batchResolvedIDsAndDismissal() async {+ let first = offer()+ let second = offer()+ let (coordinator, mock) = sut([first, second])+ await coordinator.enqueue(+ eventID: UUID(),+ transitions: [join(first, addressed: [UUID(), UUID()]), join(first), join(second)])+ #expect(coordinator.offers.count == 2 && mock.recordCopyOfferCalls.count == 2)+ coordinator.selectDestination(first.destination.id)+ await coordinator.review()+ #expect(coordinator.copyModel != nil)+ coordinator.consume()+ #expect(+ coordinator.offers.isEmpty && coordinator.copyModel == nil && mock.recordCopyCommits.isEmpty)+ }++ @Test("Changed unique predecessor refreshes its visible suggestion and requires a new Review tap")+ func changedPredecessorRequiresNewReview() async {+ let before = offer()+ let after = offer(destinationID: before.destination.id, seriesID: before.series.id)+ let (coordinator, mock) = sut([before])+ await coordinator.enqueue(eventID: UUID(), transitions: [join(before)])+ mock.recordCopyOfferResultByDestinationID[before.destination.id] = .success(after)+ await coordinator.review()+ #expect(coordinator.copyModel == nil && coordinator.message != nil)+ #expect(coordinator.selectedOffer?.sources[0].id == after.sources[0].id)+ await coordinator.review()+ #expect(coordinator.copyModel != nil && mock.recordCopyCommits.isEmpty)+ }++ @Test("Destination leaving the series removes its old offer without selecting an older source")+ func changedMembershipDropsOffer() async {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ await coordinator.enqueue(eventID: UUID(), transitions: [join(projection)])+ mock.recordCopyOfferResultByDestinationID[projection.destination.id] = .success(nil)+ await coordinator.review()+ #expect(coordinator.offers.isEmpty && coordinator.copyModel == nil)+ }++ @Test("A late offer read cannot reopen a departed host")+ func lateReadCannotReopen() async throws {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ let gate = SubmissionGate()+ mock.recordCopyOfferHold = gate+ let task = Task { await coordinator.enqueue(eventID: UUID(), transitions: [join(projection)]) }+ defer {+ gate.open()+ task.cancel()+ }+ for _ in 0..<10000 where mock.recordCopyOfferCalls.isEmpty { await Task.yield() }+ try #require(mock.recordCopyOfferCalls.count == 1)+ coordinator.cancelHost()+ gate.open()+ await task.value+ #expect(coordinator.offers.isEmpty && coordinator.eventID == nil)+ }++ @Test(+ "Order changes after explicit entry into copying do not swap the deliberately chosen source")+ func enteredCopyIsExplicitChoice() async {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ await coordinator.enqueue(eventID: UUID(), transitions: [join(projection)])+ await coordinator.review()+ let copy = coordinator.copyModel+ mock.recordCopyOfferResultByDestinationID[projection.destination.id] = .success(nil)+ await coordinator.review()+ #expect(coordinator.copyModel === copy && mock.recordCopyOfferCalls.count == 2)+ }+ @Test("A new saved addition waits for an owned in-flight copy and is not consumed")+ func newSaveWaitsForInFlightCopy() async throws {+ let first = offer()+ let second = offer()+ let (coordinator, mock) = sut([first, second])+ let record = RecordCopyRecord(id: UUID(), kind: .character, name: "Ada")+ mock.recordCopyContextResult = .success(.init(+ source: first.sources[0], destinations: [first.destination], records: [record]))+ mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: first.sources[0].work))+ mock.recordCopyPreviewHandler = { source, destination, selections, notes in+ let rows = selections.map { selection in+ RecordCopyPlannedRow(sourceID: selection.sourceID, destinationID: selection.destinationID,+ kind: selection.kind, payload: .init(record: record, includeNotes: notes),+ choice: .copy, informationalClashes: [])+ }+ return .init(sourceWorkID: source, destinationWorkID: destination, includeNotes: notes,+ rows: rows, basis: .init(sourceSeriesID: first.series.id,+ destinationSeriesID: first.series.id, directlyLinked: false,+ selected: [record], destination: []))+ }+ await coordinator.enqueue(eventID: UUID(), transitions: [join(first)])+ await coordinator.review()+ let copy = try #require(coordinator.copyModel)+ await copy.start()+ await copy.toggleSelection(record.identity)+ try #require(copy.canAccept)+ let gate = SubmissionGate()+ mock.recordCopyCommitHold = gate+ mock.recordCopyCommitResult = .success(.refused(reason: "Refresh"))+ let submission = Task { await copy.accept() }+ defer { gate.open(); submission.cancel() }+ for _ in 0..<10000 where mock.recordCopyCommits.isEmpty { await Task.yield() }+ try #require(mock.recordCopyCommits.count == 1)+ let laterEvent = UUID()+ await coordinator.enqueue(eventID: laterEvent, transitions: [join(second)])+ coordinator.consume()+ #expect(coordinator.copyModel === copy && copy.isSubmitting)+ #expect(mock.recordCopyOfferCalls.count == 2)+ gate.open()+ await submission.value+ coordinator.consume()+ await coordinator.advanceDeferredEvents()+ #expect(coordinator.eventID == laterEvent)+ #expect(coordinator.selectedDestinationID == second.destination.id)+ #expect(mock.recordCopyOfferCalls.count == 3 && mock.recordCopyCommits.count == 1)+ }++ @Test("An offer awaiting its reader keeps its identity while a distinct saved event waits")+ func visibleOfferQueuesNewEvent() async {+ let first = offer(); let second = offer()+ let (coordinator, mock) = sut([first, second])+ let originalEvent = UUID(); let laterEvent = UUID()+ await coordinator.enqueue(eventID: originalEvent, transitions: [join(first)])+ await coordinator.enqueue(eventID: laterEvent, transitions: [join(second)])+ await coordinator.enqueue(eventID: laterEvent, transitions: [join(second)])+ #expect(coordinator.eventID == originalEvent)+ #expect(coordinator.selectedDestinationID == first.destination.id)+ #expect(mock.recordCopyOfferCalls.count == 1)+ coordinator.consume()+ await coordinator.advanceDeferredEvents()+ #expect(coordinator.eventID == laterEvent && coordinator.selectedDestinationID == second.destination.id)+ #expect(mock.recordCopyOfferCalls.count == 2)+ coordinator.consume()+ await coordinator.advanceDeferredEvents()+ #expect(coordinator.eventID == nil && mock.recordCopyOfferCalls.count == 2)+ }++ @Test("An empty first projection retires immediately and admits its queued event once")+ func emptyProjectionAdvancesDeferredEvent() async throws {+ let first = offer(); let second = offer()+ let (coordinator, mock) = sut([first, second])+ mock.recordCopyOfferResultByDestinationID[first.destination.id] = .success(nil)+ let gate = SubmissionGate(); mock.recordCopyOfferHold = gate+ let originalEvent = UUID(); let laterEvent = UUID()+ let initial = Task { await coordinator.enqueue(eventID: originalEvent, transitions: [join(first)]) }+ defer { gate.open(); initial.cancel() }+ for _ in 0..<10000 where mock.recordCopyOfferCalls.isEmpty { await Task.yield() }+ try #require(mock.recordCopyOfferCalls.count == 1)+ await coordinator.enqueue(eventID: laterEvent, transitions: [join(second)])+ await coordinator.enqueue(eventID: laterEvent, transitions: [join(second)])+ gate.open(); await initial.value+ #expect(coordinator.eventID == laterEvent && coordinator.selectedDestinationID == second.destination.id)+ #expect(mock.recordCopyOfferCalls.count == 2)+ coordinator.consume()+ await coordinator.enqueue(eventID: originalEvent, transitions: [join(first)])+ #expect(coordinator.eventID == nil && mock.recordCopyOfferCalls.count == 2)+ }++ @Test("Leaving the host consumes queued event identities so delayed callbacks cannot reopen them")+ func cancelledDeferredCallbackCannotReopen() async {+ let first = offer(); let second = offer()+ let (coordinator, mock) = sut([first, second])+ await coordinator.enqueue(eventID: UUID(), transitions: [join(first)])+ let deferredID = UUID()+ await coordinator.enqueue(eventID: deferredID, transitions: [join(second)])+ coordinator.cancelHost()+ await coordinator.enqueue(eventID: deferredID, transitions: [join(second)])+ #expect(coordinator.offers.isEmpty && coordinator.eventID == nil)+ #expect(mock.recordCopyOfferCalls.count == 1)+ }++ @Test("A destination leaving while the presenter is obstructed drops the offer")+ func delayedPresentationRechecksMembership() async {+ let projection = offer()+ let (coordinator, mock) = sut([projection])+ await coordinator.enqueue(eventID: UUID(), transitions: [join(projection)])+ mock.recordCopyOfferResultByDestinationID[projection.destination.id] = .success(nil)+ #expect(await coordinator.prepareForPresentation() == false)+ #expect(coordinator.offers.isEmpty && coordinator.copyModel == nil)+ }++}
diff --git a/Asterism/AsterismTests/RecordCopyOfferTestFixtures.swift b/Asterism/AsterismTests/RecordCopyOfferTestFixtures.swiftnew file mode 100644index 00000000..53df012f--- /dev/null+++ b/Asterism/AsterismTests/RecordCopyOfferTestFixtures.swift@@ -0,0 +1,52 @@+import AsterismCore+import AsterismTestSupport+import Foundation++nonisolated enum RecordCopyOfferTestFixtures {+ static func offer(+ destinationID: UUID = UUID(), sourceID: UUID = UUID(), seriesID: UUID = UUID(),+ tied: Bool = false+ ) -> RecordCopySeriesOffer {+ let source = TestFixtures.makeWork(+ id: sourceID, displayTitle: "Earlier book", memberships: [],+ membership: .init(seriesID: seriesID, position: 1))+ let destination = TestFixtures.makeWork(+ id: destinationID, displayTitle: "Added book", memberships: [],+ membership: .init(seriesID: seriesID, position: 2))+ let series = SeriesDisplay(id: seriesID, name: "Cycle", createdAt: TestFixtures.fixedDate)+ let unavailable = TestFixtures.makeWork(+ displayTitle: "Empty tied peer", memberships: [],+ membership: .init(seriesID: seriesID, position: 1))+ let members =+ [+ RecordCopyOfferMember(+ work: .init(id: source.id, title: source.displayTitle, membership: source.membership),+ eligibleRecordCount: 1),+ RecordCopyOfferMember(+ work: .init(+ id: destination.id, title: destination.displayTitle, membership: destination.membership),+ eligibleRecordCount: 1),+ ]+ + (tied+ ? [+ .init(+ work: .init(+ id: unavailable.id, title: unavailable.displayTitle,+ membership: unavailable.membership), eligibleRecordCount: 0)+ ] : [])+ return .init(+ destination: .init(work: destination, unavailableReason: nil), series: series,+ sources: [.init(work: source, unavailableReason: nil)],+ unavailablePredecessors: tied+ ? [.init(work: unavailable, unavailableReason: "No available characters or places")] : [],+ basis: RecordCopyOfferPlanning.predecessor(+ destinationID: destination.id, seriesID: seriesID, members: members)!)+ }+ static func join(_ offer: RecordCopySeriesOffer, addressed: [UUID]? = nil)+ -> WorkMembershipTransition+ {+ .init(+ addressedWorkIDs: addressed ?? [offer.destination.id], resolvedWorkID: offer.destination.id,+ before: nil, after: offer.destination.work.membership)+ }+}
diff --git a/Asterism/AsterismTests/SeriesRecordCopyOfferTests.swift b/Asterism/AsterismTests/SeriesRecordCopyOfferTests.swiftnew file mode 100644index 00000000..2559c515--- /dev/null+++ b/Asterism/AsterismTests/SeriesRecordCopyOfferTests.swift@@ -0,0 +1,134 @@+import AsterismCore+import AsterismTestSupport+import Foundation+import Testing++@testable import Asterism++@Suite("Series editor confirmed copy offers")+@MainActor+struct SeriesRecordCopyOfferTests {+ private func fixture(+ addressedIDs: [UUID]? = nil, onMutation: @escaping @Sendable () async -> Void = {}+ ) -> (SeriesDetailModel, MockLibraryProvider, RecordCopySeriesOffer, [WorkSnapshot]) {+ let projection = RecordCopyOfferTestFixtures.offer()+ let ids = addressedIDs ?? [projection.destination.id]+ let candidates = ids.map {+ TestFixtures.makeWork(id: $0, displayTitle: "Addition", memberships: [])+ }+ let mock = MockLibraryProvider()+ mock.seriesDetailResult = .success(+ .init(display: projection.series, notes: "", members: [projection.sources[0].work]))+ mock.seriesMemberCandidatesResult = .success(+ candidates.map { .init(work: $0, unavailableReason: nil) })+ mock.nextSeriesPositionResult = .success(2)+ mock.seriesReceiptTransitions = [RecordCopyOfferTestFixtures.join(projection, addressed: ids)]+ mock.recordCopyOfferResultByDestinationID[projection.destination.id] = .success(projection)+ let model = SeriesDetailModel(+ seriesID: projection.series.id, originWorkID: nil, library: mock, onMutation: onMutation)+ return (model, mock, projection, candidates)+ }+ private func stage(_ model: SeriesDetailModel, _ candidates: [WorkSnapshot]) async {+ await model.load()+ model.beginEditing()+ await model.loadCandidates()+ for candidate in candidates { await model.addMember(candidate.id) }+ }++ @Test("Staged selection and Cancel do not read offers or write membership")+ func stagedAndCancelledHaveNoOffer() async {+ let (model, mock, _, candidates) = fixture()+ await stage(model, candidates)+ #expect(mock.committedSeriesEdits.isEmpty && mock.recordCopyOfferCalls.isEmpty)+ model.cancelEditing()+ #expect(+ mock.committedSeriesEdits.isEmpty && mock.recordCopyOfferCalls.isEmpty+ && model.recordCopyOffers.offers.isEmpty)+ }++ @Test("Saved addition uses addressed intent but offers against its resolved destination")+ func resolvedAdditionIntent() async {+ let addressed = UUID()+ let (model, mock, projection, candidates) = fixture(addressedIDs: [addressed])+ await stage(model, candidates)+ mock.seriesDetailResult = .success(+ .init(+ display: projection.series, notes: "",+ members: [projection.sources[0].work, projection.destination.work]))+ await model.save()+ #expect(!model.isEditing && mock.committedSeriesEdits.first?.members.first?.workID == addressed)+ #expect(+ mock.recordCopyOfferCalls.count == 1+ && mock.recordCopyOfferCalls.first?.destinationID == projection.destination.id)+ #expect(model.recordCopyOffers.offers.count == 1 && mock.recordCopyCommits.isEmpty)+ }++ @Test("Multiple addressed additions resolving to one survivor produce one batch destination")+ func redirectedAliasesDeduplicate() async {+ let (model, mock, projection, candidates) = fixture(addressedIDs: [UUID(), UUID()])+ await stage(model, candidates)+ mock.seriesDetailResult = .success(+ .init(+ display: projection.series, notes: "",+ members: [projection.sources[0].work, projection.destination.work]))+ await model.save()+ #expect(mock.committedSeriesEdits.first?.members.count == 2)+ #expect(mock.recordCopyOfferCalls.count == 1 && model.recordCopyOffers.offers.count == 1)+ }++ @Test(+ "No-op and position-only series saves create no join event", arguments: ["noop", "position"])+ func nonAdditionSavesDoNotOffer(_ mode: String) async {+ let (model, mock, projection, _) = fixture()+ await model.load()+ model.beginEditing()+ if mode == "position" { model.setPositionDraft("1.5", for: projection.sources[0].id) }+ mock.seriesReceiptTransitions = []+ await model.save()+ #expect(mock.recordCopyOfferCalls.isEmpty && model.recordCopyOffers.offers.isEmpty)+ }++ @Test("Failed series write preserves staged additions and emits nothing")+ func failedWriterDoesNotOffer() async {+ let (model, mock, _, candidates) = fixture()+ await stage(model, candidates)+ mock.commitSeriesEditsResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Save failed"))+ await model.save()+ #expect(model.isEditing && model.members.contains { $0.id == candidates[0].id })+ #expect(mock.recordCopyOfferCalls.isEmpty && model.recordCopyOffers.offers.isEmpty)+ }++ @Test(+ "A held committed callback cannot enqueue after host discard or borrow a new edit event",+ arguments: ["discard", "newEdit"])+ func lateCommittedCallbackRetired(_ mode: String) async throws {+ let (_, mock, projection, candidates) = fixture()+ let gate = SubmissionGate()+ let model = SeriesDetailModel(+ seriesID: projection.series.id, originWorkID: nil, library: mock,+ onMutation: {+ mock.callLog.append("held series committed callback")+ await gate.wait()+ })+ await stage(model, candidates)+ mock.seriesDetailResult = .success(+ .init(+ display: projection.series, notes: "",+ members: [projection.sources[0].work, projection.destination.work]))+ let task = Task { await model.save() }+ defer {+ gate.open()+ task.cancel()+ }+ for _ in 0..<10000 where !mock.callLog.contains("held series committed callback") {+ await Task.yield()+ }+ try #require(mock.callLog.contains("held series committed callback"))+ if mode == "discard" { model.discardRecordCopyOffers() } else { model.beginEditing() }+ gate.open()+ await task.value+ #expect(mock.recordCopyOfferCalls.isEmpty && model.recordCopyOffers.offers.isEmpty)+ if mode == "newEdit" { #expect(model.isEditing) }+ }+}
diff --git a/Asterism/AsterismTests/WorkDetailSeriesCopyOfferTests.swift b/Asterism/AsterismTests/WorkDetailSeriesCopyOfferTests.swiftnew file mode 100644index 00000000..3f8d8ba0--- /dev/null+++ b/Asterism/AsterismTests/WorkDetailSeriesCopyOfferTests.swift@@ -0,0 +1,228 @@+import AsterismCore+import AsterismTestSupport+import Foundation+import Testing++@testable import Asterism++@Suite("Work editor confirmed series copy offers")+@MainActor+struct WorkDetailSeriesCopyOfferTests {+ private func fixture(routeID: UUID? = nil) -> (+ WorkDetailModel, MockLibraryProvider, RecordCopySeriesOffer+ ) {+ let projection = RecordCopyOfferTestFixtures.offer()+ let work = TestFixtures.makeWork(+ id: projection.destination.id, displayTitle: "Added book", memberships: [])+ let mock = MockLibraryProvider()+ mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: work))+ mock.workResult = .success(work)+ mock.nextSeriesPositionResult = .success(2)+ mock.recordCopyOfferResultByDestinationID[work.id] = .success(projection)+ mock.updateWorkReceiptTransitions = [+ RecordCopyOfferTestFixtures.join(projection, addressed: [routeID ?? work.id])+ ]+ return (makeWorkDetailModel(workID: routeID ?? work.id, library: mock), mock, projection)+ }+ private func stageJoin(_ model: WorkDetailModel, _ offer: RecordCopySeriesOffer) async {+ await model.load()+ model.beginEditing()+ await model.selectSeries(offer.series.id)+ }++ @Test(+ "Metadata join followed by a later refusal queues nothing until terminal retry succeeds",+ arguments: ["record", "link"])+ func partialSaveThenRetry(_ step: String) async {+ let (model, mock, projection) = fixture()+ await stageJoin(model, projection)+ if step == "record" {+ model.addCharacter(named: "New reader record")+ mock.commitRecordEditsResult = .success(.refused(.workGone))+ } else {+ model.addLink(to: UUID(), type: "sequel")+ mock.commitLinkEditsResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Link refused"))+ }+ await model.commitEditing()+ #expect(+ model.isEditing && model.recordCopyOffers.offers.isEmpty && mock.recordCopyOfferCalls.isEmpty)+ #expect(mock.updateWorkCallCount == 1)+ mock.updateWorkReceiptTransitions = [+ .init(+ addressedWorkIDs: [projection.destination.id], resolvedWorkID: projection.destination.id,+ before: projection.destination.work.membership,+ after: projection.destination.work.membership)+ ]+ mock.commitRecordEditsResult = .success(.committed(recordIDs: []))+ mock.commitLinkEditsResult = .success(())+ await model.commitEditing()+ #expect(!model.isEditing && model.recordCopyOffers.offers.count == 1)+ #expect(mock.recordCopyOfferCalls.count == 1 && mock.recordCopyCommits.isEmpty)+ await model.commitEditing()+ #expect(mock.recordCopyOfferCalls.count == 1)+ }++ @Test(+ "Subsequent confirmed membership replaces, clears or preserves the pending join",+ arguments: ["same", "move", "leave"])+ func pendingTransitionPolicy(_ mode: String) async {+ let (model, mock, first) = fixture()+ await stageJoin(model, first)+ model.addCharacter(named: "Reader record")+ mock.commitRecordEditsResult = .success(.refused(.workGone))+ await model.commitEditing()+ let next: SeriesMembership?+ if mode == "move" {+ let second = RecordCopyOfferTestFixtures.offer(destinationID: first.destination.id)+ mock.recordCopyOfferResultByDestinationID[first.destination.id] = .success(second)+ next = second.destination.work.membership+ await model.selectSeries(second.series.id)+ } else if mode == "leave" {+ next = nil+ await model.selectSeries(nil)+ } else {+ next = first.destination.work.membership+ model.draftTitle = "A corrected title"+ }+ mock.updateWorkReceiptTransitions = [+ .init(+ addressedWorkIDs: [first.destination.id], resolvedWorkID: first.destination.id,+ before: first.destination.work.membership, after: next)+ ]+ mock.commitRecordEditsResult = .success(.committed(recordIDs: []))+ await model.commitEditing()+ #expect(!model.isEditing)+ if mode == "leave" {+ #expect(mock.recordCopyOfferCalls.isEmpty && model.recordCopyOffers.offers.isEmpty)+ } else {+ #expect(+ mock.recordCopyOfferCalls.count == 1+ && mock.recordCopyOfferCalls.first?.seriesID == next?.seriesID)+ }+ }++ @Test("Cancel after a partial editor save discards the offer intent without undoing membership")+ func cancellationDropsPendingIntent() async {+ let (model, mock, projection) = fixture()+ await stageJoin(model, projection)+ model.addCharacter(named: "Reader record")+ mock.commitRecordEditsResult = .success(.refused(.workGone))+ await model.commitEditing()+ model.cancelEditing()+ #expect(mock.updateWorkCallCount == 1 && mock.recordCopyOfferCalls.isEmpty && !model.isEditing)+ mock.commitRecordEditsResult = .success(.committed(recordIDs: []))+ model.beginEditing()+ mock.updateWorkReceiptTransitions = []+ await model.commitEditing()+ #expect(mock.recordCopyOfferCalls.isEmpty)+ }++ @Test("No-op and unrelated metadata edits never manufacture a membership event")+ func ordinaryEditsDoNotOffer() async {+ let (model, mock, _) = fixture()+ mock.updateWorkReceiptTransitions = []+ await model.load()+ model.beginEditing()+ await model.commitEditing()+ #expect(mock.updateWorkCallCount == 0 && mock.recordCopyOfferCalls.isEmpty)+ model.beginEditing()+ model.draftTitle = "New title"+ await model.commitEditing()+ #expect(mock.updateWorkCallCount == 1 && mock.recordCopyOfferCalls.isEmpty)+ await model.load()+ #expect(mock.recordCopyOfferCalls.isEmpty)+ }++ @Test("A failed metadata write creates no offer receipt and keeps the editor")+ func failedMetadataDoesNotOffer() async {+ let (model, mock, projection) = fixture()+ await stageJoin(model, projection)+ mock.updateWorkResult = .failure(MockLibraryProvider.MockError.simulatedFailure("Save failed"))+ await model.commitEditing()+ #expect(+ model.isEditing && mock.recordCopyOfferCalls.isEmpty && model.recordCopyOffers.offers.isEmpty)+ }++ @Test("Redirected metadata receipt offers against the actual resolved destination")+ func resolvedDestinationReceipt() async {+ let old = UUID()+ let (model, mock, projection) = fixture(routeID: old)+ await stageJoin(model, projection)+ await model.commitEditing()+ #expect(mock.updateWorkCalls.first?.id == old)+ #expect(mock.recordCopyOfferCalls.first?.destinationID == projection.destination.id)+ #expect(model.recordCopyOffers.offers.first?.destination.id == projection.destination.id)+ }++ @Test("The metadata helper outside an editor cannot recreate a Save completion event")+ func helperSaveOutsideEditorDoesNotOffer() async {+ let (model, mock, _) = fixture()+ await model.load()+ model.draftTitle = "Changed"+ await model.save()+ #expect(mock.updateWorkCallCount == 1 && mock.recordCopyOfferCalls.isEmpty)+ }++ @Test(+ "Host discard or a new edit during terminal follow-through cannot admit the old join",+ arguments: ["discard", "newEdit"])+ func lateTerminalCallbackDoesNotBorrowNewSession(_ mode: String) async throws {+ let (_, mock, projection) = fixture()+ let gate = SubmissionGate()+ let model = makeWorkDetailModel(+ workID: projection.destination.id, library: mock,+ onMutation: {+ mock.callLog.append("offer-test mutation")+ if mock.callLog.filter({ $0 == "offer-test mutation" }).count == 2 {+ mock.callLog.append("offer-test held terminal mutation")+ await gate.wait()+ }+ })+ await stageJoin(model, projection)+ model.addCharacter(named: "New reader record")+ let task = Task { await model.commitEditing() }+ defer {+ gate.open()+ task.cancel()+ }+ for _ in 0..<10000 where !mock.callLog.contains("offer-test held terminal mutation") {+ await Task.yield()+ }+ try #require(mock.callLog.contains("offer-test held terminal mutation"))+ if mode == "discard" { model.discardRecordCopyOffers() } else { model.beginEditing() }+ mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: projection.destination.work))+ gate.open()+ await task.value+ #expect(mock.recordCopyOfferCalls.isEmpty && model.recordCopyOffers.offers.isEmpty)+ if mode == "newEdit" { #expect(model.isEditing) }+ }+ @Test("Confirmed leave followed by record refusal can explicitly rejoin the original series")+ func leaveThenRejoinAfterRefusal() async {+ let (model, mock, projection) = fixture()+ let membership = projection.destination.work.membership+ let work = TestFixtures.makeWork(id: projection.destination.id,+ displayTitle: "Added book", memberships: [], membership: membership, series: projection.series)+ mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: work))+ mock.workResult = .success(work)+ await model.load()+ model.beginEditing()+ await model.selectSeries(nil)+ model.addCharacter(named: "Reader record")+ mock.updateWorkReceiptTransitions = [.init(addressedWorkIDs: [work.id],+ resolvedWorkID: work.id, before: membership, after: nil)]+ mock.commitRecordEditsResult = .success(.refused(.workGone))+ await model.commitEditing()+ #expect(model.isEditing && mock.updateWorkCallCount == 1)+ await model.selectSeries(projection.series.id)+ #expect(model.hasUnsavedChanges)+ mock.updateWorkReceiptTransitions = [.init(addressedWorkIDs: [work.id],+ resolvedWorkID: work.id, before: nil, after: membership)]+ mock.commitRecordEditsResult = .success(.committed(recordIDs: []))+ await model.commitEditing()+ #expect(mock.updateWorkCallCount == 2 && !model.isEditing)+ #expect(mock.recordCopyOfferCalls.count == 1)+ #expect(mock.updateWorkCalls.last?.basis.membership == nil)+ }++}
diff --git a/Asterism/AsterismTests/WorkDetailThumbnailTests.swift b/Asterism/AsterismTests/WorkDetailThumbnailTests.swiftindex 2213ef0a..8737ba17 100644--- a/Asterism/AsterismTests/WorkDetailThumbnailTests.swift+++ b/Asterism/AsterismTests/WorkDetailThumbnailTests.swift@@ -500,16 +500,267 @@ struct WorkDetailThumbnailTests { // MARK: - Helpers + @Test("Dropped image providers open crop without writing, and crop Cancel preserves the saved cover")+ @MainActor func droppedImageUsesCropAndSave() async throws {+ let (model, mock) = makeSUT(thumbnail: Self.storedIdentity)+ await model.load(); model.beginEditing()+ let bytes = try #require(jpegBytes(width: 600, height: 600))+ let provider = NSItemProvider(item: bytes as NSData, typeIdentifier: UTType.jpeg.identifier)+ #expect(await model.acceptDroppedProviders([provider]))+ #expect(model.pendingCrop != nil && model.thumbnailMessage == nil)+ #expect(model.draftThumbnail == .stored(Self.storedIdentity) && mock.updateWorkCallCount == 0)+ model.cancelCrop()+ #expect(model.draftThumbnail == .stored(Self.storedIdentity))+ #expect(await model.acceptDroppedProviders([provider]))+ let crop = try #require(model.pendingCrop)+ let draft = Self.makeDraft()+ await model.acceptCroppedThumbnail(draft, token: crop.id)+ #expect(mock.updateWorkCallCount == 0)+ await model.save()+ #expect(mock.lastUpdateWorkDraft?.thumbnail == .set(draft))+ }++ @Test("A generic image representation opens crop without writing", arguments: [false, true])+ @MainActor func droppedGenericImageRepresentation(temporary: Bool) async throws {+ let (model, mock) = makeSUT(thumbnail: Self.storedIdentity)+ await model.load(); model.beginEditing()+ let bytes = try #require(jpegBytes(width: 800, height: 1_200, format: .png))+ let provider = NSItemProvider()+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("generic-cover-drop-\(UUID()).png")+ defer { try? FileManager.default.removeItem(at: url) }+ if temporary {+ try bytes.write(to: url)+ provider.registerFileRepresentation(forTypeIdentifier: UTType.image.identifier, fileOptions: [], visibility: .all) { completion in+ completion(url, false, nil)+ try? FileManager.default.removeItem(at: url)+ return nil+ }+ } else {+ provider.registerDataRepresentation(forTypeIdentifier: UTType.image.identifier, visibility: .all) { completion in+ completion(bytes, nil); return nil+ }+ }+ #expect(provider.registeredTypeIdentifiers == [UTType.image.identifier])+ #expect(!provider.hasItemConformingToTypeIdentifier(UTType.png.identifier))+ let loading = try #require(model.beginCoverDrop([provider]))+ #expect(await loading.value)+ let image = try #require(model.pendingCrop?.image)+ #expect(image.width == 800 && image.height == 1_200)+ #expect(model.draftThumbnail == .stored(Self.storedIdentity))+ #expect(model.thumbnailMessage == nil && mock.updateWorkCallCount == 0)+ }++ @Test("An unsupported concrete image drop preserves the current crop and guidance", arguments: [UTType.tiff, .bmp])+ @MainActor func concreteUnsupportedImagePreservesSession(format: UTType) async throws {+ let (model, mock) = makeSUT(thumbnail: Self.storedIdentity)+ await model.load(); model.beginEditing()+ let token = model.beginThumbnailPick()+ model.acceptPickedImage(try #require(jpegBytes(width: 600, height: 900)), token: token, source: .file)+ let provider = NSItemProvider(item: try #require(jpegBytes(width: 600, height: 900, format: format)) as NSData, typeIdentifier: format.identifier)+ #expect(provider.registeredTypeIdentifiers == [format.identifier])+ #expect(provider.hasItemConformingToTypeIdentifier(UTType.image.identifier))+ #expect(model.beginCoverDrop([provider]) == nil)+ #expect(!(await model.acceptDroppedProviders([provider])))+ #expect(model.thumbnailSessionToken == token && model.pendingCrop?.id == token)+ #expect(model.thumbnailMessage == nil && model.draftThumbnail == .stored(Self.storedIdentity))+ #expect(mock.updateWorkCallCount == 0)+ }++ @Test("Generic image advertisement cannot bypass the supported encoded formats", arguments: [UTType.tiff, .bmp])+ @MainActor func genericImageRejectsUnsupportedBytes(format: UTType) async throws {+ let (model, mock) = makeSUT(thumbnail: Self.storedIdentity)+ await model.load(); model.beginEditing()+ let bytes = try #require(jpegBytes(width: 600, height: 900, format: format))+ let provider = NSItemProvider(item: bytes as NSData, typeIdentifier: UTType.image.identifier)+ let loading = try #require(model.beginCoverDrop([provider]))+ #expect(await loading.value)+ #expect(model.pendingCrop == nil && model.draftThumbnail == .stored(Self.storedIdentity))+ #expect(model.thumbnailMessage == "That file could not be read as an image.")+ #expect(mock.updateWorkCallCount == 0)+ }++ @Test("An undecodable representation and provider do not mask the next usable image")+ @MainActor func droppedRepresentationFallback() async throws {+ let (model, _) = makeSUT()+ await model.load(); model.beginEditing()+ let bytes = try #require(jpegBytes(width: 800, height: 1_200, format: .png))+ let bad = NSItemProvider(item: Data([0xFF]) as NSData, typeIdentifier: UTType.jpeg.identifier)+ let fallback = NSItemProvider()+ fallback.registerDataRepresentation(forTypeIdentifier: UTType.jpeg.identifier, visibility: .all) { completion in+ completion(Data([0xFF]), nil); return nil+ }+ fallback.registerDataRepresentation(forTypeIdentifier: UTType.png.identifier, visibility: .all) { completion in+ completion(bytes, nil); return nil+ }+ let later = NSItemProvider(item: try #require(jpegBytes(width: 600, height: 600)) as NSData, typeIdentifier: UTType.jpeg.identifier)+ #expect(await model.acceptDroppedProviders([bad, fallback, later]))+ let image = try #require(model.pendingCrop?.image)+ #expect(image.width == 800 && image.height == 1_200)+ #expect(model.thumbnailMessage == nil)+ }++ @Test("Local file URLs and temporary image files are consumed within their provider lifetime", arguments: [false, true])+ @MainActor func droppedLocalFiles(temporary: Bool) async throws {+ let (model, _) = makeSUT()+ await model.load(); model.beginEditing()+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("cover-drop-\(UUID()).jpg")+ try #require(jpegBytes(width: 600, height: 900)).write(to: url)+ defer { try? FileManager.default.removeItem(at: url) }+ let provider: NSItemProvider+ if temporary {+ provider = NSItemProvider()+ provider.registerDataRepresentation(forTypeIdentifier: UTType.jpeg.identifier, visibility: .all) { completion in+ completion(nil, nil); return nil+ }+ provider.registerFileRepresentation(forTypeIdentifier: UTType.jpeg.identifier, fileOptions: [], visibility: .all) { completion in+ completion(url, false, nil)+ try? FileManager.default.removeItem(at: url)+ return nil+ }+ } else { provider = NSItemProvider(item: url as NSURL, typeIdentifier: UTType.fileURL.identifier) }+ #expect(await model.acceptDroppedProviders([provider]))+ #expect(model.pendingCrop?.image.width == 600 && model.thumbnailMessage == nil)+ }++ @Test("Unsupported and remote-only drops preserve the current crop and guidance")+ @MainActor func rejectedDropsPreserveSession() async throws {+ let (model, _) = makeSUT()+ await model.load(); model.beginEditing()+ let token = model.beginThumbnailPick()+ model.acceptPickedImage(try #require(jpegBytes(width: 600, height: 600)), token: token, source: .file)+ let remote = NSItemProvider(object: try #require(URL(string: "https://example.com/cover.jpg")) as NSURL)+ #expect(model.beginCoverDrop([remote, NSItemProvider(object: "text" as NSString)]) == nil)+ #expect(!(await model.acceptDroppedProviders([remote])))+ #expect(model.pendingCrop?.id == token && model.thumbnailSessionToken == token)+ #expect(model.thumbnailMessage == nil)+ }++ @Test("Accepted invalid image and unreadable file leave the draft intact with file guidance", arguments: [false, true])+ @MainActor func invalidDropsPreserveDraft(file: Bool) async throws {+ let (model, _) = makeSUT(thumbnail: Self.storedIdentity)+ await model.load(); model.beginEditing()+ let oldToken = model.beginThumbnailPick()+ model.acceptPickedImage(try #require(jpegBytes(width: 600, height: 600)), token: oldToken, source: .file)+ let provider = file+ ? NSItemProvider(item: URL(fileURLWithPath: "/nonexistent/\(UUID()).png") as NSURL, typeIdentifier: UTType.fileURL.identifier)+ : NSItemProvider(item: Data([0xFF]) as NSData, typeIdentifier: UTType.png.identifier)+ #expect(await model.acceptDroppedProviders([provider]))+ #expect(model.pendingCrop == nil && model.draftThumbnail == .stored(Self.storedIdentity))+ #expect(model.thumbnailSessionToken != oldToken)+ #expect(model.thumbnailMessage == "That file could not be read as an image.")+ }++ @Test("Late provider results cannot revive a crop or overwrite guidance after navigation, Cancel, Save or a newer pick", arguments: ["navigation", "cancel", "save", "newPick"], [false, true])+ @MainActor func staleDroppedProvider(action: String, invalid: Bool) async throws {+ let (model, _) = makeSUT()+ await model.load(); model.beginEditing()+ let bytes = invalid ? Data([0xFF]) : try #require(jpegBytes(width: 600, height: 600))+ let requested = SubmissionGate(), release = SubmissionGate()+ let provider = NSItemProvider()+ provider.registerDataRepresentation(forTypeIdentifier: UTType.jpeg.identifier, visibility: .all) { completion in+ Task { requested.open(); await release.wait(); completion(bytes, nil) }+ return nil+ }+ let loading = Task { await model.acceptDroppedProviders([provider]) }+ await requested.wait()+ switch action {+ case "navigation": model.retireThumbnailPresentation()+ case "cancel": model.cancelEditing()+ case "save": model.draftTitle = "Saved"; await model.save()+ default:+ let new = model.beginThumbnailPick()+ model.acceptPickedImage(Data([0xFF]), token: new, source: .photos)+ }+ let message = model.thumbnailMessage+ release.open(); _ = await loading.value+ #expect(model.pendingCrop == nil && model.thumbnailMessage == message)+ }++ @Test("A drop is refused outside editing and while Save is submitting")+ @MainActor func droppedSubmissionGuard() async throws {+ let (model, mock) = makeSUT()+ await model.load()+ let provider = NSItemProvider(item: try #require(jpegBytes(width: 600, height: 600)) as NSData, typeIdentifier: UTType.jpeg.identifier)+ #expect(!(await model.acceptDroppedProviders([provider])))+ model.beginEditing(); model.draftTitle = "Saved"+ let entered = SubmissionGate(), release = SubmissionGate()+ mock.updateWorkHold = { entered.open(); await release.wait() }+ let saving = Task { await model.save() }+ await entered.wait()+ #expect(model.beginCoverDrop([provider]) == nil)+ #expect(!(await model.acceptDroppedProviders([provider])))+ release.open(); await saving.value+ #expect(model.pendingCrop == nil)+ }++ @Test("A torn work refuses drops without changing its image session")+ @MainActor func readOnlyDropIsRefused() async throws {+ let (model, mock) = makeSUT()+ let work = TestFixtures.makeWork(id: model.workID, groupState: .torn(variants: [+ AuthoredVariant(content: WorkAuthoredContent(genericNotes: "one"), firstCapturedAt: TestFixtures.fixedDate),+ AuthoredVariant(content: WorkAuthoredContent(genericNotes: "two"), firstCapturedAt: TestFixtures.laterDate)+ ]))+ mock.workDetailResult = .success(TestFixtures.makeWorkDetail(work: work))+ await model.load(); model.beginEditing()+ let token = model.thumbnailSessionToken+ let provider = NSItemProvider(item: try #require(jpegBytes(width: 600, height: 600)) as NSData, typeIdentifier: UTType.jpeg.identifier)+ #expect(model.isReadOnly && model.beginCoverDrop([provider]) == nil)+ #expect(!(await model.acceptDroppedProviders([provider])))+ #expect(model.thumbnailSessionToken == token && model.pendingCrop == nil)+ }++ @Test("An admitted drop queued before navigation or a newer pick cannot adopt the replacement session", arguments: [false, true])+ @MainActor func queuedDropRetainsAdmissionToken(newPick: Bool) async throws {+ let (model, _) = makeSUT()+ await model.load(); model.beginEditing()+ let provider = NSItemProvider(item: try #require(jpegBytes(width: 600, height: 600)) as NSData, typeIdentifier: UTType.jpeg.identifier)+ let admitted = try #require(model.beginCoverDrop([provider]))+ // No suspension between admission and retirement: the queued main-actor+ // task cannot have begun loading the provider yet.+ if newPick {+ let replacement = model.beginThumbnailPick()+ model.acceptPickedImage(Data([0xFF]), token: replacement, source: .photos)+ } else { model.retireThumbnailPresentation() }+ let replacementToken = model.thumbnailSessionToken, message = model.thumbnailMessage+ #expect(!(await admitted.value))+ #expect(model.pendingCrop == nil && model.thumbnailMessage == message)+ #expect(model.thumbnailSessionToken == replacementToken)+ }++ @Test("The newest admitted drop wins over both queued and in-flight older providers", arguments: [false, true])+ @MainActor func newestAdmittedDropWins(inFlight: Bool) async throws {+ let (model, _) = makeSUT()+ await model.load(); model.beginEditing()+ let olderBytes = try #require(jpegBytes(width: 800, height: 1_200))+ let requested = SubmissionGate(), release = SubmissionGate()+ let older = NSItemProvider()+ older.registerDataRepresentation(forTypeIdentifier: UTType.jpeg.identifier, visibility: .all) { completion in+ Task { requested.open(); await release.wait(); completion(olderBytes, nil) }+ return nil+ }+ let newer = NSItemProvider(item: try #require(jpegBytes(width: 600, height: 600)) as NSData, typeIdentifier: UTType.jpeg.identifier)+ let oldTask = try #require(model.beginCoverDrop([older]))+ if inFlight { await requested.wait() }+ // In the queued case there is no suspension between the two admissions.+ let newTask = try #require(model.beginCoverDrop([newer]))+ #expect(await newTask.value)+ let newestToken = try #require(model.pendingCrop?.id)+ release.open(); _ = await oldTask.value+ #expect(model.pendingCrop?.id == newestToken)+ #expect(model.pendingCrop?.image.width == 600 && model.pendingCrop?.image.height == 600)+ #expect(model.thumbnailMessage == nil && model.draftThumbnail == .none)+ }+ /// Real JPEG bytes of a given size, for the decode paths. /// /// Written through ImageIO here rather than through `ThumbnailCodec.encode`, /// which only ever writes the two stored shapes: a source image the reader /// picks is any size at all, and one of these cases is about exactly that.- private func jpegBytes(width: Int, height: Int) -> Data? {+ private func jpegBytes(width: Int, height: Int, format: UTType = .jpeg) -> Data? { let image = Self.makeImage(width: width, height: height) let output = NSMutableData() guard let destination = CGImageDestinationCreateWithData(- output, UTType.jpeg.identifier as CFString, 1, nil)+ output, format.identifier as CFString, 1, nil) else { return nil } CGImageDestinationAddImage( destination, image,
diff --git a/Asterism/AsterismTests/WorkRecordCopyModelTests.swift b/Asterism/AsterismTests/WorkRecordCopyModelTests.swiftnew file mode 100644index 00000000..506acb80--- /dev/null+++ b/Asterism/AsterismTests/WorkRecordCopyModelTests.swift@@ -0,0 +1,574 @@+import AsterismCore+import AsterismTestSupport+import Foundation+import Testing++@testable import Asterism++@Suite("Work record copy session")+struct WorkRecordCopyModelTests {+ @MainActor private func fixture() -> (+ WorkRecordCopyModel, MockLibraryProvider, RecordCopyRecord, RecordCopyRecord+ ) {+ let source = TestFixtures.makeWork(displayTitle: "Book one", memberships: [])+ let destination = TestFixtures.makeWork(displayTitle: "Book two", memberships: [])+ let character = RecordCopyRecord(+ id: UUID(), kind: .character, name: "Ada", aliases: ["Nightjar"], note: "A secret")+ let place = RecordCopyRecord(id: UUID(), kind: .place, name: "Harbour", note: "A setting")+ let mock = MockLibraryProvider()+ mock.recordCopyContextResult = .success(+ .init(+ source: .init(work: source, unavailableReason: nil),+ destinations: [.init(work: destination, unavailableReason: nil)],+ records: [character, place]))+ mock.workDetailResult = .success(+ TestFixtures.makeWorkDetail(+ work: source,+ links: [+ .init(+ id: UUID(), otherWorkID: destination.id, otherTitle: destination.displayTitle,+ linkType: "sequel", modifiedAt: TestFixtures.fixedDate)+ ]))+ mock.recordCopyPreviewHandler = { sourceID, destinationID, selections, notes in+ let records = [character, place].filter { record in+ selections.contains { $0.sourceID == record.id && $0.kind == record.kind }+ }+ var rows = RecordCopyPlanning.initialPlan(+ selected: records, destination: [], includeNotes: notes)+ rows = rows.map { row in+ RecordCopyPlannedRow(+ sourceID: row.sourceID,+ destinationID: selections.first { $0.sourceID == row.sourceID && $0.kind == row.kind }!+ .destinationID, kind: row.kind, payload: row.payload, choice: row.choice,+ informationalClashes: row.informationalClashes)+ }+ return .init(+ sourceWorkID: sourceID, destinationWorkID: destinationID, includeNotes: notes, rows: rows,+ basis: .init(+ sourceSeriesID: nil, destinationSeriesID: nil, directlyLinked: true, selected: records,+ destination: []))+ }+ return (+ WorkRecordCopyModel(sourceWorkID: source.id, library: mock, onMutation: {}), mock, character,+ place+ )+ }++ @Test("Opening reads choices, labels direct eligibility, and selects nothing")+ @MainActor func opensWithoutSelection() async {+ let (model, mock, _, _) = fixture()+ await model.start()+ #expect(model.records.count == 2 && model.selectedIdentities.isEmpty)+ #expect(!model.includeNotes && !model.canAccept)+ #expect(model.relationshipLabel(for: model.destinations[0]) == "Linked work")+ #expect(mock.recordCopyCommits.isEmpty)+ }++ @Test("Scoped select all and clear preserve the other kind and planned IDs")+ @MainActor func kindSelectionAndStableIDs() async throws {+ let (model, _, character, place) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.selectAll(.character)+ await model.selectAll(.place)+ let id = try #require(model.preview?.rows.first { $0.kind == .place }?.destinationID)+ await model.clear(.character)+ #expect(model.selectedIdentities == [place.identity])+ #expect(model.preview?.rows.first?.destinationID == id)+ await model.toggleSelection(character.identity)+ #expect(model.preview?.rows.first { $0.kind == .place }?.destinationID == id)+ }++ @Test("Notes are opt in, previewed verbatim, and changing inclusion keeps UUIDs")+ @MainActor func noteOptionAndPayload() async throws {+ let (model, _, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ let id = try #require(model.preview?.rows.first?.destinationID)+ #expect(model.preview?.rows.first?.payload.note == "")+ await model.setIncludeNotes(true)+ #expect(model.preview?.rows.first?.payload.note == "A secret")+ #expect(model.preview?.rows.first?.payload.aliases == ["Nightjar"])+ #expect(model.preview?.rows.first?.destinationID == id)+ }++ @Test("Skip disables zero-result acceptance, cancellation writes nothing")+ @MainActor func skipAndCancel() async {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ model.setChoice(.skip, for: character.identity)+ #expect(!model.canAccept && model.plannedCount == 0)+ await model.accept()+ model.close()+ #expect(mock.recordCopyCommits.isEmpty && model.state == .closed)+ }++ @Test("Refusal keeps selection and requires a reviewed refresh")+ @MainActor func refusedCommitPreservesDraft() async {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ mock.recordCopyCommitResult = .success(.refused(reason: "Changed source"))+ await model.accept()+ #expect(model.selectedIdentities.contains(character.identity))+ #expect(model.message == "Changed source" && !model.canAccept)+ #expect(mock.recordCopyCommits.count == 1)+ await model.refreshPreview()+ #expect(model.canAccept)+ #expect(model.message == nil)+ }++ @Test("Committed copy is terminal and reports destination and both counts")+ @MainActor func successIsTerminal() async throws {+ let (model, mock, character, place) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ await model.toggleSelection(place.identity)+ model.setChoice(.skip, for: place.identity)+ let id = try #require(model.preview?.rows.first { $0.kind == .character }?.destinationID)+ mock.recordCopyCommitResult = .success(.committed(createdIDs: [id], skippedCount: 1))+ await model.accept()+ await model.accept()+ #expect(model.state == .committed && mock.recordCopyCommits.count == 1)+ #expect(model.success?.destination.displayTitle == "Book two")+ #expect(model.success?.createdCount == 1 && model.success?.skippedCount == 1)+ }++ @Test("Unconfirmed all-present response completes without a second write")+ @MainActor func uncertainPresent() async {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ mock.recordCopyCommitResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Lost response"))+ mock.recordCopyInspectionResult = .success(.committed)+ await model.accept()+ #expect(model.state == .committed && mock.recordCopyCommits.count == 1)+ #expect(mock.recordCopyInspections.count == 1)+ }++ @Test("Unconfirmed absence refreshes, warns and retains IDs for conscious retry")+ @MainActor func uncertainAbsentRetainsIDs() async throws {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ let id = try #require(model.preview?.rows.first?.destinationID)+ mock.recordCopyCommitResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Lost response"))+ mock.recordCopyInspectionResult = .success(.absent)+ await model.accept()+ #expect(model.retryNeedsConfirmation && !model.canAccept)+ #expect(model.message?.contains("deleted elsewhere") == true)+ #expect(model.preview?.rows.first?.destinationID == id)+ model.confirmRetry()+ #expect(model.canAccept && mock.recordCopyCommits.count == 1)+ }++ @Test("Partial or conflicting response blocks reacceptance while preserving draft")+ @MainActor func uncertainConflictBlocks() async {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ mock.recordCopyCommitResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Lost response"))+ mock.recordCopyInspectionResult = .success(.conflicting)+ await model.accept()+ await model.accept()+ #expect(!model.canAccept && model.selectedIdentities.contains(character.identity))+ #expect(mock.recordCopyCommits.count == 1 && model.state == .blocked)+ }++ @Test("A pending submission ignores duplicate acceptance and selection changes")+ @MainActor func oneInFlight() async throws {+ let (model, mock, character, place) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ let gate = SubmissionGate()+ mock.recordCopyCommitHold = gate+ mock.recordCopyCommitResult = .success(.refused(reason: "Refresh"))+ let task = Task { await model.accept() }+ defer {+ gate.open()+ task.cancel()+ }+ for _ in 0..<10000 where mock.recordCopyCommits.isEmpty { await Task.yield() }+ try #require(mock.recordCopyCommits.count == 1)+ await model.accept()+ await model.toggleSelection(place.identity)+ #expect(mock.recordCopyCommits.count == 1 && !model.selectedIdentities.contains(place.identity))+ gate.open()+ await task.value+ }++ @Test("A cancelled asynchronous initial read cannot reopen the session")+ @MainActor func cancelledReadCannotReopen() async throws {+ let (model, mock, _, _) = fixture()+ let gate = SubmissionGate()+ mock.recordCopyContextHold = gate+ let task = Task { await model.start() }+ defer {+ gate.open()+ task.cancel()+ }+ for _ in 0..<10000 where mock.recordCopyContextCallCount == 0 { await Task.yield() }+ try #require(mock.recordCopyContextCallCount == 1)+ model.close()+ gate.open()+ await task.value+ #expect(model.state == .closed && model.destinations.isEmpty)+ }++ @Test("Unavailable refreshed records remain visible and available selections survive")+ @MainActor func refreshedUnavailableSelection() async {+ let (model, mock, character, place) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.selectAll(.character)+ await model.selectAll(.place)+ let old = try! mock.recordCopyContextResult.get()+ var torn = character+ torn.unavailableReason = "Resolve differing copies"+ mock.recordCopyContextResult = .success(+ .init(source: old.source, destinations: old.destinations, records: [torn, place]))+ await model.refreshChoices()+ #expect(model.records[0].unavailableReason != nil)+ #expect(model.selectedIdentities == [place.identity])+ #expect(model.message?.contains("unavailable") == true)+ }++ @Test("Clashes start at Skip and concrete acknowledgement gates Keep separate")+ @MainActor func clashRequiresExplicitConsent() async throws {+ let (model, mock, character, _) = fixture()+ let existing = RecordCopyRecord(id: UUID(), kind: .character, name: "Ada")+ mock.recordCopyPreviewHandler = { source, destination, selections, notes in+ guard let selection = selections.first else {+ return .init(+ sourceWorkID: source, destinationWorkID: destination, includeNotes: notes, rows: [],+ basis: .init(+ sourceSeriesID: nil, destinationSeriesID: nil, directlyLinked: true, selected: [],+ destination: [existing]))+ }+ let row = RecordCopyPlanning.initialPlan(+ selected: [character], destination: [existing], includeNotes: notes)[0]+ return .init(+ sourceWorkID: source, destinationWorkID: destination, includeNotes: notes,+ rows: [+ .init(+ sourceID: character.id, destinationID: selection.destinationID, kind: .character,+ payload: row.payload, choice: row.choice, informationalClashes: row.informationalClashes+ )+ ],+ basis: .init(+ sourceSeriesID: nil, destinationSeriesID: nil, directlyLinked: true,+ selected: [character], destination: [existing]))+ }+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ #expect(model.preview?.rows[0].choice == .skip && !model.canAccept)+ model.setChoice(.copy, for: character.identity)+ #expect(!model.canAccept)+ model.acknowledge(character.identity)+ #expect(model.canAccept)+ let overlap = try #require(model.preview?.rows[0].informationalClashes)+ model.setChoice(.skip, for: character.identity)+ #expect(model.preview?.rows[0].informationalClashes == overlap)+ }++ @Test("A newly planned batch overlap clears consent while Skip information remains")+ @MainActor func addedBatchOverlapInvalidatesConsent() async {+ let (model, mock, character, _) = fixture()+ let peer = RecordCopyRecord(id: UUID(), kind: .character, name: "Nightjar")+ let context = try! mock.recordCopyContextResult.get()+ mock.recordCopyContextResult = .success(+ .init(source: context.source, destinations: context.destinations, records: [character, peer]))+ mock.recordCopyPreviewHandler = { source, destination, selections, notes in+ let chosen = [character, peer].filter { r in selections.contains { $0.sourceID == r.id } }+ let rows = RecordCopyPlanning.initialPlan(+ selected: chosen, destination: [], includeNotes: notes+ ).map { row in+ RecordCopyPlannedRow(+ sourceID: row.sourceID,+ destinationID: selections.first { $0.sourceID == row.sourceID }!.destinationID,+ kind: row.kind, payload: row.payload, choice: row.choice,+ informationalClashes: row.informationalClashes)+ }+ return .init(+ sourceWorkID: source, destinationWorkID: destination, includeNotes: notes, rows: rows,+ basis: .init(+ sourceSeriesID: nil, destinationSeriesID: nil, directlyLinked: true, selected: chosen,+ destination: []))+ }+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ model.acknowledge(character.identity)+ #expect(model.canAccept)+ await model.toggleSelection(peer.identity)+ #expect(model.preview?.rows.first { $0.sourceID == peer.id }?.choice == .skip)+ #expect(model.canAccept)+ model.setChoice(.copy, for: peer.identity)+ #expect(+ !model.canAccept+ && model.preview?.rows.first { $0.sourceID == character.id }?.acknowledgedClashes.isEmpty+ == true+ )+ model.acknowledge(character.identity)+ model.acknowledge(peer.identity)+ #expect(model.canAccept)+ }++ @Test("Missing destinations and torn sources preserve selection and disable acceptance")+ @MainActor func writeUnavailablePreservesSelection() async {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ let old = try! mock.recordCopyContextResult.get()+ mock.recordCopyContextResult = .success(+ .init(+ source: .init(work: old.source.work, unavailableReason: "Resolve work"), destinations: [],+ records: old.records))+ await model.refreshChoices()+ #expect(model.selectedIdentities == [character.identity] && !model.canAccept)+ #expect(model.source?.unavailableReason == "Resolve work")+ }++ @Test("Failed outcome inspection stays blocked and retry check never submits again")+ @MainActor func failedInspectionRetryIsReadOnly() async {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ mock.recordCopyCommitResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Lost response"))+ mock.recordCopyInspectionResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Unavailable store"))+ await model.accept()+ #expect(model.state == .blocked && !model.canAccept)+ mock.recordCopyInspectionResult = .success(.committed)+ await model.inspectOutcome()+ #expect(+ model.state == .committed && mock.recordCopyCommits.count == 1+ && mock.recordCopyInspections.count == 2)+ }++ @Test("Late note preview cannot replace a newer option or reopen a closed session")+ @MainActor func latePreviewCannotOverwrite() async throws {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ let handler = try #require(mock.recordCopyPreviewHandler)+ let gate = SubmissionGate()+ mock.recordCopyPreviewHandler = { source, destination, selections, notes in+ if notes { await gate.wait() }+ return try await handler(source, destination, selections, notes)+ }+ let pending = Task { await model.setIncludeNotes(true) }+ defer {+ gate.open()+ pending.cancel()+ }+ for _ in 0..<10000 where !model.includeNotes { await Task.yield() }+ try #require(model.includeNotes)+ model.setChoice(.skip, for: character.identity)+ #expect(model.preview?.rows.first?.choice == .copy)+ await model.setIncludeNotes(false)+ #expect(model.preview?.includeNotes == false)+ model.close()+ gate.open()+ await pending.value+ #expect(model.state == .closed && model.preview?.includeNotes == false)+ }++ @Test("A new destination alias clash defaults a previously automatic Copy to Skip")+ @MainActor func newDestinationClashDefaultsSkip() async throws {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ #expect(model.canAccept && model.preview?.rows.first?.choice == .copy)+ let handler = try #require(mock.recordCopyPreviewHandler)+ let destinationRecord = RecordCopyRecord(+ id: UUID(), kind: .character, name: "Another keeper", aliases: ["Nightjar"])+ mock.recordCopyPreviewHandler = { source, destination, selections, notes in+ let old = try await handler(source, destination, selections, notes)+ let planned = RecordCopyPlanning.initialPlan(+ selected: old.basis.selected, destination: [destinationRecord], includeNotes: notes)+ let rows = planned.map { row in+ RecordCopyPlannedRow(+ sourceID: row.sourceID,+ destinationID: selections.first { $0.sourceID == row.sourceID && $0.kind == row.kind }!+ .destinationID,+ kind: row.kind, payload: row.payload, choice: row.choice,+ informationalClashes: row.informationalClashes)+ }+ return .init(+ sourceWorkID: source, destinationWorkID: destination, includeNotes: notes, rows: rows,+ basis: .init(+ sourceSeriesID: nil, destinationSeriesID: nil, directlyLinked: true,+ selected: old.basis.selected, destination: [destinationRecord]))+ }+ await model.refreshPreview()+ #expect(model.selectedIdentities == [character.identity])+ #expect(model.preview?.rows.first?.choice == .skip && !model.canAccept)+ model.setChoice(.copy, for: character.identity)+ model.acknowledge(character.identity)+ #expect(model.canAccept)+ }++ @Test("Repeated outcome checks share one in-flight read and cannot overwrite success")+ @MainActor func oneInFlightInspection() async throws {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ let gate = SubmissionGate()+ mock.recordCopyCommitResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Lost response"))+ mock.recordCopyInspectionResult = .success(.committed)+ mock.recordCopyInspectionHold = gate+ let pending = Task { await model.accept() }+ defer {+ gate.open()+ pending.cancel()+ }+ for _ in 0..<10000 where mock.recordCopyInspections.isEmpty { await Task.yield() }+ try #require(mock.recordCopyInspections.count == 1)+ await model.inspectOutcome()+ #expect(model.state == .checkingOutcome && mock.recordCopyInspections.count == 1)+ gate.open()+ await pending.value+ #expect(model.state == .committed && mock.recordCopyCommits.count == 1)+ }++ @Test("Resolution suspension preserves values and IDs; explicit resume refreshes without copying")+ @MainActor func suspendedResolutionRetainsDraft() async throws {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ let id = try #require(model.preview?.rows.first?.destinationID)+ model.suspendForResolution()+ model.close()+ #expect(model.state == .suspended && !model.canAccept)+ await model.resumeAfterResolution()+ #expect(+ model.selectedIdentities == [character.identity]+ && model.preview?.rows.first?.destinationID == id)+ #expect(model.canAccept && mock.recordCopyCommits.isEmpty)+ }++ @Test("Discarding a suspended review retires it and cannot resume on an obsolete host")+ @MainActor func suspendedDiscardCannotResume() async {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ model.suspendForResolution()+ model.discardSuspendedSession()+ let reads = mock.recordCopyContextCallCount+ await model.resumeAfterResolution()+ #expect(+ model.state == .closed && mock.recordCopyContextCallCount == reads+ && mock.recordCopyCommits.isEmpty)+ }++ @Test("Manual factory uses the loaded resolved survivor and never the old route UUID")+ @MainActor func manualFactoryUsesResolvedWork() async throws {+ let (_, mock, _, _) = fixture()+ let survivor = try mock.recordCopyContextResult.get().source.work+ let oldRoute = UUID()+ let work = makeWorkDetailModel(workID: oldRoute, library: mock)+ await work.load()+ let copy = try #require(work.recordCopyModel())+ await copy.start()+ #expect(mock.recordCopyContextSourceIDs.last == survivor.id)+ #expect(mock.recordCopyContextSourceIDs.last != oldRoute)+ }++ @Test("Resolution resume cannot bypass an uncertain outcome or its conscious retry gate")+ @MainActor func uncertainSuspensionKeepsOutcomeGate() async throws {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ let id = try #require(model.preview?.rows.first?.destinationID)+ mock.recordCopyCommitResult = .failure(+ MockLibraryProvider.MockError.simulatedFailure("Lost response"))+ mock.recordCopyInspectionResult = .success(.conflicting)+ await model.accept()+ model.suspendForResolution()+ model.close()+ await model.resumeAfterResolution()+ #expect(model.state == .blocked && !model.canAccept)+ await model.accept()+ #expect(mock.recordCopyCommits.count == 1)+ mock.recordCopyInspectionResult = .success(.absent)+ await model.inspectOutcome()+ #expect(model.retryNeedsConfirmation && !model.canAccept)+ #expect(model.preview?.rows.first?.destinationID == id)+ #expect(mock.recordCopyInspections.allSatisfy { $0.rows.first?.destinationID == id })+ model.confirmRetry()+ #expect(model.canAccept && mock.recordCopyCommits.count == 1)+ }++ @Test("Host navigation during resumed read retires the session before the result returns")+ @MainActor func lateResumeAfterNavigationStaysClosed() async throws {+ let (model, mock, character, _) = fixture()+ await model.start()+ await model.selectDestination(model.destinations[0].id)+ await model.toggleSelection(character.identity)+ model.suspendForResolution()+ let gate = SubmissionGate()+ mock.recordCopyContextHold = gate+ let reads = mock.recordCopyContextCallCount+ let pending = Task { await model.resumeAfterResolution() }+ defer {+ gate.open()+ pending.cancel()+ }+ for _ in 0..<10000 where mock.recordCopyContextCallCount == reads { await Task.yield() }+ try #require(mock.recordCopyContextCallCount == reads + 1)+ model.discardSuspendedSession()+ gate.open()+ await pending.value+ #expect(model.state == .closed && !model.canAccept && mock.recordCopyCommits.isEmpty)+ }++ @Test(+ "Resumed offer session preserves the reader's changed destination instead of reapplying its preset"+ )+ @MainActor func resumedPresetKeepsReviewedDestination() async throws {+ let (_, mock, character, _) = fixture()+ let context = try mock.recordCopyContextResult.get()+ let other = TestFixtures.makeWork(displayTitle: "Another sequel", memberships: [])+ mock.recordCopyContextResult = .success(+ .init(+ source: context.source,+ destinations: context.destinations + [.init(work: other, unavailableReason: nil)],+ records: context.records))+ let model = WorkRecordCopyModel(+ sourceWorkID: context.source.id, library: mock, onMutation: {},+ destinationID: context.destinations[0].id)+ await model.start()+ await model.selectDestination(other.id)+ await model.toggleSelection(character.identity)+ let id = try #require(model.preview?.rows.first?.destinationID)+ model.suspendForResolution()+ await model.resumeAfterResolution()+ await model.start()+ #expect(model.destinationID == other.id && model.preview?.destinationWorkID == other.id)+ #expect(model.preview?.rows.first?.destinationID == id && mock.recordCopyCommits.isEmpty)+ }+}
diff --git a/Asterism/AsterismUITests/CharacterExtractionUITests.swift b/Asterism/AsterismUITests/CharacterExtractionUITests.swiftindex 501f6514..eac09001 100644--- a/Asterism/AsterismUITests/CharacterExtractionUITests.swift+++ b/Asterism/AsterismUITests/CharacterExtractionUITests.swift@@ -54,7 +54,8 @@ final class CharacterExtractionUITests: XCTestCase { // MARK: - Navigation private func openWorkDetail() {- waitFor(app.collectionViews["recent-list"], "The library opens", timeout: 60)+ // Phone uses List; the wide Today pane exposes this identifier as a ScrollView.+ waitFor(app.anyElement("recent-list"), "The library opens", timeout: 60) openAllWorks(in: app) waitFor(app.anyElement("works-group-allWorks"), "Works lists the seeded library") waitFor(@@ -149,21 +150,27 @@ final class CharacterExtractionUITests: XCTestCase { return byOwnLabel.exists ? byOwnLabel : facts.containing(statement).firstMatch } - /// Taps a cast pill to open its detail card.- ///- /// **Not `element.tap()`.** In a List row the pill button's AX frame spans- /// the full row while its `contentShape` is only the visual pill at the- /// leading edge, so a centre tap lands outside the shape and does nothing —- /// the same trap `flip` documents for Form toggles.- /// A coordinate tap on an off-screen element lands wherever that point- /// happens to be on screen — and a lazy List row below the fold does not- /// even exist yet — so the pill is scrolled into existence and hittability- /// first.+ /// Opens a record only after its whole pill is clear of navigation chrome.+ /// A partly visible pill can report hittable while the chosen coordinate+ /// lands on the floating tab bar (the alias/citation regression did so at+ /// y=792 with the bar starting at y=791). Scroll the work-detail column,+ /// then verify that the tap did not navigate away before negative checks. private func openPill(_ pill: XCUIElement) {- for _ in 0..<6 where !(pill.exists && pill.isHittable) {- app.swipeUp()+ let detail = waitFor(app.anyElement("work-detail-scroll"), "Work detail is open")+ let tabBar = app.tabBars.firstMatch+ func pillIsClear() -> Bool {+ guard pill.exists && pill.isHittable else { return false }+ let frame = pill.frame+ let viewport = detail.frame.intersection(app.frame)+ return !frame.isEmpty && viewport.contains(frame)+ && (!tabBar.exists || frame.maxY <= tabBar.frame.minY)+ }+ for _ in 0..<6 where !pillIsClear() {+ detail.swipeUp() }+ XCTAssertTrue(pillIsClear(), "The entire record pill is inside work detail and above the tab bar") pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).tap()+ waitFor(app.anyElement("work-detail-scroll"), "Opening a record stays on work detail") } /// The cast pill for one name. The pills of one collection all carry the@@ -584,6 +591,16 @@ final class CharacterExtractionUITests: XCTestCase { timeout: 30) openPill(pill(named: "Ada"))+ // Keep the actual open-card tree and pixels when this journey fails:+ // a missing alias must be distinguished from a tap on another pill.+ let cardTree = XCTAttachment(string: app.debugDescription)+ cardTree.name = "Record card before alias assertion"+ cardTree.lifetime = .deleteOnSuccess+ add(cardTree)+ let cardScreenshot = XCTAttachment(screenshot: app.screenshot())+ cardScreenshot.name = "Record card before alias assertion"+ cardScreenshot.lifetime = .deleteOnSuccess+ add(cardScreenshot) waitFor(aliasChip(named: "Nightjar"), "The kept alias is a chip beside the name") openPill(pill(named: "Brede"))
diff --git a/Asterism/AsterismUITests/SeriesUITests.swift b/Asterism/AsterismUITests/SeriesUITests.swiftindex 26b873aa..8c6b9cc7 100644--- a/Asterism/AsterismUITests/SeriesUITests.swift+++ b/Asterism/AsterismUITests/SeriesUITests.swift@@ -38,7 +38,7 @@ final class SeriesUITests: XCTestCase { } private func openWorks() {- waitFor(app.collectionViews["recent-list"], "The library opens", timeout: 60)+ waitFor(app.anyElement("recent-list"), "The library opens", timeout: 60) openAllWorks(in: app) waitFor(app.anyElement("works-group-allWorks"), "Works lists the seeded library") }@@ -251,7 +251,7 @@ final class SeriesUITests: XCTestCase { app.textFields["series-member-position-\(risingID)"], "Req 15.1: the editor offers the member's position under its own identifier") replace(position, with: "3")- waitFor(app.buttons["series-detail-save-button"], "The checkmark commits the editor").tap()+ tapEditorSave("series-detail-save-button", in: app, "The checkmark commits the editor") waitUntilGone( app.textFields["series-detail-name-field"], "A committed editor returns to view mode")
diff --git a/Asterism/AsterismUITests/UIJourneySupport.swift b/Asterism/AsterismUITests/UIJourneySupport.swiftindex 8ed75aef..a64bf902 100644--- a/Asterism/AsterismUITests/UIJourneySupport.swift+++ b/Asterism/AsterismUITests/UIJourneySupport.swift@@ -104,14 +104,24 @@ extension XCTestCase { _ tab: UITab, in app: XCUIApplication, timeout: TimeInterval = 30, file: StaticString = #filePath, line: UInt = #line ) -> XCUIElement {- let barButton = app.buttons[tab.label]- let sidebarRow = app.buttons[tab.sidebarIdentifier]+ let barButton = app.buttons[tab.label].firstMatch+ let sidebarRow = app.buttons[tab.sidebarIdentifier].firstMatch let deadline = Date().addingTimeInterval(timeout) while Date() < deadline { for candidate in [barButton, sidebarRow] where candidate.exists && candidate.isHittable { candidate.tap() return candidate }+ // Portrait's collapsed sidebar publishes nested top-bar buttons+ // as non-hittable, despite their visible frame. Keep this fallback+ // confined to that layout and to a control inside the app window.+ let toggle = app.buttons["sidebar-toggle"].firstMatch+ if toggle.exists, toggle.value as? String == "collapsed", barButton.exists,+ !barButton.frame.isEmpty, app.frame.contains(barButton.frame)+ {+ barButton.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+ return barButton+ } // The wait has to be on *hittability*, not existence. A control that // exists but is not yet hittable — the sidebar row during the split // view's first layout is the ordinary case — satisfied@@ -145,6 +155,45 @@ extension XCTestCase { file: file, line: line) } + /// The iPad keyboard can make a visible editor toolbar button report an+ /// unusable synthesized hit point. Keep the center tap bounded to an+ /// enabled, visible control rather than accepting an offscreen Save.+ func tapEditorSave(+ _ identifier: String, in app: XCUIApplication, _ message: String,+ file: StaticString = #filePath, line: UInt = #line+ ) {+ // A Save-time touch was dispatched to the iPad keyboard window, even+ // though Save's frame was in the app. Dismiss that actual keyboard+ // control before resolving the toolbar button again.+ let hideKeyboard = app.keyboards.buttons["Hide keyboard"].firstMatch+ if hideKeyboard.exists, hideKeyboard.isEnabled {+ let frame = hideKeyboard.frame+ XCTAssertFalse(frame.isEmpty, "Hide keyboard has a visible frame", file: file, line: line)+ XCTAssertTrue(+ app.frame.contains(frame), "Hide keyboard is inside the app window",+ file: file, line: line)+ guard !frame.isEmpty, app.frame.contains(frame) else { return }+ hideKeyboard.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+ waitUntilGone(+ app.keyboards.firstMatch, "The keyboard closes before Save", file: file, line: line)+ guard !app.keyboards.firstMatch.exists else { return }+ }+ let button = waitFor(+ app.buttons[identifier].firstMatch, message, file: file, line: line)+ XCTAssertTrue(button.isEnabled, "The editor Save is enabled", file: file, line: line)+ guard button.isEnabled else { return }+ if button.isHittable {+ button.tap()+ return+ }+ let frame = button.frame+ XCTAssertFalse(frame.isEmpty, "Save has a visible frame", file: file, line: line)+ XCTAssertTrue(+ app.frame.contains(frame), "Save is inside the app window", file: file, line: line)+ guard !frame.isEmpty, app.frame.contains(frame) else { return }+ button.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()+ }+ /// A wide-layout element sits horizontally inside the column that holds it. /// /// Shared by both iPad suites since the accessibility cases were folded back
diff --git a/Asterism/AsterismUITests/WorkDetailConnectionsUITests.swift b/Asterism/AsterismUITests/WorkDetailConnectionsUITests.swiftindex 626099d8..0fd2b318 100644--- a/Asterism/AsterismUITests/WorkDetailConnectionsUITests.swift+++ b/Asterism/AsterismUITests/WorkDetailConnectionsUITests.swift@@ -37,7 +37,7 @@ final class WorkDetailConnectionsUITests: XCTestCase { } private func openWorks() {- waitFor(app.collectionViews["recent-list"], "The library opens", timeout: 60)+ waitFor(app.anyElement("recent-list"), "The library opens", timeout: 60) openAllWorks(in: app) waitFor(app.anyElement("works-group-allWorks"), "Works lists the seeded library") }@@ -198,9 +198,10 @@ final class WorkDetailConnectionsUITests: XCTestCase { position.value as? String, "1", "Req 2.3: an empty series prefills the position with 1") replace(position, with: "2.5")- waitFor(app.buttons["work-detail-save-button"], "The checkmark commits the editor").tap()+ tapEditorSave("work-detail-save-button", in: app, "The checkmark commits the editor") waitUntilGone( app.textFields["work-detail-title-field"], "A committed editor returns to view mode")+ waitFor(app.buttons["work-detail-edit-button"], "View mode offers the editor again") let row = waitFor( app.buttons["work-detail-series-row"], "Req 5.1: view mode names the new series")
diff --git a/Asterism/AsterismUITests/WorkRecordCopyOfferUITests.swift b/Asterism/AsterismUITests/WorkRecordCopyOfferUITests.swiftnew file mode 100644index 00000000..e707a178--- /dev/null+++ b/Asterism/AsterismUITests/WorkRecordCopyOfferUITests.swift@@ -0,0 +1,165 @@+import XCTest++/// Saved membership receipts reach an optional review only after each editor closes.+/// All fixtures use ordinary isolated repository writes and default next positions.+final class WorkRecordCopyOfferUITests: XCTestCase {+ let app = XCUIApplication()+ override func setUp() { continueAfterFailure = false; terminateAndWaitForExit(app) }+ override func tearDown() { terminateAndWaitForExit(app) }+ private func launch() {+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-record-copy"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launch()+ waitFor(app.anyElement("recent-list"), "The isolated library opens", timeout: 60)+ }+ private func openWork(_ title: String) {+ openAllWorks(in: app)+ let exact = "Open Work \(title)"+ let row = app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH 'work-row-' AND (label == %@ OR label BEGINSWITH %@ OR label BEGINSWITH %@)",+ exact, exact + " from ", exact + ". ")).firstMatch+ scrollUntilTappableAndTap(row, in: app, "The saved work is listed")+ waitFor(app.anyElement("work-detail-pulse"), "The work opens")+ }+ private func assignSeries(_ name: String) {+ waitFor(app.buttons["work-detail-edit-button"], "Edit metadata").tap()+ scrollUntilTappableAndTap(app.anyElement("work-detail-series-picker"), in: app, "Choose series")+ waitFor(app.buttons[name], "The series is available").tap()+ XCTAssertFalse(app.anyElement("record-copy-offer").exists, "Staging never offers copying")+ }+ private func saveWork() {+ scrollUntilTappableAndTap(app.buttons["work-detail-save-button"], in: app, "Save the editor")+ }+ private func openSeries(_ name: String) {+ if !app.anyElement("series-index").exists {+ selectTab(.works, in: app)+ waitFor(app.buttons["library-tile-series"], "Open series library").tap()+ }+ let row = app.elements(withIdentifierPrefix: "series-card-").matching(+ NSPredicate(format: "label BEGINSWITH %@", name + ",")).firstMatch+ scrollUntilTappableAndTap(waitFor(row, "The series is listed"), in: app, "Open series")+ waitFor(app.buttons["series-detail-edit-button"], "The saved series opens").tap()+ }+ private func stageAddition(_ title: String) {+ scrollUntilTappableAndTap(app.buttons["series-detail-add-member"], in: app, "Add work")+ waitFor(app.anyElement("work-picker"), "The ordinary work picker opens")+ let search = waitFor(app.textFields["work-picker-search"], "Search this member picker")+ search.tap(); search.typeText(title)+ let row = app.buttons.matching(NSPredicate(format:+ "identifier BEGINSWITH 'work-picker-' AND label == %@", title)).firstMatch+ scrollUntilTappableAndTap(row, in: app, "The addition is offered")+ waitUntilGone(app.anyElement("work-picker"), "The picker closes before Save")+ XCTAssertFalse(app.anyElement("record-copy-offer").exists)+ }+ func testWorkJoinOpensOptionalReviewWithoutSelections() {+ launch(); openWork("Offer addition"); assignSeries("Offer cycle"); saveWork()+ waitFor(app.anyElement("record-copy-offer"), "A saved join offers the nearest earlier work")+ XCTAssertTrue(app.buttons["record-copy-offer-review"].label.contains("Offer source"))+ app.buttons["record-copy-offer-review"].tap()+ waitFor(app.anyElement("record-copy"), "Review opens ordinary copying")+ XCTAssertFalse(app.buttons["record-copy-accept"].isEnabled)+ app.buttons["record-copy-cancel"].tap()+ XCTAssertFalse(app.alerts["Copied characters and places"].exists)+ scrollUntilTappableAndTap(app.buttons["work-detail-series-row"], in: app,+ "Cancelling copying retains the saved series membership")+ waitFor(app.anyElement("series-detail"), "The saved membership opens its series")+ }+ func testStagedWorkJoinCancelledDoesNotOffer() {+ launch(); openWork("Offer addition"); assignSeries("Offer cycle")+ app.buttons["work-detail-edit-cancel-button"].tap()+ XCTAssertFalse(app.anyElement("record-copy-offer").exists)+ waitFor(app.buttons["work-detail-edit-button"], "The work remains saved").tap()+ XCTAssertFalse(app.anyElement("work-detail-series-position").exists)+ app.buttons["work-detail-edit-cancel-button"].tap()+ }+ func testNearestEmptyPredecessorHasNoOlderFallback() {+ launch(); openWork("Book three"); assignSeries("Copy cycle"); saveWork()+ waitFor(app.buttons["work-detail-edit-button"], "Saving is terminal")+ XCTAssertFalse(app.anyElement("record-copy-offer").exists,+ "Book two is the empty nearest predecessor; Book one must not be substituted")+ }+ func testTiedPredecessorIncludesUnavailablePeerAndRequiresChoice() {+ launch(); openWork("Tied addition"); assignSeries("Tied cycle"); saveWork()+ waitFor(app.anyElement("record-copy-offer"), "The saved tie opens review")+ waitFor(app.staticTexts["record-copy-offer-tie"], "The tie is explained")+ XCTAssertFalse(app.buttons["record-copy-offer-review"].isEnabled)+ XCTAssertTrue(app.staticTexts.matching(NSPredicate(+ format: "identifier BEGINSWITH 'record-copy-offer-unavailable-' AND label CONTAINS 'Empty tied peer'")).firstMatch.exists)+ app.buttons.matching(NSPredicate(format:+ "identifier BEGINSWITH 'record-copy-offer-source-' AND label BEGINSWITH 'Tied source,'")).firstMatch.tap()+ XCTAssertTrue(app.buttons["record-copy-offer-review"].isEnabled)+ app.buttons["record-copy-offer-decline"].tap()+ }+ func testSeriesJoinOffersOnlyAfterPickerAndEditorClose() {+ launch(); openSeries("Offer cycle"); stageAddition("Offer addition")+ scrollUntilTappableAndTap(app.buttons["series-detail-save-button"], in: app, "Save addition")+ waitFor(app.anyElement("record-copy-offer"), "The committed addition offers review")+ XCTAssertFalse(app.anyElement("work-picker").exists)+ XCTAssertFalse(app.buttons["series-detail-save-button"].exists)+ app.buttons["record-copy-offer-review"].tap()+ waitFor(app.anyElement("record-copy"), "The series offer opens ordinary copying")+ XCTAssertFalse(app.buttons["record-copy-accept"].isEnabled)+ XCTAssertTrue(app.buttons.matching(NSPredicate(format:+ "identifier BEGINSWITH 'record-copy-destination-' AND label CONTAINS 'Offer addition' AND label CONTAINS 'selected' AND NOT label CONTAINS 'not selected'")).firstMatch.exists)+ app.buttons["record-copy-cancel"].tap()+ waitFor(app.buttons["series-detail-edit-button"], "The saved series returns")+ app.goBack()+ waitFor(app.anyElement("series-index"), "Back returns to the saved series list")+ openSeries("Offer cycle")+ XCTAssertFalse(app.anyElement("record-copy-offer").exists, "Loading does not recreate the saved event")+ app.buttons["series-detail-cancel-button"].tap()+ }+ func testBatchNamesBothAdditionsAndDeclineConsumesWholeBatch() {+ launch(); openSeries("Offer cycle")+ stageAddition("Offer addition"); stageAddition("Offer second addition")+ scrollUntilTappableAndTap(app.buttons["series-detail-save-button"], in: app, "Save both additions")+ waitFor(app.anyElement("record-copy-offer"), "The committed batch offers review")+ XCTAssertEqual(app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH 'record-copy-offer-destination-'")).count, 2)+ XCTAssertFalse(app.buttons["record-copy-offer-review"].exists,+ "A batch does not choose an addition silently")+ waitFor(app.staticTexts["record-copy-offer-batch-explanation"], "Closing consumes the whole batch")+ app.buttons["record-copy-offer-decline"].tap()+ waitFor(app.buttons["series-detail-edit-button"], "Both memberships remain saved")+ XCTAssertFalse(app.anyElement("record-copy-offer").exists)+ // Offer addition already owns Reader; declining must preserve it and must+ // not create Ada or Harbour from the proposed source.+ app.goBack(); app.goBack()+ openWork("Offer addition")+ XCTAssertFalse(app.buttons.matching(NSPredicate(+ format: "identifier == 'work-detail-character' AND label BEGINSWITH 'Ada,'")).firstMatch.exists)+ XCTAssertFalse(app.buttons.matching(NSPredicate(+ format: "identifier == 'work-detail-place' AND label BEGINSWITH 'Harbour,'")).firstMatch.exists)+ scrollUntilTappableAndTap(app.buttons["work-detail-edit-button"], in: app, "Inspect retained addition records")+ let retained = app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH 'work-detail-character-line-' AND label BEGINSWITH 'Reader'")).firstMatch+ openEditorLine(retained, expecting: "character-editor", in: app,+ "The existing Reader record remains reachable after declining")+ XCTAssertEqual(waitFor(app.textFields["work-detail-character-name-field"],+ "The retained record keeps its name").value as? String, "Reader")+ closeEditorSheet("character-editor", done: "character-editor-done", in: app)+ app.buttons["work-detail-edit-cancel-button"].tap()+ }+ func testBatchReviewOneThenCancelConsumesWholeBatch() {+ launch(); openSeries("Offer cycle")+ stageAddition("Offer addition"); stageAddition("Offer second addition")+ scrollUntilTappableAndTap(app.buttons["series-detail-save-button"], in: app, "Save both additions")+ waitFor(app.anyElement("record-copy-offer"), "One review covers the saved batch")+ let destination = app.buttons.matching(NSPredicate(format:+ "identifier BEGINSWITH 'record-copy-offer-destination-' AND label BEGINSWITH 'Review addition Offer addition,'")).firstMatch+ scrollUntilTappableAndTap(destination, in: app, "Review one named addition")+ scrollUntilTappableAndTap(app.buttons["record-copy-offer-review"], in: app,+ "The chosen addition's review is reachable below the list")+ waitFor(app.anyElement("record-copy"), "Review starts with no automatic copies")+ XCTAssertFalse(app.buttons["record-copy-accept"].isEnabled)+ app.buttons["record-copy-cancel"].tap()+ waitFor(app.buttons["series-detail-edit-button"], "The series returns after cancelling copying")+ XCTAssertFalse(app.anyElement("record-copy-offer").exists)+ app.goBack(); app.goBack(); openWork("Offer second addition")+ scrollUntilTappableAndTap(app.buttons["work-detail-copy-records"], in: app,+ "Other saved additions keep the ordinary manual Copy action")+ waitFor(app.anyElement("record-copy"), "Manual copying remains reachable")+ app.buttons["record-copy-cancel"].tap()+ }++}
diff --git a/Asterism/AsterismUITests/WorkRecordCopyUITests.swift b/Asterism/AsterismUITests/WorkRecordCopyUITests.swiftnew file mode 100644index 00000000..c798d681--- /dev/null+++ b/Asterism/AsterismUITests/WorkRecordCopyUITests.swift@@ -0,0 +1,221 @@+import XCTest++final class WorkRecordCopyUITests: XCTestCase {+ let app = XCUIApplication()+ override func setUp() {+ continueAfterFailure = false+ terminateAndWaitForExit(app)+ }+ override func tearDown() { terminateAndWaitForExit(app) }++ private func launch(_ scenario: String = "seeded-record-copy") {+ app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = scenario+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launch()+ waitFor(app.anyElement("recent-list"), "The isolated library opens", timeout: 60)+ openAllWorks(in: app)+ }+ private func openWork(_ title: String) {+ let exact = "Open Work \(title)"+ let row = app.buttons.matching(+ NSPredicate(+ format:+ "identifier BEGINSWITH 'work-row-' AND (label == %@ OR label BEGINSWITH %@ OR label BEGINSWITH %@)",+ exact, exact + " from ", exact + ". "+ )+ ).firstMatch+ revealForReading(row, "The saved work is listed and reachable")+ XCTAssertTrue(+ row.label == exact || row.label.hasPrefix(exact + " from ")+ || row.label.hasPrefix(exact + ". "))+ scrollUntilTappableAndTap(row, in: app, "The saved work is reachable")+ waitFor(app.anyElement("work-detail-pulse"), "The saved work opens")+ }+ private func openCopy() {+ scrollUntilTappableAndTap(+ app.buttons["work-detail-copy-records"], in: app, "Copy is available outside edit mode")+ waitFor(app.anyElement("record-copy"), "The copy session opens")+ }+ private func destination(_ title: String) -> XCUIElement {+ app.buttons.matching(+ NSPredicate(+ format: "identifier BEGINSWITH 'record-copy-destination-' AND label CONTAINS %@", title)+ ).firstMatch+ }+ private func record(_ name: String, kind: String = "character") -> XCUIElement {+ app.buttons.matching(+ NSPredicate(+ format: "identifier BEGINSWITH %@ AND label BEGINSWITH %@", "record-copy-select-\(kind)-",+ "\(name),")+ ).firstMatch+ }++ private func revealForReading(_ element: XCUIElement, _ message: String) {+ for _ in 0..<8 {+ if element.exists && element.isHittable { return }+ app.swipeUp()+ }+ XCTAssertTrue(element.exists && element.isHittable, message)+ }++ func testCopyActionIsOutsideEditMode() {+ launch("seeded-series")+ openWork("Ashfall Rising")+ openCopy()+ waitFor(app.buttons["record-copy-cancel"], "Cancel is available").tap()+ waitFor(app.buttons["work-detail-edit-button"], "The original page remains").tap()+ XCTAssertFalse(app.buttons["work-detail-copy-records"].exists)+ waitFor(app.buttons["work-detail-edit-cancel-button"], "Cancel closes metadata editing").tap()+ }++ func testMixedCopyNotesAndIndependentCorrection() {+ launch()+ openWork("Book one")+ openCopy()+ waitFor(destination("Book two"), "A URL-free series peer is offered").tap()+ XCTAssertFalse(app.buttons["record-copy-accept"].isEnabled)+ waitFor(record("Ada"), "The character is selectable").tap()+ XCTAssertEqual(record("Ada").label, "Ada, Character, selected")+ scrollUntilTappableAndTap(+ record("Harbour", kind: "place"), in: app, "The place is selectable")+ XCTAssertEqual(record("Harbour", kind: "place").label, "Harbour, Place, selected")+ let ready = XCTNSPredicateExpectation(predicate: NSPredicate {+ _, _ in self.app.buttons["record-copy-accept"].isEnabled+ && self.app.buttons["record-copy-accept"].label == "Copy 2"+ }, object: nil)+ XCTAssertEqual(XCTWaiter().wait(for: [ready], timeout: 10), .completed,+ "Both selected kinds produce an accepted two-record plan")+ revealForReading(app.switches["record-copy-notes"], "The notes option is visible")+ XCTAssertEqual(app.switches["record-copy-notes"].value as? String, "0")+ // XCTest exposes the entire Toggle row as a switch. Its centre is+ // the label; tap the trailing native switch thumb instead.+ app.switches["record-copy-notes"].coordinate(withNormalizedOffset: CGVector(dx: 0.93, dy: 0.5)).tap()+ let included = XCTNSPredicateExpectation(predicate: NSPredicate {+ _, _ in self.app.switches["record-copy-notes"].value as? String == "1"+ }, object: nil)+ XCTAssertEqual(XCTWaiter().wait(for: [included], timeout: 10), .completed)+ XCTAssertEqual(app.switches["record-copy-notes"].value as? String, "1")+ waitFor(app.staticTexts["record-copy-exclusions"], "Facts are explicitly excluded")+ XCTAssertTrue(+ app.staticTexts["record-copy-exclusions"].label.contains("Facts, quotes and citations"))+ let previewNote = app.staticTexts.matching(NSPredicate(+ format: "identifier BEGINSWITH 'record-copy-preview-note-character-'")).firstMatch+ revealForReading(previewNote, "The copied note appears in the actual preview")+ XCTAssertEqual(previewNote.label, "A secret")+ scrollUntilTappableAndTap(+ app.buttons["record-copy-accept"], in: app, "Copy accepts the two planned records")+ waitFor(app.alerts["Copied characters and places"], "Success identifies the result")+ XCTAssertTrue(+ app.alerts.staticTexts.matching(+ NSPredicate(format: "label CONTAINS '2 copied' AND label CONTAINS 'Book two'")+ ).firstMatch.exists)+ app.alerts.buttons["Open destination"].tap()+ waitFor(app.buttons["work-detail-edit-button"], "The destination opens").tap()+ let line = app.buttons.matching(+ NSPredicate(+ format: "identifier BEGINSWITH 'work-detail-character-line-' AND label BEGINSWITH 'Ada'")+ ).firstMatch+ openEditorLine(+ line, expecting: "character-editor", in: app,+ "The independent copy opens in its ordinary editor")+ let field = waitFor(+ app.textFields["work-detail-character-name-field"], "The copy has an editable name")+ field.tap()+ field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 8))+ field.typeText("Ada sequel")+ closeEditorSheet("character-editor", done: "character-editor-done", in: app)+ scrollUntilTappableAndTap(+ app.buttons["work-detail-save-button"], in: app, "The destination editor saves the correction"+ )+ XCTAssertTrue(+ app.staticTexts.matching(NSPredicate(format: "label CONTAINS 'Ada sequel'")).firstMatch+ .waitForExistence(timeout: 10))+ }++ func testCancelPreservesBothWorksAndNoSelectionsOnReopen() {+ launch()+ openWork("Book one")+ openCopy()+ waitFor(destination("Book two"), "The destination exists").tap()+ waitFor(record("Ada"), "A character is offered").tap()+ app.buttons["record-copy-cancel"].tap()+ openCopy()+ waitFor(destination("Book two"), "The destination remains available").tap()+ XCTAssertFalse(app.buttons["record-copy-accept"].isEnabled)+ XCTAssertTrue(record("Ada").label.contains("not selected"))+ }++ func testRepeatedCopyDefaultsSkipAndRequiresKeepSeparateWarning() {+ launch()+ openWork("Book one")+ openCopy()+ waitFor(destination("Book two"), "Destination exists").tap()+ waitFor(record("Ada"), "Source record exists").tap()+ scrollUntilTappableAndTap(app.buttons["record-copy-accept"], in: app, "First copy commits")+ waitFor(app.alerts["Copied characters and places"], "Success is reported").buttons["Done"].tap()+ openCopy()+ waitFor(destination("Book two"), "Destination remains").tap()+ waitFor(record("Ada"), "Source remains independent").tap()+ XCTAssertFalse(app.buttons["record-copy-accept"].isEnabled)+ scrollUntilTappableAndTap(+ app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'record-copy-keep-' "))+ .firstMatch, in: app, "Keep separate is explicit")+ waitFor(app.alerts["Keep separate?"], "Concrete clash warning is shown")+ XCTAssertTrue(+ app.alerts.staticTexts.matching(NSPredicate(format: "label CONTAINS 'extracted facts' "))+ .firstMatch.exists)+ app.alerts.buttons["Keep separate"].tap()+ XCTAssertTrue(app.buttons["record-copy-accept"].isEnabled)+ let skipAda = app.buttons.matching(NSPredicate(+ format: "identifier BEGINSWITH 'record-copy-choice-character-' AND label == 'Skip this record, Ada'"+ )).firstMatch+ scrollUntilTappableAndTap(skipAda, in: app, "Skip is independent of the Keep separate action")+ XCTAssertFalse(app.alerts["Keep separate?"].exists)+ XCTAssertFalse(app.buttons["record-copy-accept"].isEnabled)+ app.buttons["record-copy-cancel"].tap()+ }++ func testInformationalOverlapWithSkippedPeerDoesNotRequireKeepSeparate() {+ launch()+ openWork("Book one")+ openCopy()+ waitFor(destination("Book two"), "Destination exists").tap()+ scrollUntilTappableAndTap(+ app.buttons["record-copy-all-character"], in: app,+ "Both same-kind source records can be selected")+ XCTAssertEqual(record("Ada").label, "Ada, Character, selected")+ XCTAssertEqual(record("Nightjar").label, "Nightjar, Character, selected")+ XCTAssertFalse(app.buttons["record-copy-accept"].isEnabled)+ let copyAda = app.buttons.matching(+ NSPredicate(+ format: "identifier BEGINSWITH 'record-copy-choice-character-' AND label == 'Copy this record, Ada'")+ ).firstMatch+ scrollUntilTappableAndTap(+ copyAda, in: app, "Copying one overlap while its peer stays Skip needs no duplicate warning")+ XCTAssertFalse(app.alerts["Keep separate?"].exists)+ XCTAssertTrue(app.buttons["record-copy-accept"].isEnabled)+ XCTAssertTrue(app.buttons["record-copy-accept"].label.contains("1"))+ app.buttons["record-copy-cancel"].tap()+ }++ func testCheckLibraryReturnsToPreservedReviewFromLibrary() {+ launch()+ openWork("Book one")+ openCopy()+ waitFor(destination("Book two"), "Destination exists").tap()+ waitFor(record("Ada"), "Ordinary source has no duplicate workload").tap()+ scrollUntilTappableAndTap(+ app.buttons["record-copy-resolve"], in: app,+ "The independent Check Library route is available")+ waitFor(app.anyElement("diagnostics-empty"), "Check Library opens on this stack", timeout: 20)+ app.goBack()+ scrollUntilTappableAndTap(+ app.buttons["work-detail-resume-copy"], in: app,+ "The original Work retains the suspended review")+ waitFor(app.anyElement("record-copy"), "Review resumes")+ XCTAssertEqual(record("Ada").label, "Ada, Character, selected")+ XCTAssertTrue(app.buttons["record-copy-accept"].isEnabled)+ XCTAssertTrue(app.buttons["record-copy-accept"].label.contains("1"))+ app.buttons["record-copy-cancel"].tap()+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ChapterCaptureResolver.swift b/Packages/AsterismCore/Sources/AsterismCore/ChapterCaptureResolver.swiftindex 907215ea..861752c0 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ChapterCaptureResolver.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ChapterCaptureResolver.swift@@ -55,6 +55,18 @@ public struct ChapterCaptureProjection: Equatable, Sendable { public var workModifiedAt: Date? = nil public var ruleBasis: CaptureBasis? = nil public var captureDefault: ChapterCaptureDefault = .ordinary++ /// Optional alternatives must not look like a required confirmation in the+ /// ordinary capture flow. Required review and whole-page chapter drafts+ /// stay expanded; this affects presentation, never target resolution.+ public var showsChapterChoicesInitially: Bool {+ switch resolution {+ case .chooseChapter, .newChapter(requiresConfirmation: true): return true+ default: return captureDefault == .multipleChaptersPerPage && offersAnotherChapter+ }+ }++ } /// Read-only decision logic shared by projection and the commit recheck. This
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex 98caa8c1..7f654285 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 recordCopyContext(sourceWorkID: UUID) async throws -> RecordCopyContext+ func previewRecordCopy(sourceWorkID: UUID, destinationWorkID: UUID, selections: [RecordCopySelection], includeNotes: Bool) async throws -> RecordCopyPreview+ func commitRecordCopy(_ preview: RecordCopyPreview) async throws -> RecordCopyOutcome+ func inspectRecordCopyOutcome(_ preview: RecordCopyPreview) async throws -> RecordCopyInspection+ func updateWorkWithMembershipReceipt(id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar) async throws -> MembershipWriteReceipt+ func commitSeriesEditsWithMembershipReceipt(seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit]) async throws -> MembershipWriteReceipt+ func recordCopyOffer(destinationWorkID: UUID, seriesID: UUID) async throws -> RecordCopySeriesOffer? 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@@ -805,6 +812,27 @@ public extension LibraryProviding { extension LibraryRepository: LibraryProviding {} extension LibraryProviding {+ public func updateWorkWithMembershipReceipt(id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar) async throws -> MembershipWriteReceipt {+ throw LibraryRepositoryError.invalidInput(operation: "saving membership", reason: "Membership receipts are unavailable")+ }+ public func commitSeriesEditsWithMembershipReceipt(seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit]) async throws -> MembershipWriteReceipt {+ throw LibraryRepositoryError.invalidInput(operation: "saving membership", reason: "Membership receipts are unavailable")+ }+ public func recordCopyOffer(destinationWorkID: UUID, seriesID: UUID) async throws -> RecordCopySeriesOffer? {+ throw LibraryRepositoryError.invalidInput(operation: "reading series offer", reason: "Record copy offers are unavailable")+ }+ public func recordCopyContext(sourceWorkID: UUID) async throws -> RecordCopyContext {+ throw LibraryRepositoryError.invalidInput(operation: "copying records", reason: "Record copying is unavailable")+ }+ public func previewRecordCopy(sourceWorkID: UUID, destinationWorkID: UUID, selections: [RecordCopySelection], includeNotes: Bool) async throws -> RecordCopyPreview {+ throw LibraryRepositoryError.invalidInput(operation: "copying records", reason: "Record copying is unavailable")+ }+ public func commitRecordCopy(_ preview: RecordCopyPreview) async throws -> RecordCopyOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "copying records", reason: "Record copying is unavailable")+ }+ public func inspectRecordCopyOutcome(_ preview: RecordCopyPreview) async throws -> RecordCopyInspection {+ throw LibraryRepositoryError.invalidInput(operation: "copying records", reason: "Record copying is unavailable")+ } /// The full-tier pass, which is every trigger but the arrival debounce. @discardableResult public func reconcileAfterSync() async throws -> ReconciliationOutcome {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swiftnew file mode 100644index 00000000..b7c86be7--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swift@@ -0,0 +1,361 @@+import Foundation+import SwiftData++extension LibraryRepository {+ public func recordCopyContext(sourceWorkID: UUID) async throws -> RecordCopyContext {+ try await withLockedContext(mode: .shared, operation: "reading copy choices") { context in+ let groups = try Self.copyWorkGroups(context)+ guard let source = groups[sourceWorkID] else {+ throw Self.copyError("The source work is unavailable.")+ }+ let links = try context.fetch(FetchDescriptor<WorkLink>()).map {+ RecordCopyLink(a: $0.lowerWorkID, b: $0.higherWorkID)+ }+ let eligible = Set(+ RecordCopyPlanning.eligibleWorks(+ from: sourceWorkID, works: groups.values.map(Self.copyWork), links: links+ ).map(\.id))+ // Keep the existing complete picker context and its ordering/qualifiers.+ let candidates = try Self.pickerCandidates(context: context, excluding: nil) { work in+ if case .torn = work.groupState { return "Being resolved" }+ return nil+ }+ guard let sourceCandidate = candidates.first(where: { $0.id == sourceWorkID }) else {+ throw Self.copyError("The source work is unavailable.")+ }+ let records = try Self.copyRecords(work: source, context: context)+ return RecordCopyContext(+ source: sourceCandidate, destinations: candidates.filter { eligible.contains($0.id) },+ records: records)+ }+ }++ public func previewRecordCopy(+ sourceWorkID: UUID, destinationWorkID: UUID,+ selections: [RecordCopySelection], includeNotes: Bool+ ) async throws -> RecordCopyPreview {+ try await withLockedContext(mode: .shared, operation: "previewing record copies") { context in+ try Self.copyPreview(+ sourceWorkID: sourceWorkID, destinationWorkID: destinationWorkID,+ selections: selections, includeNotes: includeNotes, context: context)+ }+ }++ public func commitRecordCopy(_ preview: RecordCopyPreview) async throws -> RecordCopyOutcome {+ try await withLockedContext(mode: .exclusive, operation: "copying records") { context in+ do {+ let fresh: RecordCopyPreview+ do {+ fresh = try Self.copyPreview(+ sourceWorkID: preview.sourceWorkID, destinationWorkID: preview.destinationWorkID,+ selections: preview.rows.map {+ .init(kind: $0.kind, sourceID: $0.sourceID, destinationID: $0.destinationID)+ },+ includeNotes: preview.includeNotes, context: context)+ } catch {+ Self.rollbackCopy(context)+ return .refused(reason: "The copy choices changed. Refresh the preview.")+ }+ guard fresh.basis == preview.basis,+ fresh.rows.map(\.payload) == preview.rows.map(\.payload),+ !preview.rows.filter({ $0.choice == .copy }).isEmpty,+ RecordCopyPlanning.unacknowledgedClashes(+ preview.rows, destination: fresh.basis.destination+ ).isEmpty,+ try Self.inspectCopy(preview, context: context) == .absent+ else {+ Self.rollbackCopy(context)+ return .refused(+ reason: "The copy preview or its confirmations changed. Refresh before copying.")+ }+ let groups = try Self.copyWorkGroups(context)+ guard let destination = groups[preview.destinationWorkID] else {+ throw Self.copyError("The destination is unavailable.")+ }+ let timestamp = MillisecondInstant.quantize(self.clock.now())+ for row in preview.rows where row.choice == .copy {+ switch row.kind {+ case .character:+ try Self.insertCopy(+ row, CharacterRecord.self, CharacterSuppression.self, into: destination,+ timestamp: timestamp, context: context)+ case .place:+ try Self.insertCopy(+ row, Place.self, PlaceSuppression.self, into: destination, timestamp: timestamp,+ context: context)+ }+ }+ try self.commit(context, operation: "atomically copying records")+ return .committed(+ createdIDs: preview.rows.filter { $0.choice == .copy }.map(\.destinationID),+ skippedCount: preview.rows.filter { $0.choice == .skip }.count)+ } catch {+ Self.rollbackCopy(context)+ throw error+ }+ }+ }++ public func inspectRecordCopyOutcome(_ preview: RecordCopyPreview) async throws+ -> RecordCopyInspection+ {+ try await withLockedContext(mode: .exclusive, operation: "checking record copy outcome") {+ context in+ try Self.inspectCopy(preview, context: context)+ }+ }++ static func copyError(_ reason: String) -> LibraryRepositoryError {+ .invalidInput(operation: "copying records", reason: reason)+ }++ static func copyWorkGroups(_ context: ModelContext) throws -> [UUID: WorkGroup] {+ try workGroups(+ context.fetch(FetchDescriptor<Work>()), types: workTypeDirectory(context: context))+ }++ static func copyWork(_ group: WorkGroup) -> RecordCopyWork {+ RecordCopyWork(+ id: group.id, title: group.carrier.displayTitle, membership: presentedMembership(of: group),+ unavailableReason: group.isTorn ? "Being resolved" : nil)+ }++ /// Work-scoped discovery is followed by whole-ID reads, for BOTH tables.+ static func copyRecords<Row: RecordRow>(_ type: Row.Type, work: WorkGroup, context: ModelContext)+ throws -> [RecordCopyRecord]+ {+ let ids = Array(Set(try Row.rows(of: work.rows, context: context).map(\.recordID)))+ let groups = recordGroups(try Row.rows(ids: ids, context: context))+ let index = StoryPositionIndex(+ entries: storyPositionInputs(rows: work.rows.flatMap(\.entryValues)))+ return RecordRanking.rankGroups(groups, index: index).map { group in+ let content = group.presentedContent+ let keys = Set(group.rows.map(\.nameKey))+ let validIdentity = group.rows.allSatisfy { $0.ownerWorkID == work.id } && keys.count == 1+ let variantKeys = Set(+ group.rows.flatMap { [$0.name] + $0.aliases }.map(RecordNameKey.normalize).filter {+ !$0.isEmpty+ })+ return RecordCopyRecord(+ id: group.id, kind: Row.kind, name: content.name, aliases: content.aliases,+ note: content.note,+ retainedKeys: keys, variantKeys: variantKeys,+ unavailableReason: validIdentity+ ? (group.isTorn ? "Being resolved" : nil) : "Inconsistent ownership or matching keys")+ }+ }++ static func copyRecords(work: WorkGroup, context: ModelContext) throws -> [RecordCopyRecord] {+ try copyRecords(CharacterRecord.self, work: work, context: context)+ + copyRecords(Place.self, work: work, context: context)+ }++ private static func copyPreview(+ sourceWorkID: UUID, destinationWorkID: UUID,+ selections: [RecordCopySelection], includeNotes: Bool, context: ModelContext+ ) throws -> RecordCopyPreview {+ let works = try copyWorkGroups(context)+ guard sourceWorkID != destinationWorkID, let source = works[sourceWorkID],+ let destination = works[destinationWorkID],+ !source.isTorn, !destination.isTorn+ else { throw copyError("A work is missing or being resolved.") }+ let linked = try context.fetch(FetchDescriptor<WorkLink>()).contains {+ ($0.lowerWorkID == sourceWorkID && $0.higherWorkID == destinationWorkID)+ || ($0.lowerWorkID == destinationWorkID && $0.higherWorkID == sourceWorkID)+ }+ let sourceSeries = presentedMembership(of: source)?.seriesID+ let destinationSeries = presentedMembership(of: destination)?.seriesID+ guard linked || (sourceSeries != nil && sourceSeries == destinationSeries) else {+ throw copyError("Save a relationship or shared series first.")+ }+ guard+ Set(selections.map { RecordCopyIdentity(kind: $0.kind, id: $0.sourceID) }).count+ == selections.count,+ Set(selections.map { RecordCopyIdentity(kind: $0.kind, id: $0.destinationID) }).count+ == selections.count+ else { throw copyError("A record is selected more than once.") }+ let sourceRecords = try copyRecords(work: source, context: context)+ let destinationRecords = try copyRecords(work: destination, context: context)+ guard+ !destinationRecords.contains(where: {+ $0.unavailableReason == "Inconsistent ownership or matching keys"+ })+ else {+ throw copyError("A destination record has inconsistent ownership or matching keys.")+ }+ let selected = try selections.map { selection in+ guard+ let record = sourceRecords.first(where: {+ $0.kind == selection.kind && $0.id == selection.sourceID+ }), record.unavailableReason == nil+ else {+ throw copyError("A selected record is missing or being resolved.")+ }+ return record+ }+ let rows = zip(+ RecordCopyPlanning.initialPlan(+ selected: selected, destination: destinationRecords, includeNotes: includeNotes), selections+ ).map { row, selection in+ RecordCopyPlannedRow(+ sourceID: row.sourceID, destinationID: selection.destinationID, kind: row.kind,+ payload: row.payload,+ choice: row.choice, informationalClashes: row.informationalClashes)+ }+ func payloadBasis(_ record: RecordCopyRecord, notes: Bool) -> RecordCopyRecord {+ RecordCopyRecord(+ id: record.id, kind: record.kind, name: record.name, aliases: record.aliases,+ note: notes ? record.note : "", retainedKeys: record.retainedKeys,+ variantKeys: record.variantKeys, unavailableReason: record.unavailableReason)+ }+ return RecordCopyPreview(+ sourceWorkID: sourceWorkID, destinationWorkID: destinationWorkID, includeNotes: includeNotes,+ rows: rows,+ basis: .init(+ sourceSeriesID: sourceSeries, destinationSeriesID: destinationSeries,+ directlyLinked: linked,+ selected: selected.map { payloadBasis($0, notes: includeNotes) },+ destination: destinationRecords.map { payloadBasis($0, notes: false) }.sorted {+ $0.kind.rawValue == $1.kind.rawValue+ ? $0.id.uuidString < $1.id.uuidString : $0.kind.rawValue < $1.kind.rawValue+ }))+ }++ private static func inspectCopy(_ preview: RecordCopyPreview, context: ModelContext) throws+ -> RecordCopyInspection+ {+ let planned = preview.rows.filter { $0.choice == .copy }+ guard !planned.isEmpty else { return .absent }+ var present = 0+ for row in planned {+ let matches: Bool?+ switch row.kind {+ case .character:+ matches = try copiedIdentityMatches(+ row, CharacterRecord.self, owner: preview.destinationWorkID, context: context)+ case .place:+ matches = try copiedIdentityMatches(+ row, Place.self, owner: preview.destinationWorkID, context: context)+ }+ if matches == false { return .conflicting }+ if matches == true { present += 1 }+ }+ return present == 0 ? .absent : (present == planned.count ? .committed : .conflicting)+ }++ private static func copiedIdentityMatches<Row: RecordRow>(+ _ row: RecordCopyPlannedRow, _ type: Row.Type, owner: UUID, context: ModelContext+ ) throws -> Bool? {+ let rows = try Row.rows(ids: [row.destinationID], context: context)+ guard !rows.isEmpty else { return nil }+ return rows.allSatisfy { stored in+ stored.ownerWorkID == owner && stored.nameKey == row.payload.nameKey+ && stored.name == row.payload.name+ && stored.aliases.sorted() == row.payload.aliases.sorted()+ && stored.note == row.payload.note+ }+ }++ private static func insertCopy<Row: RecordRow, Suppression: SuppressionRow>(+ _ row: RecordCopyPlannedRow, _ type: Row.Type,+ _ suppressionType: Suppression.Type, into work: WorkGroup, timestamp: Date,+ context: ModelContext+ ) throws {+ let created = Row.make(+ id: row.destinationID, name: row.payload.name, nameKey: row.payload.nameKey,+ aliases: row.payload.aliases,+ note: row.payload.note, facts: [], timestamp: timestamp, work: nil)+ context.insert(created)+ created.attach(to: work.rows.first, archivedWorkID: work.id)+ let suppressions = try Suppression.rows(of: work.rows, context: context)+ if suppressions.contains(where: {+ $0.kindRaw == CharacterSuppressionKind.candidate.rawValue && $0.nameKey == row.payload.nameKey+ }) {+ _ = writeSuppression(+ kind: .candidate, nameKey: row.payload.nameKey, source: nil, evidence: nil,+ status: .cleared,+ workRows: work.rows, suppressionRows: suppressions, timestamp: timestamp, context: context)+ }+ }++ private static func rollbackCopy(_ context: ModelContext) {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<CharacterRecord>())+ _ = try? context.fetch(FetchDescriptor<Place>())+ _ = try? context.fetch(FetchDescriptor<CharacterSuppression>())+ _ = try? context.fetch(FetchDescriptor<PlaceSuppression>())+ }+}++extension LibraryRepository {+ static func rollbackMembershipWrite(_ context: ModelContext) {+ context.rollback()+ _ = try? context.fetch(FetchDescriptor<Work>())+ _ = try? context.fetch(FetchDescriptor<Series>())+ _ = try? context.fetch(FetchDescriptor<WorkCredit>())+ }++ public func recordCopyOffer(destinationWorkID: UUID, seriesID: UUID) async throws+ -> RecordCopySeriesOffer?+ {+ try await withLockedContext(mode: .shared, operation: "reading series copy offer") { context in+ let groups = try Self.copyWorkGroups(context)+ // Half-arrived or disagreeing order evidence cannot establish a predecessor.+ let relevant = groups.values.filter { $0.rows.contains { $0.seriesID == seriesID } }+ guard+ relevant.allSatisfy({ group in+ group.rows.allSatisfy {+ ($0.seriesID == nil && $0.seriesPosition == nil)+ || GroupOrdering.membership(of: $0) != nil+ }+ && Set(group.rows.map { GroupOrdering.membership(of: $0) }).count == 1+ })+ else { return nil }+ guard let destinationGroup = groups[destinationWorkID],+ let destinationMembership = Self.copyWork(destinationGroup).membership,+ destinationMembership.seriesID == seriesID+ else { return nil }+ let members = try relevant.map { group in+ let work = Self.copyWork(group)+ let eligibleRecordCount: Int+ if let position = work.membership?.position,+ position < destinationMembership.position+ {+ eligibleRecordCount = try Self.copyRecords(work: group, context: context).filter {+ $0.unavailableReason == nil+ }.count+ } else {+ eligibleRecordCount = 0+ }+ // Preserve every member's order evidence; availability reads are only+ // useful for strictly preceding members, never the destination or later works.+ return RecordCopyOfferMember(work: work, eligibleRecordCount: eligibleRecordCount)+ }+ guard+ let basis = RecordCopyOfferPlanning.predecessor(+ destinationID: destinationWorkID, seriesID: seriesID, members: members)+ else { return nil }+ let candidates = try Self.pickerCandidates(context: context, excluding: nil) { work in+ if case .torn = work.groupState { return "Being resolved" }+ return nil+ }+ guard let destination = candidates.first(where: { $0.id == destinationWorkID }) else {+ return nil+ }+ let availableIDs = Set(basis.availableSources.map { $0.work.id })+ let bucketIDs = Set(basis.bucket.map { $0.work.id })+ let unavailable = candidates.filter {+ bucketIDs.contains($0.id) && !availableIDs.contains($0.id)+ }.map { candidate in+ WorkPickerCandidate(+ work: candidate.work,+ unavailableReason: candidate.unavailableReason ?? "No available characters or places")+ }+ return RecordCopySeriesOffer(+ destination: destination,+ series: try Self.seriesDirectory(context: context).display(of: seriesID)!,+ sources: candidates.filter { availableIDs.contains($0.id) },+ unavailablePredecessors: unavailable, basis: basis)+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swiftindex 0f66bc25..8360c84d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift@@ -306,6 +306,12 @@ extension LibraryRepository { public func commitSeriesEdits( seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit] ) async throws -> LibraryWriteOutcome {+ try await commitSeriesEditsWithMembershipReceipt(seriesID: seriesID, name: name, notes: notes, members: members).outcome+ }++ public func commitSeriesEditsWithMembershipReceipt(+ seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit]+ ) async throws -> MembershipWriteReceipt { let trimmedName = try SeriesName.validate(name) let trimmedNotes = notes.trimmingCharacters(in: .whitespacesAndNewlines) for member in members {@@ -329,25 +335,38 @@ extension LibraryRepository { return try await withLockedContext( mode: .exclusive, operation: "committing series edits" ) { context in+ var didCommit = false+ defer { if !didCommit { Self.rollbackMembershipWrite(context) } } let rows = try context.fetch( FetchDescriptor<Series>(predicate: #Predicate { $0.id == seriesID })) guard !rows.isEmpty else { throw LibraryRepositoryError.recordNotFound(type: "Series", id: seriesID) }+ // Resolve every addressed basis against the transaction-initial state.+ // Redirect aliases must not mistake this batch's earlier write for a peer edit.+ var resolvedEdits: [(edit: SeriesMemberEdit, group: WorkGroup)] = []+ var initial: [UUID: [SeriesMembership]] = [:]+ var addressed: [UUID: Set<UUID>] = [:]+ var groups: [UUID: WorkGroup] = [:]+ for member in members {+ let group: WorkGroup+ switch try self.resolveWorkWriteTarget(id: member.workID, basis: member.basis, context: context) {+ case .refused(let conflict): return MembershipWriteReceipt(outcome: .conflict(conflict))+ case .resolved(let resolved): group = resolved+ }+ if let refusal = Self.tornRefusal(group) { return MembershipWriteReceipt(outcome: refusal) }+ if initial[group.id] == nil { initial[group.id] = Self.presentedMembership(of: group).map { [$0] } ?? [] }+ addressed[group.id, default: []].insert(member.workID)+ groups[group.id] = group+ resolvedEdits.append((member, group))+ } let timestamp = MillisecondInstant.quantize(self.clock.now()) for row in rows where row.name != trimmedName || row.notes != trimmedNotes { row.name = trimmedName row.notes = trimmedNotes row.modifiedAt = timestamp }- for member in members {- let group: WorkGroup- switch try self.resolveWorkWriteTarget(- id: member.workID, basis: member.basis, context: context) {- case .refused(let conflict): return .conflict(conflict)- case .resolved(let resolved): group = resolved- }- if let refusal = Self.tornRefusal(group) { return refusal }+ for (member, group) in resolvedEdits { for work in group.rows where work.seriesID != member.membership?.seriesID || work.seriesPosition != member.membership?.position {@@ -359,7 +378,11 @@ extension LibraryRepository { } } try self.commit(context, operation: "committing series edits")- return .committed+ didCommit = true+ return MembershipWriteReceipt(outcome: .committed, transitions: groups.values.sorted { $0.id.uuidString < $1.id.uuidString }.map { group in+ .init(addressedWorkIDs: Array(addressed[group.id] ?? []), resolvedWorkID: group.id,+ before: initial[group.id]?.first, after: Self.presentedMembership(of: group))+ }) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex 03ec56da..f8acb45f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -1483,6 +1483,12 @@ public actor LibraryRepository { public func updateWork( id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar ) async throws -> LibraryWriteOutcome {+ try await updateWorkWithMembershipReceipt(id: id, basis: basis, draft: draft, calendar: calendar).outcome+ }++ public func updateWorkWithMembershipReceipt(+ id: UUID, basis: WorkEditBasis, draft: WorkMetadataDraft, calendar: Calendar+ ) async throws -> MembershipWriteReceipt { guard !draft.displayTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw LibraryRepositoryError.invalidInput(operation: "updating Work", reason: "display title is blank") }@@ -1502,12 +1508,15 @@ public actor LibraryRepository { } } return try await withLockedContext(mode: .exclusive, operation: "updating Work") { context in+ var didCommit = false+ defer { if !didCommit { Self.rollbackMembershipWrite(context) } } let group: WorkGroup switch try self.resolveWorkWriteTarget(id: id, basis: basis, context: context) {- case .refused(let conflict): return .conflict(conflict)+ case .refused(let conflict): return MembershipWriteReceipt(outcome: .conflict(conflict)) case .resolved(let resolved): group = resolved }- if let refusal = Self.tornRefusal(group) { return refusal }+ if let refusal = Self.tornRefusal(group) { return MembershipWriteReceipt(outcome: refusal) }+ let initialMembership = Self.presentedMembership(of: group) // Req 2.4: a series the reader **chose** has to still exist. A pair // carried unchanged from the basis is left alone whatever the@@ -1518,7 +1527,7 @@ public actor LibraryRepository { chosen != basis.membership?.seriesID, try Self.seriesDirectory(context: context)[chosen] == nil {- return .conflict(.seriesMissing(recordID: id, seriesID: chosen))+ return MembershipWriteReceipt(outcome: .conflict(.seriesMissing(recordID: id, seriesID: chosen))) } let timestamp = MillisecondInstant.quantize(clock.now())@@ -1531,7 +1540,7 @@ public actor LibraryRepository { creditsDraft, toWork: group.id, addressedAs: id, context: context, timestamp: timestamp) {- return .conflict(conflict)+ return MembershipWriteReceipt(outcome: .conflict(conflict)) } // Rebase under the values still stored, before the editor replaces // the status or schedule. A raw spelling change alone is not a@@ -1650,7 +1659,10 @@ public actor LibraryRepository { reason: String(describing: error) ) }- return .committed+ didCommit = true+ return MembershipWriteReceipt(outcome: .committed, transitions: [+ .init(addressedWorkIDs: [id], resolvedWorkID: group.id, before: initialMembership, after: Self.presentedMembership(of: group))+ ]) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swift b/Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swiftnew file mode 100644index 00000000..4ba7e0cc--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swift@@ -0,0 +1,371 @@+import Foundation++/// Immutable inputs to copy planning; no persistence objects or extracted evidence.+public struct RecordCopyWork: Equatable, Sendable, Identifiable {+ public let id: UUID+ public let title: String+ public let membership: SeriesMembership?+ public let unavailableReason: String?+ public init(+ id: UUID, title: String, membership: SeriesMembership? = nil, unavailableReason: String? = nil+ ) {+ self.id = id+ self.title = title+ self.membership = membership+ self.unavailableReason = unavailableReason+ }+}++public struct RecordCopyLink: Equatable, Sendable {+ public let a: UUID+ public let b: UUID+ public init(a: UUID, b: UUID) {+ self.a = a+ self.b = b+ }+}++public struct RecordCopyRecord: Equatable, Sendable {+ public let id: UUID+ public let kind: RecordKind+ public let name: String+ public let aliases: [String]+ public let note: String+ public let retainedKeys: Set<String>+ /// Includes every torn variant's current name/aliases, for destination matching.+ public let variantKeys: Set<String>+ public var unavailableReason: String?+ public init(+ id: UUID, kind: RecordKind, name: String, aliases: [String] = [], note: String = "",+ retainedKeys: Set<String> = [], variantKeys: Set<String> = [], unavailableReason: String? = nil+ ) {+ self.id = id+ self.kind = kind+ self.name = name+ self.aliases = aliases.sorted()+ self.note = note+ self.retainedKeys = retainedKeys+ self.variantKeys = variantKeys+ self.unavailableReason = unavailableReason+ }+ public var identity: RecordCopyIdentity { .init(kind: kind, id: id) }+ public var portableKeys: Set<String> {+ Set(([name] + aliases).map(RecordNameKey.normalize).filter { !$0.isEmpty })+ }+ public var destinationKeys: Set<String> {+ portableKeys.union(retainedKeys.map(RecordNameKey.normalize)).union(variantKeys).filter {+ !$0.isEmpty+ }+ }+}++public struct RecordCopyPayload: Equatable, Sendable {+ public let name: String+ public let nameKey: String+ public let aliases: [String]+ public let note: String+ public init(record: RecordCopyRecord, includeNotes: Bool) {+ name = record.name+ nameKey = RecordNameKey.normalize(record.name)+ aliases = record.aliases+ note = includeNotes ? record.note : ""+ }+ public var keys: Set<String> {+ Set(([name] + aliases).map(RecordNameKey.normalize).filter { !$0.isEmpty })+ }+}++public enum RecordCopyChoice: Equatable, Sendable { case skip, copy }++/// Concrete identity plus overlapping keys: changing the plan invalidates old consent.+public struct RecordCopyClash: Equatable, Hashable, Sendable {+ public let recordID: UUID+ public let name: String+ public let keys: Set<String>+ public let isExistingDestination: Bool+}++public struct RecordCopyPlannedRow: Equatable, Sendable, Identifiable {+ public let sourceID: UUID+ public let destinationID: UUID+ public let kind: RecordKind+ public let payload: RecordCopyPayload+ public var choice: RecordCopyChoice+ public let informationalClashes: Set<RecordCopyClash>+ public var acknowledgedClashes: Set<RecordCopyClash>+ public var id: UUID { destinationID }+ public init(+ sourceID: UUID, destinationID: UUID = UUID(), kind: RecordKind, payload: RecordCopyPayload,+ choice: RecordCopyChoice, informationalClashes: Set<RecordCopyClash> = [],+ acknowledgedClashes: Set<RecordCopyClash> = []+ ) {+ self.sourceID = sourceID+ self.destinationID = destinationID+ self.kind = kind+ self.payload = payload+ self.choice = choice+ self.informationalClashes = informationalClashes+ self.acknowledgedClashes = acknowledgedClashes+ }+}++public enum RecordCopyPlanning {+ public static func eligibleWorks(+ from sourceID: UUID, works: [RecordCopyWork], links: [RecordCopyLink]+ ) -> [RecordCopyWork] {+ guard let source = works.first(where: { $0.id == sourceID }), source.unavailableReason == nil+ else { return [] }+ let linked = Set(links.compactMap { $0.a == sourceID ? $0.b : ($0.b == sourceID ? $0.a : nil) })+ var seen: Set<UUID> = []+ return works.filter { candidate in+ candidate.id != sourceID && candidate.unavailableReason == nil+ && seen.insert(candidate.id).inserted+ && (linked.contains(candidate.id)+ || (source.membership != nil+ && source.membership?.seriesID == candidate.membership?.seriesID))+ }.sorted {+ let comparison = $0.title.localizedStandardCompare($1.title)+ return comparison == .orderedSame+ ? $0.id.uuidString < $1.id.uuidString : comparison == .orderedAscending+ }+ }++ public static func initialPlan(+ selected: [RecordCopyRecord], destination: [RecordCopyRecord], includeNotes: Bool+ ) -> [RecordCopyPlannedRow] {+ selected.filter { $0.unavailableReason == nil }.map { source in+ let conflicts = Set(+ destination.filter { $0.kind == source.kind }.compactMap { other -> RecordCopyClash? in+ let keys = source.portableKeys.intersection(other.destinationKeys)+ return keys.isEmpty+ ? nil+ : .init(recordID: other.id, name: other.name, keys: keys, isExistingDestination: true)+ }+ + selected.filter {+ $0.kind == source.kind && $0.id != source.id && $0.unavailableReason == nil+ }.compactMap { other -> RecordCopyClash? in+ let keys = source.portableKeys.intersection(other.portableKeys)+ return keys.isEmpty+ ? nil+ : .init(+ recordID: other.id, name: other.name, keys: keys, isExistingDestination: false)+ })+ return RecordCopyPlannedRow(+ sourceID: source.id, kind: source.kind,+ payload: .init(record: source, includeNotes: includeNotes),+ choice: conflicts.isEmpty ? .copy : .skip, informationalClashes: conflicts)+ }+ }++ public static func actualClashes(+ for row: RecordCopyPlannedRow, in rows: [RecordCopyPlannedRow], destination: [RecordCopyRecord]+ ) -> Set<RecordCopyClash> {+ guard row.choice == .copy else { return [] }+ let existing = destination.filter { $0.kind == row.kind }.compactMap {+ other -> RecordCopyClash? in+ let keys = row.payload.keys.intersection(other.destinationKeys)+ return keys.isEmpty+ ? nil : .init(recordID: other.id, name: other.name, keys: keys, isExistingDestination: true)+ }+ let planned = rows.filter {+ $0.kind == row.kind && $0.sourceID != row.sourceID && $0.choice == .copy+ }.compactMap { other -> RecordCopyClash? in+ let keys = row.payload.keys.intersection(other.payload.keys)+ return keys.isEmpty+ ? nil+ : .init(+ recordID: other.sourceID, name: other.payload.name, keys: keys,+ isExistingDestination: false)+ }+ return Set(existing + planned)+ }++ public static func unacknowledgedClashes(+ _ rows: [RecordCopyPlannedRow], destination: [RecordCopyRecord]+ ) -> [RecordCopyPlannedRow] {+ rows.filter {+ !actualClashes(for: $0, in: rows, destination: destination).isSubset(+ of: $0.acknowledgedClashes)+ }+ }+}++/// Kind is part of identity: a character and a place may carry the same UUID.+public struct RecordCopyIdentity: Equatable, Hashable, Sendable {+ public let kind: RecordKind+ public let id: UUID+ public init(kind: RecordKind, id: UUID) {+ self.kind = kind+ self.id = id+ }+ public func hash(into hasher: inout Hasher) {+ hasher.combine(kind.rawValue)+ hasher.combine(id)+ }+}++public struct RecordCopySelection: Equatable, Sendable {+ public let kind: RecordKind+ public let sourceID: UUID+ public let destinationID: UUID+ public init(kind: RecordKind, sourceID: UUID, destinationID: UUID = UUID()) {+ self.kind = kind+ self.sourceID = sourceID+ self.destinationID = destinationID+ }+}++public struct RecordCopyContext: Equatable, Sendable {+ public let source: WorkPickerCandidate+ public let destinations: [WorkPickerCandidate]+ public let records: [RecordCopyRecord]+ public init(+ source: WorkPickerCandidate, destinations: [WorkPickerCandidate], records: [RecordCopyRecord]+ ) {+ self.source = source+ self.destinations = destinations+ self.records = records+ }+}++public struct RecordCopyBasis: Equatable, Sendable {+ public let sourceSeriesID: UUID?+ public let destinationSeriesID: UUID?+ public let directlyLinked: Bool+ public let selected: [RecordCopyRecord]+ public let destination: [RecordCopyRecord]+ public init(+ sourceSeriesID: UUID?, destinationSeriesID: UUID?, directlyLinked: Bool,+ selected: [RecordCopyRecord], destination: [RecordCopyRecord]+ ) {+ self.sourceSeriesID = sourceSeriesID+ self.destinationSeriesID = destinationSeriesID+ self.directlyLinked = directlyLinked+ self.selected = selected+ self.destination = destination+ }+}++public struct RecordCopyPreview: Equatable, Sendable {+ public let sourceWorkID: UUID+ public let destinationWorkID: UUID+ public let includeNotes: Bool+ public var rows: [RecordCopyPlannedRow]+ public let basis: RecordCopyBasis+ public init(+ sourceWorkID: UUID, destinationWorkID: UUID, includeNotes: Bool,+ rows: [RecordCopyPlannedRow], basis: RecordCopyBasis+ ) {+ self.sourceWorkID = sourceWorkID+ self.destinationWorkID = destinationWorkID+ self.includeNotes = includeNotes+ self.rows = rows+ self.basis = basis+ }+}++public enum RecordCopyOutcome: Equatable, Sendable {+ case committed(createdIDs: [UUID], skippedCount: Int)+ case refused(reason: String)+}++public enum RecordCopyInspection: Equatable, Sendable {+ case committed+ /// No automatic retry: absence could also mean deletion after a commit.+ case absent+ case conflicting+}++public struct WorkMembershipTransition: Equatable, Sendable {+ public let addressedWorkIDs: [UUID]+ public let resolvedWorkID: UUID+ public let before: SeriesMembership?+ public let after: SeriesMembership?+ public var isJoin: Bool { after != nil && before?.seriesID != after?.seriesID }+ public init(+ addressedWorkIDs: [UUID], resolvedWorkID: UUID, before: SeriesMembership?,+ after: SeriesMembership?+ ) {+ self.addressedWorkIDs = addressedWorkIDs.sorted { $0.uuidString < $1.uuidString }+ self.resolvedWorkID = resolvedWorkID+ self.before = before+ self.after = after+ }+}++public struct MembershipWriteReceipt: Equatable, Sendable {+ public let outcome: LibraryWriteOutcome+ public let transitions: [WorkMembershipTransition]+ public init(outcome: LibraryWriteOutcome, transitions: [WorkMembershipTransition] = []) {+ self.outcome = outcome+ self.transitions = transitions+ }+}++public struct RecordCopyOfferMember: Equatable, Sendable {+ public let work: RecordCopyWork+ public let eligibleRecordCount: Int+ public let membershipIsConsistent: Bool+ public init(work: RecordCopyWork, eligibleRecordCount: Int, membershipIsConsistent: Bool = true) {+ self.work = work+ self.eligibleRecordCount = eligibleRecordCount+ self.membershipIsConsistent = membershipIsConsistent+ }+ public var isAvailable: Bool { work.unavailableReason == nil && eligibleRecordCount > 0 }+}++public struct RecordCopyPredecessorProjection: Equatable, Sendable {+ public let destinationID: UUID+ public let seriesID: UUID+ public let destinationPosition: Double+ public let position: Double+ public let bucket: [RecordCopyOfferMember]+ public var requiresSourceChoice: Bool { bucket.count > 1 }+ public var availableSources: [RecordCopyOfferMember] { bucket.filter(\.isAvailable) }+}++public enum RecordCopyOfferPlanning {+ public static func predecessor(+ destinationID: UUID, seriesID: UUID, members: [RecordCopyOfferMember]+ ) -> RecordCopyPredecessorProjection? {+ let seriesMembers = members.filter { $0.work.membership?.seriesID == seriesID }+ guard seriesMembers.allSatisfy(\.membershipIsConsistent),+ let destination = seriesMembers.first(where: { $0.work.id == destinationID }),+ destination.work.unavailableReason == nil,+ let destinationPosition = destination.work.membership?.position, destinationPosition.isFinite+ else { return nil }+ let earlier = seriesMembers.filter {+ ($0.work.membership?.position ?? .infinity) < destinationPosition+ }+ guard+ let position = earlier.compactMap({ $0.work.membership?.position }).filter(\.isFinite).max()+ else { return nil }+ let bucket = earlier.filter { $0.work.membership?.position == position }.sorted {+ $0.work.id.uuidString < $1.work.id.uuidString+ }+ guard bucket.contains(where: \.isAvailable) else { return nil }+ return RecordCopyPredecessorProjection(+ destinationID: destinationID, seriesID: seriesID, destinationPosition: destinationPosition,+ position: position, bucket: bucket)+ }+}++public struct RecordCopySeriesOffer: Equatable, Sendable {+ public let destination: WorkPickerCandidate+ public let series: SeriesDisplay+ public let sources: [WorkPickerCandidate]+ public let unavailablePredecessors: [WorkPickerCandidate]+ public let basis: RecordCopyPredecessorProjection+ public var requiresSourceChoice: Bool { basis.requiresSourceChoice }+ public var precedingPosition: Double { basis.position }+ public init(+ destination: WorkPickerCandidate, series: SeriesDisplay, sources: [WorkPickerCandidate],+ unavailablePredecessors: [WorkPickerCandidate], basis: RecordCopyPredecessorProjection+ ) {+ self.destination = destination+ self.series = series+ self.sources = sources+ self.unavailablePredecessors = unavailablePredecessors+ self.basis = basis+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureResolverTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureResolverTests.swiftindex 068235d6..b840b9be 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureResolverTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCaptureResolverTests.swift@@ -15,6 +15,72 @@ struct ChapterCaptureResolverTests { entries: entries, captureDefault: captureDefault) } + @Test("Ordinary new and saved pages keep chapter alternatives optional without an extra confirmation")+ func optionalChapterPresentation() {+ let id = UUID()+ let saved = ChapterCaptureEntry(id: id, workID: work, sourceURLs: [page])+ for projection in [project([]), project([saved])] {+ #expect(!projection.showsChapterChoicesInitially)+ #expect(projection.offersAnotherChapter)+ }+ #expect(project([]).resolution == .newEntry)+ #expect(project([saved]).resolution == .update(entryID: id))+ let clear = project([saved], evidence: [evidence("12")])+ #expect(clear.showsChapterChoicesInitially) // incomparable saved evidence still requires review+ let detected = project([], evidence: [evidence("12")])+ #expect(!detected.showsChapterChoicesInitially && !detected.offersAnotherChapter)+ }++ @Test("Shared-page ambiguity and multiple-page drafts keep their chapter choices visible")+ func requiredChapterPresentation() {+ let entries = [ChapterCaptureEntry(id: UUID(), workID: work, sourceURLs: [page]),+ ChapterCaptureEntry(id: UUID(), workID: work, sourceURLs: [page])]+ #expect(project(entries).showsChapterChoicesInitially)+ #expect(project(entries, captureDefault: .multipleChaptersPerPage).showsChapterChoicesInitially)+ #expect(project([], captureDefault: .multipleChaptersPerPage).showsChapterChoicesInitially)+ let detected = project([], evidence: [evidence("12")], captureDefault: .multipleChaptersPerPage)+ #expect(!detected.showsChapterChoicesInitially && !detected.offersAnotherChapter)+ }++ @Test("Automatic detected new and saved chapters do not present a correction prompt")+ func automaticDetectedCorrectionPresentation() {+ let id = UUID()+ let twelve = evidence("12")+ let saved = ChapterCaptureEntry(id: id, workID: work,+ bindings: [twelve.binding], sourceURLs: [page])+ for mode in [ChapterCaptureDefault.ordinary, .multipleChaptersPerPage] {+ let fresh = project([], evidence: [twelve], captureDefault: mode)+ let existing = project([saved], evidence: [twelve], captureDefault: mode)+ #expect(fresh.resolution == .newChapter(requiresConfirmation: false))+ #expect(existing.resolution == .update(entryID: id))+ for projection in [fresh, existing] {+ #expect(!projection.showsChapterChoicesInitially)+ #expect(!projection.evidence.isEmpty) // detected evidence remains intact+ #expect(!projection.offersAnotherChapter)+ }+ }+ }++ @Test("Removing share correction preserves required conflicting and incomparable chapter choices")+ func requiredChapterChoicesWithoutCorrection() {+ let id = UUID()+ let twelve = evidence("12")+ let manual = ChapterCaptureEntry(id: id, workID: work,+ target: .init(kind: .chapter, designation: "12"), sourceURLs: [page])+ let known = ChapterCaptureEntry(id: id, workID: work, bindings: [twelve.binding])+ for projection in [project([manual], evidence: [twelve]),+ project([known], evidence: [twelve, evidence("13")])] {+ if case .chooseChapter = projection.resolution {} else {+ Issue.record("Required review must not become an automatic capture")+ }+ #expect(projection.showsChapterChoicesInitially)+ }+ let unidentifiedWholePage = project([manual], captureDefault: .multipleChaptersPerPage)+ #expect(unidentifiedWholePage.resolution == .newChapter(requiresConfirmation: true))+ #expect(unidentifiedWholePage.showsChapterChoicesInitially)+ #expect(project([]).resolution == .newEntry)+ }+ @Test("Specific chapter evidence wins over a shared-page association in either mode") func specificWins() { let twelve = UUID(), thirteen = UUID()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ShareChapterCorrectionReachTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ShareChapterCorrectionReachTests.swiftnew file mode 100644index 00000000..b8a502e4--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ShareChapterCorrectionReachTests.swift@@ -0,0 +1,38 @@+import Foundation+import Testing++/// This source reach guard covers every branch of the shared view, including+/// expanded alternatives. It is not rendered incoming-extension acceptance.+@Suite("Share chapter selection never exposes detected-chapter correction")+struct ShareChapterCorrectionReachTests {+ private var projectDirectory: URL {+ var url = URL(fileURLWithPath: #filePath)+ for _ in 0..<5 { url.deleteLastPathComponent() }+ return url.appending(path: "Asterism")+ }++ @Test("Correction is absent from all share choice branches, while both capture paths keep choices")+ func correctionIsAbsentEvenFromExpandedChoices() throws {+ let source = try String(contentsOf: projectDirectory.appending(path:+ "AsterismShareExtension/ChapterCaptureChoicesView.swift"), encoding: .utf8)+ for forbidden in ["Correct detected chapter", "capture.correct-chapter",+ "Chapter options", "capture.chapter-options",+ ".correctedExisting", ".correctedNewChapter", "isCorrecting"] {+ #expect(!source.contains(forbidden), "Share choices must never expose correction: \(forbidden)")+ }+ // Removing correction must not remove the separately required choices.+ for retained in ["expandedAlternatives", "showsChapterChoicesInitially",+ "capture.choose-chapter", "capture.confirm-new-chapter",+ "capture.add-another-chapter", "capture.generic-note", ".existing(", ".newChapter("] {+ #expect(source.contains(retained), "Required chapter alternatives remain: \(retained)")+ }+ for file in ["CaptureView.swift", "ReShareCaptureView.swift"] {+ let branch = try String(contentsOf: projectDirectory.appending(path:+ "AsterismShareExtension/" + file), encoding: .utf8)+ #expect(branch.contains("ChapterCaptureChoicesView(projection:"))+ }+ let editor = try String(contentsOf: projectDirectory.appending(path:+ "Asterism/Views/EntryDetailView.swift"), encoding: .utf8)+ #expect(editor.contains("entry-detail-correct"), "Saved entry correction remains available")+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyOfferTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyOfferTests.swiftnew file mode 100644index 00000000..fdc6b981--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyOfferTests.swift@@ -0,0 +1,354 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Work record copy offers", .serialized)+struct WorkRecordCopyOfferTests {+ @Test func nearestLowerBucketPrecedesAvailabilityFiltering() {+ let series = UUID()+ let destination = UUID()+ let older = UUID()+ let nearest = UUID()+ let members = [+ RecordCopyOfferMember(+ work: .init(+ id: destination, title: "Next", membership: .init(seriesID: series, position: 3)),+ eligibleRecordCount: 0),+ RecordCopyOfferMember(+ work: .init(id: older, title: "Old", membership: .init(seriesID: series, position: -2)),+ eligibleRecordCount: 2),+ RecordCopyOfferMember(+ work: .init(+ id: nearest, title: "Prior", membership: .init(seriesID: series, position: 2.5),+ unavailableReason: "Being resolved"), eligibleRecordCount: 0),+ ]+ #expect(+ RecordCopyOfferPlanning.predecessor(+ destinationID: destination, seriesID: series, members: members) == nil)+ #expect(+ RecordCopyOfferPlanning.predecessor(destinationID: older, seriesID: series, members: members)+ == nil)+ }++ @Test func nearestTiesRequireExplicitChoiceIncludingUnavailablePeer() throws {+ let series = UUID()+ let destination = UUID()+ let one = UUID()+ let unavailable = UUID()+ let samePosition = UUID()+ let members = [+ RecordCopyOfferMember(+ work: .init(id: destination, title: "A", membership: .init(seriesID: series, position: 3)),+ eligibleRecordCount: 0),+ RecordCopyOfferMember(+ work: .init(id: one, title: "Z", membership: .init(seriesID: series, position: 1.5)),+ eligibleRecordCount: 2),+ RecordCopyOfferMember(+ work: .init(+ id: unavailable, title: "B", membership: .init(seriesID: series, position: 1.5),+ unavailableReason: "Being resolved"), eligibleRecordCount: 0),+ RecordCopyOfferMember(+ work: .init(+ id: samePosition, title: "Earlier title", membership: .init(seriesID: series, position: 3)+ ), eligibleRecordCount: 5),+ ]+ for input in [members, Array(members.reversed())] {+ let projection = try #require(+ RecordCopyOfferPlanning.predecessor(+ destinationID: destination, seriesID: series, members: input))+ #expect(projection.position == 1.5 && projection.requiresSourceChoice)+ #expect(Set(projection.bucket.map { $0.work.id }) == [one, unavailable])+ #expect(projection.availableSources.map { $0.work.id } == [one])+ }+ }++ @Test func inconsistentOrderAndEmptyNearestOmitOffer() {+ let series = UUID()+ let destination = UUID()+ let first = RecordCopyOfferMember(+ work: .init(id: UUID(), title: "First", membership: .init(seriesID: series, position: 1)),+ eligibleRecordCount: 3)+ let next = RecordCopyOfferMember(+ work: .init(id: destination, title: "Next", membership: .init(seriesID: series, position: 3)),+ eligibleRecordCount: 0)+ let empty = RecordCopyOfferMember(+ work: .init(id: UUID(), title: "Empty", membership: .init(seriesID: series, position: 2)),+ eligibleRecordCount: 0)+ #expect(+ RecordCopyOfferPlanning.predecessor(+ destinationID: destination, seriesID: series, members: [first, empty, next]) == nil)+ let ambiguous = RecordCopyOfferMember(+ work: .init(id: UUID(), title: "Ambiguous", membership: .init(seriesID: series, position: 2)),+ eligibleRecordCount: 3, membershipIsConsistent: false)+ #expect(+ RecordCopyOfferPlanning.predecessor(+ destinationID: destination, seriesID: series, members: [first, ambiguous, next]) == nil)+ }++ private func draft(_ work: WorkSnapshot, membership: SeriesMembership?) -> WorkMetadataDraft {+ .init(+ displayTitle: work.displayTitle, typeAssignment: work.typeDisplay.assignment,+ genreTags: work.genreTags,+ genericNotes: work.genericNotes, publicationEdit: .unchanged,+ readingStatus: work.readingStatus,+ verdict: work.verdict, releaseDays: work.releaseDays, membership: membership, thumbnail: .keep+ )+ }+ private func fixture(save: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws+ -> (M5Fixture, UUID, UUID)+ {+ let fixture = try await M5Fixture(saveStrategy: save)+ let series = try await fixture.repository.createSeries(name: "Series", notes: "")+ let work = try await fixture.repository.createWork(.init(displayTitle: "Book", hostname: ""))+ return (fixture, series, work.id)+ }++ @Test func workReceiptUsesActualMembershipRatherThanEditorBasis() async throws {+ let (fixture, series, id) = try await fixture()+ let loaded = try await fixture.repository.work(id: id)+ try await fixture.repository.forceMembership(of: id, seriesID: series, position: 1)+ let result = try await fixture.repository.updateWorkWithMembershipReceipt(+ id: id, basis: .init(work: loaded),+ draft: draft(loaded, membership: .init(seriesID: series, position: 2)), calendar: .current)+ #expect(result.outcome == .committed && result.transitions.count == 1)+ #expect(+ result.transitions[0].before?.position == 1 && result.transitions[0].after?.position == 2)+ #expect(!result.transitions[0].isJoin)+ }++ @Test func workJoinLeaveAndSameSeriesReceiptsPreserveOrdinaryWriter() async throws {+ let (fixture, series, id) = try await fixture()+ var work = try await fixture.repository.work(id: id)+ let joined = try await fixture.repository.updateWorkWithMembershipReceipt(+ id: id, basis: .init(work: work),+ draft: draft(work, membership: .init(seriesID: series, position: 1)), calendar: .current)+ #expect(joined.outcome == .committed && joined.transitions[0].isJoin)+ #expect(+ joined.transitions[0].addressedWorkIDs == [id] && joined.transitions[0].resolvedWorkID == id)+ work = try await fixture.repository.work(id: id)+ let same = try await fixture.repository.updateWorkWithMembershipReceipt(+ id: id, basis: .init(work: work), draft: draft(work, membership: work.membership),+ calendar: .current)+ #expect(!same.transitions[0].isJoin)+ #expect(+ try await fixture.repository.updateWork(+ id: id, basis: .init(work: work), draft: draft(work, membership: nil), calendar: .current)+ == .committed)+ #expect(try await fixture.repository.work(id: id).membership == nil)+ }++ @Test func seriesAliasesFoldTransactionInitialAndFinalMembershipOnce() async throws {+ let (fixture, series, id) = try await fixture()+ let work = try await fixture.repository.work(id: id)+ let a = UUID()+ let b = UUID()+ await fixture.repository.recordCollapse(loser: a, survivor: id, type: .work)+ await fixture.repository.recordCollapse(loser: b, survivor: id, type: .work)+ let result = try await fixture.repository.commitSeriesEditsWithMembershipReceipt(+ seriesID: series, name: "Series", notes: "",+ members: [+ .init(+ workID: a, basis: .init(work: work), membership: .init(seriesID: series, position: 1)),+ .init(+ workID: b, basis: .init(work: work), membership: .init(seriesID: series, position: 2)),+ ])+ #expect(result.outcome == .committed && result.transitions.count == 1)+ #expect(Set(result.transitions[0].addressedWorkIDs) == [a, b])+ #expect(result.transitions[0].resolvedWorkID == id && result.transitions[0].before == nil)+ #expect(result.transitions[0].after?.position == 2 && result.transitions[0].isJoin)+ }++ @Test func failedReceiptSaveLeavesNoMembershipOrSeriesChanges() async throws {+ let save = FailingSaveStrategy()+ let (fixture, series, id) = try await fixture(save: save)+ let work = try await fixture.repository.work(id: id)+ save.fail = true+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await fixture.repository.updateWorkWithMembershipReceipt(+ id: id, basis: .init(work: work),+ draft: draft(work, membership: .init(seriesID: series, position: 1)), calendar: .current)+ }+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await fixture.repository.commitSeriesEditsWithMembershipReceipt(+ seriesID: series, name: "Changed", notes: "changed",+ members: [+ .init(+ workID: id, basis: .init(work: work), membership: .init(seriesID: series, position: 1))+ ])+ }+ save.fail = false+ #expect(try await fixture.repository.work(id: id).membership == nil)+ #expect(try await fixture.repository.seriesDetail(id: series)?.display.name == "Series")+ }++ @Test func savedFinalBatchAndOfferReprojectionUseNewMembersAndOrder() async throws {+ let (fixture, series, first) = try await fixture()+ let second = try await fixture.repository.createWork(+ .init(displayTitle: "Second", hostname: ""))+ let third = try await fixture.repository.createWork(.init(displayTitle: "Third", hostname: ""))+ _ = try await fixture.repository.commitRecordEdits(+ workID: first, operations: [.create(.init(kind: .character, name: "Cast"))])+ _ = try await fixture.repository.commitRecordEdits(+ workID: second.id, operations: [.create(.init(kind: .place, name: "Setting"))])+ let works = try await fixture.repository.works().works+ let edits = [first, second.id, third.id].enumerated().map { index, id in+ SeriesMemberEdit(+ workID: id, basis: .init(work: works.first { $0.id == id }!),+ membership: .init(seriesID: series, position: Double(index + 1)))+ }+ let receipt = try await fixture.repository.commitSeriesEditsWithMembershipReceipt(+ seriesID: series, name: "Series", notes: "", members: edits)+ #expect(receipt.transitions.filter(\.isJoin).count == 3)+ let before = try #require(+ try await fixture.repository.recordCopyOffer(destinationWorkID: third.id, seriesID: series))+ #expect(before.sources.map(\.id) == [second.id])+ #expect(+ try await fixture.repository.recordCopyOffer(destinationWorkID: first, seriesID: series)+ == nil)+ try await fixture.repository.forceMembership(of: second.id, seriesID: series, position: 4)+ let after = try #require(+ try await fixture.repository.recordCopyOffer(destinationWorkID: third.id, seriesID: series))+ #expect(after.sources.map(\.id) == [first] && before.basis != after.basis)+ }+ @Test(arguments: ["half", "splitPosition", "splitSeries"])+ func knownPartialOrSplitMembershipSuppressesAutomaticOffer(problem: String) async throws {+ let (fixture, series, destination) = try await fixture()+ let older = try await fixture.repository.createWork(.init(displayTitle: "Older", hostname: ""))+ let nearest = try await fixture.repository.createWork(+ .init(displayTitle: "Nearest", hostname: ""))+ for (id, position) in [(older.id, 1.0), (nearest.id, 2.0), (destination, 3.0)] {+ try await fixture.repository.forceMembership(of: id, seriesID: series, position: position)+ }+ for id in [older.id, nearest.id] {+ _ = try await fixture.repository.commitRecordEdits(+ workID: id, operations: [.create(.init(kind: .character, name: "Cast"))])+ }+ let before = try #require(+ try await fixture.repository.recordCopyOffer(destinationWorkID: destination, seriesID: series)+ )+ #expect(before.sources.map(\.id) == [nearest.id])+ if problem == "half" {+ try await fixture.repository.forceMembership(of: nearest.id, seriesID: series, position: nil)+ } else {+ try await fixture.repository.seedM5Rows(works: [+ .init(id: nearest.id, displayTitle: "Nearest", hostname: "offer.example")+ ])+ try await fixture.repository.forceMembership(+ of: nearest.id, seriesID: problem == "splitSeries" ? UUID() : series,+ position: problem == "splitPosition" ? 2.5 : 2, rowIndex: 1)+ }+ #expect(+ try await fixture.repository.recordCopyOffer(destinationWorkID: destination, seriesID: series)+ == nil,+ "Unknown nearest order must not silently offer the older eligible work")+ }++ @Test func tiedNearestBucketIncludesUnavailableWholeIdentityPeer() async throws {+ let (fixture, series, destination) = try await fixture()+ let older = try await fixture.repository.createWork(.init(displayTitle: "Older", hostname: ""))+ let available = try await fixture.repository.createWork(+ .init(displayTitle: "Available", hostname: ""))+ let unavailable = try await fixture.repository.createWork(+ .init(displayTitle: "Unavailable", hostname: ""))+ for (id, position) in [+ (older.id, 1.0), (available.id, 2.0), (unavailable.id, 2.0), (destination, 3.0),+ ] {+ try await fixture.repository.forceMembership(of: id, seriesID: series, position: position)+ }+ for id in [older.id, available.id, unavailable.id] {+ _ = try await fixture.repository.commitRecordEdits(+ workID: id, operations: [.create(.init(kind: .character, name: "Cast"))])+ }+ let record = try #require(+ try await fixture.repository.recordCopyContext(sourceWorkID: unavailable.id).records.first)+ try await fixture.repository.seedM5Rows(characters: [+ .init(id: record.id, name: record.name, workID: nil)+ ])+ let offer = try #require(+ try await fixture.repository.recordCopyOffer(destinationWorkID: destination, seriesID: series)+ )+ #expect(offer.requiresSourceChoice && offer.precedingPosition == 2)+ #expect(offer.sources.map(\.id) == [available.id])+ #expect(offer.unavailablePredecessors.map(\.id) == [unavailable.id])+ #expect(offer.unavailablePredecessors[0].unavailableReason != nil)+ #expect(!offer.sources.contains { $0.id == older.id })+ }++ @Test(arguments: ["staleRedirect", "torn", "missing"])+ func receiptVariantsPreserveOrdinaryWriterRefusals(problem: String) async throws {+ let (fixture, series, id) = try await fixture()+ let loaded = try await fixture.repository.work(id: id)+ let addressed = problem == "torn" ? id : UUID()+ if problem == "staleRedirect" {+ await fixture.repository.recordCollapse(loser: addressed, survivor: id, type: .work)+ try await fixture.repository.withLockedContext(+ mode: .exclusive, operation: "diverged survivor fixture"+ ) { context in+ for work in try context.fetch(FetchDescriptor<Work>()) where work.id == id {+ work.genericNotes = "Peer edit"+ }+ try context.save()+ }+ } else if problem == "torn" {+ try await fixture.repository.seedM5Rows(works: [+ .init(+ id: id, displayTitle: "Disagreeing", hostname: "offer.example", genericNotes: "Peer edit")+ ])+ }+ let basis =+ problem == "missing"+ ? WorkEditBasis(+ displayTitle: "Absent work", typeAssignment: .none, genreTags: [], genericNotes: "",+ memberships: [], lastParsedTitle: nil, titleProvenance: .manual)+ : WorkEditBasis(work: loaded)+ let metadata = draft(loaded, membership: .init(seriesID: series, position: 1))+ let members = [+ SeriesMemberEdit(+ workID: addressed, basis: basis,+ membership: .init(seriesID: series, position: 1))+ ]+ if problem == "missing" {+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await fixture.repository.updateWorkWithMembershipReceipt(+ id: addressed, basis: basis, draft: metadata, calendar: .current)+ }+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await fixture.repository.updateWork(+ id: addressed, basis: basis, draft: metadata, calendar: .current)+ }+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await fixture.repository.commitSeriesEditsWithMembershipReceipt(+ seriesID: series, name: "Changed", notes: "", members: members)+ }+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await fixture.repository.commitSeriesEdits(+ seriesID: series, name: "Changed", notes: "", members: members)+ }+ } else {+ let receipt = try await fixture.repository.updateWorkWithMembershipReceipt(+ id: addressed, basis: basis, draft: metadata, calendar: .current)+ let ordinary = try await fixture.repository.updateWork(+ id: addressed, basis: basis, draft: metadata, calendar: .current)+ guard case .conflict = ordinary else {+ Issue.record("Expected ordinary work refusal")+ return+ }+ #expect(receipt.outcome == ordinary && receipt.transitions.isEmpty)+ let batchReceipt = try await fixture.repository.commitSeriesEditsWithMembershipReceipt(+ seriesID: series, name: "Changed", notes: "", members: members)+ let batchOrdinary = try await fixture.repository.commitSeriesEdits(+ seriesID: series, name: "Changed", notes: "", members: members)+ guard case .conflict = batchOrdinary else {+ Issue.record("Expected ordinary series refusal")+ return+ }+ #expect(batchReceipt.outcome == batchOrdinary && batchReceipt.transitions.isEmpty)+ }+ #expect(try await fixture.repository.seriesDetail(id: series)?.display.name == "Series")+ #expect(+ try await fixture.repository.membershipColumns(of: id).allSatisfy { $0.seriesID == nil })+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swiftnew file mode 100644index 00000000..02c1648c--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift@@ -0,0 +1,378 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++@Suite("Work record copy repository", .serialized)+struct WorkRecordCopyRepositoryTests {+ private let source = UUID(), destination = UUID(), character = UUID(), place = UUID()++ private func fixture(save: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws+ -> M5Fixture+ {+ let fixture = try await M5Fixture(saveStrategy: save)+ try await fixture.repository.seedM5Rows(+ sites: [.init(hostname: "copy.example")],+ works: [+ .init(id: source, displayTitle: "First", hostname: "copy.example"),+ .init(id: destination, displayTitle: "Second", hostname: "copy.example"),+ ],+ characters: [+ .init(+ id: character, name: "Robert", nameKey: "bob", aliases: ["Bobby"], note: "secret",+ facts: [+ .init(+ statement: "source fact", quote: "source quote", nameKey: "bob", source: .genericNotes+ )+ ], workID: source)+ ],+ suppressions: [+ .init(workID: destination, nameKey: "robert"), .init(workID: destination, nameKey: "bobby"),+ ],+ places: [.init(id: place, name: "Dock", note: "setting", workID: source)])+ try await fixture.repository.seedWorkLinks([.init(a: source, b: destination, type: "arbitrary")]+ )+ return fixture+ }+ private func preview(_ repository: LibraryRepository, includeNotes: Bool = false) async throws+ -> RecordCopyPreview+ {+ try await repository.previewRecordCopy(+ sourceWorkID: source, destinationWorkID: destination,+ selections: [+ .init(kind: .character, sourceID: character), .init(kind: .place, sourceID: place),+ ], includeNotes: includeNotes)+ }++ @Test func mixedCopyIsIndependentAndLeavesMetadataAndEvidenceAlone() async throws {+ let fixture = try await fixture()+ let before = try await fixture.repository.backupV19Snapshot()+ let preview = try await preview(fixture.repository)+ #expect(preview.rows.count == 2)+ #expect(try await fixture.repository.backupV19Snapshot() == before, "Preview is read-only")+ guard+ case .committed(let ids, let skipped) = try await fixture.repository.commitRecordCopy(preview)+ else {+ Issue.record("Expected commit")+ return+ }+ #expect(Set(ids) == Set(preview.rows.map(\.destinationID)) && skipped == 0)+ let after = try await fixture.repository.backupV19Snapshot()+ #expect(after.works == before.works && after.entries == before.entries)+ #expect(+ after.characters.filter { $0.workID == source }+ == before.characters.filter { $0.workID == source })+ #expect(+ after.places.filter { $0.workID == source } == before.places.filter { $0.workID == source })+ let copied = try #require(after.characters.first { $0.workID == destination })+ #expect(copied.name == "Robert" && copied.nameKey == "robert" && copied.aliases == ["Bobby"])+ #expect(copied.note.isEmpty && copied.facts.isEmpty)+ #expect(copied.createdAt == M5Fixture.epoch && copied.modifiedAt == M5Fixture.epoch)+ #expect(+ after.suppressions.first { $0.workID == destination && $0.nameKey == "robert" }?.statusRaw+ == "cleared")+ #expect(+ after.suppressions.first { $0.workID == destination && $0.nameKey == "bobby" }?.statusRaw+ == "active")+ }++ @Test func failedMixedSaveRollsBackRowsAndSuppression() async throws {+ let save = FailingSaveStrategy()+ let fixture = try await fixture(save: save)+ let before = try await fixture.repository.backupV19Snapshot()+ let preview = try await preview(fixture.repository)+ save.fail = true+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await fixture.repository.commitRecordCopy(preview)+ }+ save.fail = false+ await fixture.repository.shutdown()+ let reopened = try await LibraryRepository.openForApp(.init(rootDirectory: fixture.directory))+ .repository+ #expect(try await reopened.backupV19Snapshot() == before)+ #expect(try await reopened.inspectRecordCopyOutcome(preview) == .absent)+ }++ @Test(arguments: ["sourceName", "sourceOwner", "sourceKey", "destinationAlias", "link"])+ func stalePreviewRefusesWithoutWrites(change: String) async throws {+ let fixture = try await fixture()+ let preview = try await preview(fixture.repository)+ try await fixture.repository.withLockedContext(+ mode: .exclusive, operation: "mutating copy fixture"+ ) { context in+ let row = try #require(CharacterRecord.rows(ids: [character], context: context).first)+ switch change {+ case "sourceName": row.name = "Changed"+ case "sourceOwner": row.work = nil+ case "sourceKey": row.nameKey = "changed"+ case "destinationAlias":+ let work = try #require(+ context.fetch(FetchDescriptor<Work>()).first { $0.id == destination })+ context.insert(+ CharacterRecord.make(+ id: UUID(), name: "Else", nameKey: "else", aliases: ["Robert"], note: "", facts: [],+ timestamp: M5Fixture.epoch, work: work))+ default: for link in try context.fetch(FetchDescriptor<WorkLink>()) { context.delete(link) }+ }+ try context.save()+ }+ let before = try await fixture.repository.backupV19Snapshot()+ guard case .refused = try await fixture.repository.commitRecordCopy(preview) else {+ Issue.record("Expected refusal")+ return+ }+ #expect(try await fixture.repository.backupV19Snapshot() == before)+ }++ @Test func sourceFactsAndUnselectedNotesDoNotStalePortablePayload() async throws {+ let fixture = try await fixture()+ let preview = try await preview(fixture.repository)+ try await fixture.repository.withLockedContext(+ mode: .exclusive, operation: "source-only evidence change"+ ) { context in+ let row = try #require(CharacterRecord.rows(ids: [character], context: context).first)+ row.note = "changed note"+ row.facts = []+ try context.save()+ }+ guard case .committed = try await fixture.repository.commitRecordCopy(preview) else {+ Issue.record("Excluded content must not stale preview")+ return+ }+ }++ @Test(arguments: ["orphan", "offOwner", "key", "torn"])+ func wholeIdentitySourceSiblingsAreUnavailable(problem: String) async throws {+ let fixture = try await fixture()+ try await fixture.repository.seedM5Rows(characters: [+ .init(+ id: character, name: problem == "torn" ? "Different" : "Robert",+ nameKey: problem == "key" ? "different" : "bob", aliases: ["Bobby"], note: "secret",+ facts: [+ .init(+ statement: "source fact", quote: "source quote", nameKey: "bob", source: .genericNotes)+ ], workID: problem == "orphan" ? nil : (problem == "offOwner" ? destination : source))+ ])+ let context = try await fixture.repository.recordCopyContext(sourceWorkID: source)+ #expect(+ context.records.first { $0.id == character && $0.kind == .character }?.unavailableReason+ != nil)+ await #expect(throws: LibraryRepositoryError.self) { _ = try await preview(fixture.repository) }+ }++ @Test func kindNamespacesAndPlannedIDsAreVerified() async throws {+ let fixture = try await fixture()+ try await fixture.repository.seedM5Rows(places: [+ .init(id: character, name: "Same UUID place", workID: source)+ ])+ let preview = try await fixture.repository.previewRecordCopy(+ sourceWorkID: source, destinationWorkID: destination,+ selections: [+ .init(kind: .character, sourceID: character), .init(kind: .place, sourceID: character),+ ], includeNotes: false)+ #expect(preview.rows.count == 2 && Set(preview.rows.map(\.destinationID)).count == 2)+ #expect(try await fixture.repository.inspectRecordCopyOutcome(preview) == .absent)+ guard case .committed = try await fixture.repository.commitRecordCopy(preview) else {+ Issue.record("Expected mixed namespaces commit")+ return+ }+ guard case .committed = try await fixture.repository.inspectRecordCopyOutcome(preview) else {+ Issue.record("Exact-ID inspection must find both kinds")+ return+ }+ guard case .refused = try await fixture.repository.commitRecordCopy(preview) else {+ Issue.record("Existing planned IDs must not insert again")+ return+ }+ }++ @Test func uncertainPartialAndConflictingIdentitiesBlockRetry() async throws {+ let fixture = try await fixture()+ let preview = try await preview(fixture.repository)+ let row = preview.rows[0]+ try await fixture.repository.seedM5Rows(characters: [+ .init(+ id: row.destinationID, name: row.payload.name, nameKey: row.payload.nameKey,+ aliases: row.payload.aliases, workID: destination)+ ])+ #expect(try await fixture.repository.inspectRecordCopyOutcome(preview) == .conflicting)+ let before = try await fixture.repository.backupV19Snapshot()+ guard case .refused = try await fixture.repository.commitRecordCopy(preview) else {+ Issue.record("Partial outcome must block acceptance")+ return+ }+ #expect(try await fixture.repository.backupV19Snapshot() == before)+ }++ @Test func ordinaryBackupRoundTripIsIdempotentAndCopiesRemainEditable() async throws {+ let fixture = try await fixture()+ let preview = try await preview(fixture.repository, includeNotes: true)+ _ = try await fixture.repository.commitRecordCopy(preview)+ let payload = try await fixture.repository.backupV19Snapshot()+ let archive = try BackupV19Codec.encode(+ payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let plan = try BackupImporter.plan(from: archive)+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: plan)+ _ = try await restored.repository.confirmImport(plan: plan)+ let after = try await restored.repository.backupV19Snapshot()+ #expect(after.characters.count == 2 && after.places.count == 2)+ #expect(Set(after.characters.map(\.id)) == Set(payload.characters.map(\.id)))+ let copied = try #require(after.characters.first { $0.workID == destination })+ #expect(+ copied.note == "secret" && after.places.first { $0.workID == destination }?.note == "setting")+ let basis = RecordEditBasis(+ kind: .character, recordID: copied.id, name: copied.name, note: copied.note,+ aliases: copied.aliases, facts: copied.facts)+ _ = try await restored.repository.commitRecordEdits(+ workID: destination,+ operations: [+ .update(basis: basis, draft: .init(kind: .character, name: "Corrected", note: "local"))+ ])+ #expect(+ try await restored.repository.backupV19Snapshot().characters.first { $0.id == character }?+ .name == "Robert")+ let corrected = RecordEditBasis(+ kind: .character, recordID: copied.id, name: "Corrected", note: "local", aliases: [],+ facts: [])+ _ = try await restored.repository.commitRecordEdits(+ workID: destination, operations: [.delete(basis: corrected)])+ #expect(try await restored.repository.backupV19Snapshot().characters.count == 1)+ }++ @Test(arguments: ["orphan", "offOwner", "key"])+ func destinationWholeIdentityConsistencyRefuses(problem: String) async throws {+ let fixture = try await fixture()+ let id = UUID()+ try await fixture.repository.seedM5Rows(characters: [+ .init(id: id, name: "Existing", nameKey: "existing", workID: destination),+ .init(+ id: id, name: "Existing", nameKey: problem == "key" ? "other" : "existing",+ workID: problem == "orphan" ? nil : (problem == "offOwner" ? source : destination)),+ ])+ await #expect(throws: LibraryRepositoryError.self) { _ = try await preview(fixture.repository) }+ }++ @Test func reusedSourceIDRefusesButSkippedIDsAreNotInspected() async throws {+ let fixture = try await fixture()+ var preview = try await fixture.repository.previewRecordCopy(+ sourceWorkID: source, destinationWorkID: destination,+ selections: [+ .init(kind: .character, sourceID: character, destinationID: character),+ .init(kind: .place, sourceID: place),+ ], includeNotes: false)+ guard case .refused = try await fixture.repository.commitRecordCopy(preview) else {+ Issue.record("A source UUID is not fresh")+ return+ }+ preview.rows[0].choice = .skip+ #expect(try await fixture.repository.inspectRecordCopyOutcome(preview) == .absent)+ guard+ case .committed(let ids, let skipped) = try await fixture.repository.commitRecordCopy(preview)+ else {+ Issue.record("Skipped IDs are not creations")+ return+ }+ #expect(ids == [preview.rows[1].destinationID] && skipped == 1)+ }++ @Test func outcomeInspectionIgnoresSubsequentDestinationFacts() async throws {+ let fixture = try await fixture()+ let preview = try await preview(fixture.repository)+ _ = try await fixture.repository.commitRecordCopy(preview)+ let id = try #require(preview.rows.first { $0.kind == .character }?.destinationID)+ try await fixture.repository.withLockedContext(+ mode: .exclusive, operation: "destination enrichment"+ ) { context in+ let row = try #require(CharacterRecord.rows(ids: [id], context: context).first)+ row.facts = [+ .init(+ statement: "destination fact", quote: "destination quote", nameKey: row.nameKey,+ source: .genericNotes)+ ]+ try context.save()+ }+ #expect(try await fixture.repository.inspectRecordCopyOutcome(preview) == .committed)+ }++ @Test func destinationExtractionReadMatchesCopiesWithoutHiddenHistoricalKey() async throws {+ let fixture = try await fixture()+ try await fixture.repository.withLockedContext(+ mode: .exclusive, operation: "destination extraction source"+ ) { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == destination })+ work.genericNotes = "Bobby stood at the Dock."+ try context.save()+ }+ let preview = try await preview(fixture.repository)+ _ = try await fixture.repository.commitRecordCopy(preview)+ let candidate = try #require(+ try await fixture.repository.extractionCandidates(limit: 10, workIDs: [destination]).first)+ let copiedID = try #require(preview.rows.first { $0.kind == .character }?.destinationID)+ #expect(candidate.match(nameKey: "robert", kind: .character)?.id == copiedID)+ #expect(candidate.match(nameKey: "bobby", kind: .character)?.id == copiedID)+ #expect(candidate.match(nameKey: "bob", kind: .character) == nil)+ #expect(+ candidate.acceptedFacts(of: .character).isEmpty && candidate.acceptedFacts(of: .place).isEmpty+ )+ #expect(+ candidate.match(nameKey: "dock", kind: .place)?.id+ == preview.rows.first { $0.kind == .place }?.destinationID)+ }++ @Test(arguments: ["missingSource", "missingDestination", "tornSource", "tornDestination"])+ func unavailableWorkRefuses(problem: String) async throws {+ let fixture = try await fixture()+ let id = problem.hasSuffix("Source") ? source : destination+ if problem.hasPrefix("missing") {+ try await fixture.repository.withLockedContext(+ mode: .exclusive, operation: "missing work fixture"+ ) { context in+ for work in try context.fetch(FetchDescriptor<Work>()) where work.id == id {+ context.delete(work)+ }+ try context.save()+ }+ } else {+ try await fixture.repository.seedM5Rows(works: [+ .init(+ id: id, displayTitle: "Different authored title", hostname: "copy.example",+ genericNotes: "Different content")+ ])+ }+ await #expect(throws: LibraryRepositoryError.self) { _ = try await preview(fixture.repository) }+ }++ @Test func repeatAndTornDestinationClashesNeedConcreteAcknowledgement() async throws {+ let fixture = try await fixture()+ _ = try await fixture.repository.commitRecordCopy(preview(fixture.repository))+ var repeated = try await preview(fixture.repository)+ #expect(repeated.rows.allSatisfy { $0.choice == .skip && !$0.informationalClashes.isEmpty })+ repeated.rows[0].choice = .copy+ guard case .refused = try await fixture.repository.commitRecordCopy(repeated) else {+ Issue.record("Clash must be acknowledged")+ return+ }+ repeated.rows[0].acknowledgedClashes = RecordCopyPlanning.actualClashes(+ for: repeated.rows[0], in: repeated.rows, destination: repeated.basis.destination)+ guard+ case .committed(let ids, let skipped) = try await fixture.repository.commitRecordCopy(+ repeated)+ else {+ Issue.record("Explicit independent copy should succeed")+ return+ }+ #expect(ids.count == 1 && skipped == 1)+ let tornID = UUID()+ try await fixture.repository.seedM5Rows(characters: [+ .init(id: tornID, name: "Other", nameKey: "other", workID: destination),+ .init(id: tornID, name: "Another", nameKey: "other", aliases: ["Bobby"], workID: destination),+ ])+ let tornPreview = try await preview(fixture.repository)+ #expect(+ tornPreview.rows.first { $0.kind == .character }?.informationalClashes.contains {+ $0.recordID == tornID && $0.keys.contains("bobby")+ } == true)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyTests.swiftnew file mode 100644index 00000000..15575abb--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyTests.swift@@ -0,0 +1,148 @@+import Foundation+import Testing++@testable import AsterismCore++@Suite("Work record copy plans")+struct WorkRecordCopyTests {+ private func record(+ _ name: String, kind: RecordKind = .character,+ aliases: [String] = [], key: String? = nil+ ) -> RecordCopyRecord {+ RecordCopyRecord(+ id: UUID(), kind: kind, name: name, aliases: aliases,+ note: "Spoiler", retainedKeys: [key ?? RecordNameKey.normalize(name)])+ }++ @Test func directAndSeriesEligibilityIsBounded() {+ let source = UUID()+ let linked = UUID()+ let sibling = UUID()+ let remote = UUID()+ let series = UUID()+ let works = [+ RecordCopyWork(id: source, title: "Same", membership: .init(seriesID: series, position: 1)),+ RecordCopyWork(id: linked, title: "Same"),+ RecordCopyWork(id: sibling, title: "Same", membership: .init(seriesID: series, position: 2)),+ RecordCopyWork(id: remote, title: "Same"),+ ]+ for links in [+ [RecordCopyLink(a: source, b: linked), RecordCopyLink(a: linked, b: remote)],+ [RecordCopyLink(a: linked, b: source), RecordCopyLink(a: remote, b: linked)],+ ] {+ #expect(+ Set(RecordCopyPlanning.eligibleWorks(from: source, works: works, links: links).map(\.id))+ == [linked, sibling])+ }+ }++ @Test func unavailableAndSelfWorksAreExcluded() {+ let a = UUID()+ let b = UUID()+ #expect(+ RecordCopyPlanning.eligibleWorks(+ from: a,+ works: [+ .init(id: a, title: "A"), .init(id: b, title: "B", unavailableReason: "Being resolved"),+ ],+ links: [.init(a: a, b: b)]+ ).isEmpty)+ #expect(+ RecordCopyPlanning.eligibleWorks(from: UUID(), works: [.init(id: b, title: "B")], links: [])+ .isEmpty)+ #expect(+ RecordCopyPlanning.eligibleWorks(+ from: a,+ works: [+ .init(id: a, title: "A", unavailableReason: "Being resolved"), .init(id: b, title: "B"),+ ], links: [.init(a: a, b: b)]+ ).isEmpty)+ }++ @Test func hiddenSourceKeyDoesNotTravelOrCreateClashes() {+ let source = record("New Name", key: "historical")+ let destination = record("Historical")+ #expect(+ RecordCopyPlanning.initialPlan(+ selected: [source], destination: [destination], includeNotes: false)[0].choice == .copy)+ let visibleAlias = record("New Name", aliases: ["Historical"], key: "historical")+ #expect(+ RecordCopyPlanning.initialPlan(+ selected: [visibleAlias], destination: [destination], includeNotes: false)[0].choice+ == .skip)+ }++ @Test func portablePayloadDerivesFreshKeyAndNotesAreOptional() throws {+ let renamed = record("The New Name", aliases: ["Old Name"], key: "historical")+ let plan = RecordCopyPlanning.initialPlan(+ selected: [renamed], destination: [], includeNotes: false)+ let row = try #require(plan.first)+ #expect(row.payload.nameKey == RecordNameKey.normalize("The New Name"))+ #expect(row.payload.aliases == ["Old Name"])+ #expect(row.payload.note.isEmpty)+ #expect(row.destinationID != renamed.id)+ #expect(+ RecordCopyPlanning.initialPlan(selected: [renamed], destination: [], includeNotes: true)[0]+ .payload.note == "Spoiler")+ }++ @Test func sameKindRetainedAliasAndUnicodeClashesDefaultToSkip() {+ let selected = record("The Café", aliases: ["Captain"])+ for existing in [record("Different", key: "café"), record("Different", aliases: ["captain"])] {+ let rows = RecordCopyPlanning.initialPlan(+ selected: [selected], destination: [existing], includeNotes: false)+ #expect(rows[0].choice == .skip)+ #expect(!rows[0].informationalClashes.isEmpty)+ }+ #expect(+ RecordCopyPlanning.initialPlan(+ selected: [selected], destination: [record("The Café", kind: .place)], includeNotes: false)[+ 0+ ].choice == .copy)+ }++ @Test func selectedOverlapIsInformationalUntilBothWillBeCreated() {+ let a = record("The Captain")+ let b = record("Captain")+ var rows = RecordCopyPlanning.initialPlan(+ selected: [a, b], destination: [], includeNotes: false)+ #expect(rows.allSatisfy { $0.choice == .skip && !$0.informationalClashes.isEmpty })+ rows[0].choice = .copy+ #expect(RecordCopyPlanning.unacknowledgedClashes(rows, destination: []).isEmpty)+ rows[1].choice = .copy+ #expect(RecordCopyPlanning.unacknowledgedClashes(rows, destination: []).count == 2)+ for index in rows.indices {+ rows[index].acknowledgedClashes = RecordCopyPlanning.actualClashes(+ for: rows[index], in: rows, destination: [])+ }+ #expect(RecordCopyPlanning.unacknowledgedClashes(rows, destination: []).isEmpty)+ let destination = [record("Captain")]+ #expect(RecordCopyPlanning.unacknowledgedClashes(rows, destination: destination).count == 2)+ }++ @Test func planningOrderDoesNotChangeClashEvidence() {+ let records = [+ record("Captain"), record("Admiral", aliases: ["Captain"]), record("Dock", kind: .place),+ ]+ let forward = RecordCopyPlanning.initialPlan(+ selected: records, destination: [], includeNotes: false)+ let reversed = RecordCopyPlanning.initialPlan(+ selected: Array(records.reversed()), destination: [], includeNotes: false)+ #expect(+ Dictionary(uniqueKeysWithValues: forward.map { ($0.sourceID, $0.informationalClashes) })+ == Dictionary(uniqueKeysWithValues: reversed.map { ($0.sourceID, $0.informationalClashes) })+ )+ }++ @Test func tornAndInconsistentSourceCannotBePlanned() {+ var invalid = record("Captain")+ invalid.unavailableReason = "Inconsistent ownership"+ #expect(+ RecordCopyPlanning.initialPlan(selected: [invalid], destination: [], includeNotes: false)+ .isEmpty)+ #expect(+ RecordCopyPlanning.initialPlan(+ selected: [], destination: [record("Captain")], includeNotes: false+ ).isEmpty)+ }+}
diff --git a/specs/copy-work-records/ticket-draft.json b/specs/copy-work-records/ticket-draft.jsonnew file mode 100644index 00000000..abb1bb0b--- /dev/null+++ b/specs/copy-work-records/ticket-draft.json@@ -0,0 +1,13 @@+{+ "status": "created and verified in Transit",+ "deduplication": "After Transit restart, copy/character/manual-note reads succeeded with no duplicate; T2439 created and read back in Asterism. Historical READ_TIMEOUT attempts retained in decision history.",+ "request": {+ "projectId": "2403D561-9060-48CC-9AFD-90A35E2B46D6",+ "name": "Copy selected characters and places between related works",+ "description": "Copy selected characters, places or both as independent destination records between directly linked/shared-series works. Approved payload: names/explicit aliases, fresh matching key, optional record notes off, no extracted facts. Approved clashes: Skip or explicit Keep separate, no merge/update. After a reader saves a work newly added to a series, offer to open copying from a preceding work chosen by series position, never auto-copy. Requirements updated; design review/approval pending, no implementation.",+ "type": "feature",+ "idempotencyKey": "216adc51-0338-47a1-ad35-03c42e73f939"+ },+ "taskId": "CAC6897B-FAD2-4CA6-BF33-AD0760AD79B9",+ "displayId": 2439+}
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3f4eee26..f7b1605e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Keep references read-only, preserve authored drafts and URL-free rating-only Save, and omit chips for works without a cast. +- **Cover and chapter feedback (T-2433/T-2436):** accept generic image drag+ representations while preserving the current crop for explicitly unsupported+ image types; remove detected-chapter correction from the share sheet entirely,+ including expanded options. Preserve required ambiguous choices, Save behavior+ and correction through post-save Entry Detail editing.++- **Cover image drop (T-2433):** accept local image files on the work editor's+ Cover field through the existing crop, draft and Save flow. Preserve drafts+ on invalid input and discard stale loads after cancellation, navigation, Save+ or a newer image choice.++- **Chapter choices (T-2436):** keep optional chapter alternatives behind+ Choose chapter for ordinary share captures. Retain required ambiguous and+ shared-page choices and multiple-chapters-per-page defaults. Chapter correction+ belongs in post-save Entry Detail editing.+ - **Work editor layout (T-2416):** align “Pages usually contain” with existing editor fields inside the Notes card, keeping the complete menu visible and preserving work-default choices, accessibility and Save/Cancel behavior.@@ -43,6 +59,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- **Copy characters and places (T-2439):** review independent copies into directly+ related works or series peers, with explicit record selection, optional notes+ and Skip/Keep separate choices for name clashes. Extracted evidence stays in+ its original work. Saving a new series membership offers an optional review+ from the nearest earlier saved position; tied predecessors require a choice+ and batch additions share one offer.++- **Copy work records — Core contracts (T-2439):** add bounded direct-link/shared-series destination choices, portable character/place previews and explicit same-kind clash acknowledgements. Copy both kinds atomically as independent destination records, with exact-ID uncertain-outcome inspection and rollback/refault safeguards. Return saved membership-transition receipts and nearest-lower-position offer projections without schema/history changes or automatic copying. App presentation follows in the next phase.+ - **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,@@ -136,6 +161,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- **Character-extraction UI journeys (T-2439):** scroll record pills fully clear of the tab bar before tapping, verify work-detail navigation, and recognize the wide Today pane by its stable identifier. Preserve alias/fact/citation assertions and failure evidence.+ - **iPad editor preservation — Focused verification (T-2404):** retain unfinished work drafts across layout host replacement, with exact-instance Save/Cancel release and bootstrap/epoch guards. On the reconciled main source, all seven
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 4377c079..010fb158 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -2,6 +2,8 @@ | Name | Creation Date | Status | Summary | |------|---------------|--------|---------|+| [Cover Image Drop](#cover-image-drop) | 2026-10-11 | Draft Review | T-2433. Drop local cover images through existing crop/draft/Save; no network or schema change. |+| [Redundant Chapter Confirmation](#redundant-chapter-confirmation) | 2026-10-11 | Draft Review | T-2436. Keep ordinary share capture automatic and reveal optional chapter alternatives on demand. | | [Export Selected Day's Notes](#export-selected-days-notes) | 2026-10-06 | Complete — scoped checks passed; full phone UI exception recorded; manual Mac check unrun | T2404. Export notes and ratings originally captured on the day selected in Today, with frozen displayed context, existing Markdown blocks and native sharing. | | [Wide Layouts Rethink](#wide-layouts-rethink) | 2026-10-01 | Done — full 2,112-test pre-push unit gate, final MCP Mac/iOS builds and targeted iPad UI checks passed | Implements the section 6 handover: Library destinations in the sidebar, full-width adaptive Today, note inspector, responsive work detail, and shared navigation across window widths. | | [Immutable Capture Safety Net](#immutable-capture-safety-net) | 2026-07-17 | Done | Establishes durable local capture, curation, and self-validating backup foundations. |@@ -62,6 +64,7 @@ | [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. | | [Manual Note Character Chips](#manual-note-character-chips) | 2026-10-12 | In Progress — source preparation; checks pending coordinated slot | Read-only ranked cast chips and alias/note cards in Add note, reusing the share component and preserving URL-free/title/rating draft semantics. |+| [Copy Work Records](#copy-work-records) | 2026-10-12 | Draft PR107 — qualified acceptance | T-2439: independent selected character/place copies with clash preview and once-per-save series-add offers. | --- @@ -1005,3 +1008,33 @@ Approved package `198b65ab`; implementation in progress for T-2416. Retains ordi - [ticket-draft.json](manual-note-character-chips/ticket-draft.json) - [implementation.md](manual-note-character-chips/implementation.md) - [verification-plan.json](manual-note-character-chips/verification-plan.json)++++## Cover Image Drop++T-2433 adds a local image-file drop source to the existing work cover crop/draft/Save pipeline.++- [Small specification](cover-image-drop/smolspec.md)+- [Tasks](cover-image-drop/tasks.md)+- [Decisions](cover-image-drop/decision_log.md)+- [Implementation and verification](cover-image-drop/implementation.md)++## Redundant Chapter Confirmation++T-2436 removes the appearance of mandatory chapter confirmation on automatic ordinary capture while retaining required ambiguity and shared-page choices.++- [Bugfix report and evidence](bugfixes/redundant-chapter-confirmation/report.md)+++## Copy Work Records++T-2439. All fourteen Core/App implementation tasks are complete and source-reviewed in draft PR107. The branch is rebased onto main; the historical alias-chip failure was traced to a UI-test tap inside the tab bar and the scoped harness fix passes all four affected consumers on phone/iPad plus all 13 feature phone cases; refreshed Core/native/signed Mac gates pass. Historical full-UI failures, interruptions and skips remain preserved; no unified green full-phone verdict. See implementation.md and the linked bugfix report for current exact-source checks.++- [requirements.md](copy-work-records/requirements.md)+- [design.md](copy-work-records/design.md)+- [tasks.md](copy-work-records/tasks.md)+- [decision_log.md](copy-work-records/decision_log.md)+- [design-review.md](copy-work-records/design-review.md)+- [ticket-draft.json](copy-work-records/ticket-draft.json)+- [implementation.md](copy-work-records/implementation.md)
diff --git a/specs/bugfixes/alias-chip-tap-enters-tab-bar/report.md b/specs/bugfixes/alias-chip-tap-enters-tab-bar/report.mdnew file mode 100644index 00000000..8acae7ca--- /dev/null+++ b/specs/bugfixes/alias-chip-tap-enters-tab-bar/report.md@@ -0,0 +1,78 @@+# Bugfix Report: Alias-chip journey taps the tab bar++**Date:** 2026-10-12 (UTC)+**Status:** Fixed and reviewed; focused regression and required build/native gates pass++## Description of the Issue++PR107's existing character-extraction citation journey repeatedly reports that Ada's kept Nightjar alias chip is missing. The same test failed its original single retry. All historical failures remain preserved.++Reproduce with `make test-only TEST=AsterismUITests/CharacterExtractionUITests/testACitationInTheFactGutterOpensTheCitedNote` on the dedicated phone: keep Ada and Brede, close review, then ask for Ada's card. The original helper considers the partly exposed pill hittable and taps its fixed normalized (0.08, 0.5) point.++## Investigation Summary++Read the fixture/canned extraction, cast/card rendering, identifier table, four callers of `openPill`, and existing tab-bar guards in WorkDetailStatusUITests. The alias identifier is on a text leaf. A focused rebased red run retained the original assertion and added failure-only tree/pixel evidence; it exited 2 with the same failure. All-attachment export recovered 43 attachments; the `--only-failures` filter returned none, so that filter is not evidence that attachments were absent.++- Red source: rebased b9e2ae14 plus diagnostic attachments only; no interaction/production fix.+- Red result: `/tmp/pr107-alias-red.xcresult`, log and receipt (186.9 seconds; no watchdog).+- Screenshot: `/tmp/pr107-alias-red-all-evidence/1AF84EA1-3317-420C-8099-602C3F8B5A89.png`.+- Full hierarchy: `/tmp/pr107-alias-red-all-evidence/F5216C23-D129-4BE9-A3AD-97B068ECEDB3.txt`.+- Synthesized event: `/tmp/pr107-alias-red-all-evidence/47CAF9E6-E654-4B2E-A23D-F31A2404D6FD`.++## Discovered Root Cause++**Defect type:** UI-test tap geometry/occlusion guard.++The synthesized tap is (130.48, 792.0) on a 402 × 874 window. The tab bar begins at y=791. Both the immediately captured screenshot and full AX hierarchy show Today selected and `recent-list`, with no work detail/card. The helper's `isHittable` check says that some portion of the pill can be touched, not that its chosen coordinate is safe. A partly exposed pill therefore passes the guard while the fixed tap lands in the tab-bar region and changes screens. Waiting for an alias on Today then misreports a missing alias; negative alias/fact assertions could also pass on the wrong screen.++Why chain: the alias assertion fails because no card is open; no card is open because the tap changes tabs; the tap changes tabs because it falls in the bar; it falls in the bar because partial hittability ends scrolling; partial hittability was assumed to validate the chosen coordinate. This is a proven harness defect. The focused citation journey passed after changing only test navigation. Production aliases/storage/rendering were unchanged.++## Resolution for the Issue++The scoped helper keeps bounded scrolling in the work-detail column, requires the whole pill within the viewport and above a present tab bar, and asserts the work-detail root remains after the coordinate tap. It reuses the existing tab-clearance convention and preserves every alias/fact/citation assertion. Failure-only hierarchy and screenshot attachments retain the actual screen if this recurs.++A separate iPad readiness failure occurred before extraction: Today exposes the stable `recent-list` identifier as a ScrollView, while the fixture required a CollectionView. `openWorkDetail` now queries that same identifier through `anyElement`, preserving its assertion and timeout. The original iPad failure is retained. One mistakenly launched run was canceled before any completed case after a failed edit; it is zero execution, not four failures or passes. No application source changed.++## Regression Test++The already failing citation journey is the red regression. Four `openPill` consumers cover kept character/negative alias filtering, kept place, citation navigation and combine/quote behavior. Run those on phone and iPad; preserve all original assertions. Copying/offer behavior will retain affected focused coverage after rebase. No repeated full UI run is used to erase previous outcomes.++## Verification++- [x] Original focused assertion reproduces on rebased source with exact screen/tap evidence.+- [x] Corrected helper and all four callers pass on final phone/iPad source.+- [x] Four reviewers report no source blocker; full Core, official fast and signed Mac/full native pass.++## Related++PR107: https://github.com/ArjenSchwarz/asterism/pull/107 . Original branch history is preserved at `refs/backup/t2439-before-alias-fix-20261012`. Rebase onto main bdbae0d5 retained both spec-overview sections; only documentation conflicts occurred. No phone install, merge or unrelated process changes.++## Final exact-source evidence++Only `CharacterExtractionUITests.swift` changed in executable source for this follow-up. Application sources and all original assertions are preserved. Rebased main is bdbae0d5; documentation-only commits after verification do not change tested Swift files.++| Check | Actual outcome | Retained evidence stem under /tmp |+| --- | --- | --- |+| Original focused red | Failed alias assertion; tab-bar tap proved | pr107-alias-red |+| Initial phone helper consumers | 4/4 passed before portable readiness correction | pr107-alias-green-phone |+| Original iPad readiness attempt | Failed before extraction: CollectionView query on ScrollView | pr107-alias-green-ipad |+| Mistaken pre-correction launch | Canceled, zero completed cases | pr107-alias-green-ipad2 |+| Final iPad helper consumers | 4/4 passed, exit0, no skips or timeout | pr107-alias-green-ipad3 |+| Final phone helper consumers + copying/offers | 17/17 passed (4 extraction + 13 feature), exit0, no skips or timeout | pr107-final-focused-phone |+| Unfiltered serial Core | 3,870 summary declarations, four products; 55 opt-in skip records retained; no compiler warnings | pr107-alias-final-core |+| Official fast manifest | 456 declarations passed, exit0 | pr107-alias-final-fast |+| Signed Mac + full native | 1,738 declarations / 1,794 invocations passed; zero failed/skipped/structured runtime warnings | pr107-alias-final-native |++Temporary-store repair diagnostics and extension metadata-extraction warnings remain in raw build/native logs. No new compiler warning. No formatter/linter is configured; `git diff --check` passes.++## Explanation and completeness++Beginner: the alias was present, but the test tapped the navigation bar. It now scrolls the record into view and verifies the book screen.++Intermediate: the local XCTest helper requires viewport containment and tab clearance before a leading-edge coordinate tap; stable-ID readiness works across phone List and wide ScrollView. Every alias/fact/citation assertion remains unchanged.++Expert: partial AX hittability cannot prove a selected normalized coordinate is unobscured. Bounded detail-column scrolling and a post-navigation witness protect positive and negative checks without changing product geometry or persistence.++The proven harness defect is fixed. Original full-UI failures, accessibility retry, two opt-in phone skips, interrupted gate and unfinalized watchdog bundle remain preserved in implementation.md and the original review. These focused results do not establish a single green full-phone gate. The user requested bounded focused investigation instead of broad UI repeats. Draft PR107 remains unmerged; no physical install, live-data reset or shared-service change.++Structured UI warning records retained: final phone 32, final iPad 8 (Calendar/CivilDay environment outside a View). These passing selections are not warning-free. Mac app deep/strict and embedded-extension strict signature verification also passed without launching either product.
diff --git a/specs/bugfixes/redundant-chapter-confirmation/report.md b/specs/bugfixes/redundant-chapter-confirmation/report.mdnew file mode 100644index 00000000..a96116c1--- /dev/null+++ b/specs/bugfixes/redundant-chapter-confirmation/report.md@@ -0,0 +1,45 @@+# Redundant chapter confirmation — T-2436++## Scope and authority+The owner activated the deferred Asterism bug on 11 October 2026. Use established ordinary one-page-per-chapter behavior without a redundant confirmation step; retain correction and necessary ambiguous/mixed/shared-page choices. Exact Transit ticket `E8455023-ED04-489D-805B-3DE7A7160A57` is verified and moved to in-progress with an activation comment. Branch `T-2433/cover-drop-and-chapter-confirmation` starts from merged main `8aef9858` and also carries separately tracked T-2433.++## Source diagnosis+`ChapterCaptureResolver` already returns automatic new/update resolutions for clear comparable chapter evidence and ordinary URL captures. Required selection for incomparable, conflicting or multiple-source targets protects existing identity and content and stays unchanged.++`Asterism/AsterismShareExtension/ChapterCaptureChoicesView.swift` eagerly expands all chapter alternatives whenever `projection.offersAnotherChapter` is true, including optional ordinary captures that already allow Save. Existing-entry buttons, chapter fields and an Add/Confirm action make an optional alternative appear like a required confirmation above the note/rating. Both new and saved-page share branches use the same view. A tentative dual v2/v3 evidence theory was rejected after tracing current derivation; no speculative resolver fix is made.++## Original resolution (superseded by Q5)+Ordinary automatic capture keeps optional chapter alternatives collapsed behind a single Choose chapter action. Required resolver choices and the multiple-chapters-per-page flow remain immediately visible. Clear detected-chapter correction stays available; an unidentified page still permits Add another chapter after opening alternatives. Selecting another chapter or generic note retains current intent, content-review and learning semantics. Resolver, Save gating, source identity and work defaults do not change.++This is a reversible presentation correction with no new learned layout policy, site-wide restriction, confidence API, schema or migration. An actual disabled-Save report on an incomparable page would require that page's evidence before changing matching safety.++## Verification plan and status+Write focused presentation-policy regressions for automatic ordinary captures versus required ambiguous/multiple-page/correction cases and existing new/saved capture adapter Save parity. Preserve source-required extension wiring and correction assertions. The exclusive serial lane is granted. Focused Core discovery executed 101 tests in five suites, including both new presentation regressions, and passed. Focused native discovery executed 64 tests in three suites and passed. Required unfiltered package/fast/native gates and signed Mac app/embedded-extension compilation passed; the two focused crop UI journeys passed. No baseline behavioral red is claimed: the new presentation predicate did not exist before the patch. The existing incoming-extension rendering harness limit remains explicit; model/source tests are not rendered share-sheet acceptance.++## Decision history+| ID | Date | Decision | Evidence |+|---|---|---|---|+| Q1 | 2026-10-11 | Correct eager optional presentation, preserve resolver safety | Source already permits ordinary Save; ticket explicitly preserves ambiguous/mixed/shared-page choices |+| Q2 | 2026-10-11 | Keep optional chapter and correction routes reachable | T-2416 requirements 3.2/3.5 and owner correction-afterwards intent |+| Q3 | 2026-10-11 | No confirmation-policy learning/schema | No existing stored “known one-page” state is needed for this presentation correction |+++Source checkpoint: the three-file patch and two regression declarations are written; independent source review is clean. Focused and required broad checks plus extension compilation passed. See [implementation checkpoint](../../cover-image-drop/implementation.md) for exact affected cohorts and retained rendering limits. This supports draft review; actual incoming-extension rendering remains incomplete. The subsequent full phone gate ran once and failed an unrelated Settings role-reordering method; all ChapterNotes methods passed. The full iPad gate failed an unchanged Monday-boundary day-selection fixture. One exact phone role retry passed; one exact iPad inspector retry failed again and is flagged. Both full-gate failures remain authoritative; exact discovery, warnings, durations and exported artifacts are in the linked evidence. There is no green full UI verdict.++Source commit: `af2d84df`. Detailed gate receipts and warning/acceptance limits are in the linked implementation evidence.++## Q4 — Owner feedback: correction still appeared upfront++2026-10-12. The standalone installed PR105 head c7b380aa still renders Correct detected chapter for every nonempty evidence set. Collapsing alternatives did not satisfy the no-upfront-correction request. Both new and saved share branches use this common view. Automatic detected create/update now moves that action into a neutral Chapter options menu. Required conflicting/incomparable review and explicitly expanded choices retain visible correction. Existing corrected intents and ordinary Save remain unchanged; saved Entry Detail also retains Correct entry. No known-one-page persisted policy or confidence score is introduced. Two value-policy regressions cover automatic new/update in both capture defaults and required ambiguity. Actual incoming extension rendering remains unverified. The installed Development extension is named Asterism Dev, bundle me.nore.ig.Asterism.dev.ShareExtension; both Release and Development exist and no wrong-extension selection is inferred.+++## Q5 — Definitive owner requirement: no correction in the share sheet++2026-10-12. The owner tested `beb8e6d6` and explicitly rejected correction behind Chapter options. Q4's menu approach is superseded. Remove Correct detected chapter completely from both share branches, including all expanded alternatives, together with its now-pointless wrapper and correction-only state. Keep separately required ambiguous/existing/new-chapter and generic-note choices and their content-review behavior. Correction belongs to post-save Entry Detail editing. No new phone installation is requested.++The focused source-reach regression is written before the change and covers every view branch rather than an initially-hidden flag. Actual incoming-extension rendering is still a separate unverified journey. Existing historical native/UI failures are preserved; no unchanged broad rerun is used to erase them.+++Focused Q5 regression: red run executed one source-reach test and failed seven expected forbidden-action/state/intent assertions (make exit 2). After complete removal, the source reach, ChapterCaptureResolverTests and ChapterCaptureTransactionTests executed 27 tests in three suites and passed (make exit 0). Logs: `/tmp/pr105-chapter-removal-{red,green}.log`; private scratch path `/tmp/pr105-chapter-removal-core-cache`. The fresh package compile preserves its existing unrelated compiler warnings. No rendered incoming share or expanded-options UI acceptance is claimed from this source guard.++Q5 compile and review: `make build-mac` compiled the changed ChapterCaptureChoicesView in AsterismShareExtensionMac, built the Development app and verified its embedded extension (exit 0). Independent deep/strict app and strict extension signature checks passed with normal host trust access; no app was installed or launched. Four read-only pre-push reviewers found no blocking code issues; stale pre-save guidance was corrected. User requested narrow tests; unchanged broad native/UI gates were not repeated and their historical failed verdicts remain. Local review: `/Users/arjen/Documents/Codex/2026-10-12/task-3/pr105-chapter-review/review.html`. Actual incoming-extension rendering remains unverified.
diff --git a/specs/copy-work-records/decision_log.md b/specs/copy-work-records/decision_log.mdnew file mode 100644index 00000000..6f51d71f--- /dev/null+++ b/specs/copy-work-records/decision_log.md@@ -0,0 +1,244 @@+# Decision Log: Copy work records++## Quick Decisions++| ID | Date | Decision | Rationale |+| --- | --- | --- | --- |+| Q1 | 2026-10-12 | Full creating-spec workflow; scope assessment approved | User explicitly requested a proper spec. Content provenance and clash behavior also carry user-owned ambiguity. |+| Q2 | 2026-10-12 | Copy feature is separate from manual note chips and draft PR105 | User described two features; copying is specification-only and chips remain narrow. |+| Q3 | 2026-10-12 | Requirements and reviewed design78795d41 are approved; user authorized task planning and implementation | Earlier pending-approval checkpoints below are historical; direct approval is recorded at the end of this log. |+| Q4 | 2026-10-12 | Transit ticket T-2439 is created and verified in-progress | Earlier lookups timed out; subsequent bounded read and protected status update succeeded before implementation. |+| Q5 | 2026-10-12 | Shared SwiftData/source-owner knowledge applied | After rollback re-fault; SourceRef is scoped to the owning work. Repository instructions independently require these constraints. |+| Q6 | 2026-10-12 | Correction navigation uses the originating stack and retains a suspended review in app-local navigation state | The source-Work duplicate callback is narrower than Check Library, and wide layout replaces the originating view during a push. No persisted history or new library writer is introduced. |++## Decision 1: Independent destination-owned records++**Date**: 2026-10-12+**Status**: accepted++### Context++The same named cast or place can occur in related works, but characters/places today belong to one work and are editable authored records. The user agreed to independent copies with a name-clash preview.++### Decision++Copy selected characters, places or both as new destination-owned UUID identities, leaving the source unchanged. Show clashes before accepting anything.++### Rationale++Independent records fit work-scoped editing and extraction and do not introduce a global character/place identity or coupling between books.++### Alternatives Considered++- **Shared global record**: edits would propagate between books and require model/ownership changes; outside approved independent-copy direction.+- **Move record**: removes it from the source; fails the reuse request.++### Consequences++**Positive:** source and sequel can evolve separately using ordinary record operations.++**Negative:** later source edits need manual copying/editing; names alone cannot prove cross-book identity.++---++## Decision 2: Limit payload to portable authored metadata++**Date**: 2026-10-12+**Status**: accepted++### Context++`RecordAuthoredContent` contains name, aliases, note and facts. A fact's `SourceRef` has only `.entry(UUID)` or `.genericNotes`, interpreted within the owning work. Copying `.genericNotes` would falsely cite the destination's notes; source entries would be absent from destination presentation. There is no source-work identifier in the source-ref wire shape.++### Decision++Copy displayed name and aliases; derive a new matching key from the copied displayed name, as manual creation does. Offer record notes with a session option off initially. Exclude facts/quotes/citations, suppression and coverage. Add no schema/provenance/history table.++### Rationale++Names and aliases provide immediate reuse and extraction matching without manufacturing evidence. Optional notes let the reader carry descriptions knowingly, with a preview limiting accidental spoilers. Explicit aliases carry portable matching names; a source retained key is hidden history and need not become a fresh record’s matching policy.++### Alternatives Considered++- **Everything verbatim**: SourceRef silently changes meaning or dangles; source-specific suppression/coverage could hide destination evidence.+- **Cross-work fact provenance**: defensible but needs new SourceRef/model/archive semantics, source navigation and migration; disproportionate to this request unless the user asks for facts.+- **Preserve hidden retained key**: keeps source rename history but adds destination routing absent from the visible name/aliases; not the default for an independent newly created record.+- **Names only**: discards reader-authored aliases and breaks expected matching continuity.++### Consequences++**Positive:** existing schema/backup shape; explicit content preview; destination evidence stays work-local.++**Negative:** facts are not portable in this feature; a copied note may contain spoilers if deliberately included. Destination retained keys still contribute clash evidence, while source historical keys are excluded.++---++## Decision 3: Skip or explicitly keep clashing records++**Date**: 2026-10-12+**Status**: accepted++### Context++Record duplicate machinery groups only by UUID; distinct-UUID name duplicates are deliberately reader-owned. Same normalized name/alias/key is a possible match, not identity proof. Both source batch overlaps and destination overlaps can make reader intent ambiguous while the matcher still routes deterministically by tier and UUID.++### Decision++Detect within-kind overlaps across planned names/aliases and destination names/retained keys/aliases, including batch-internal overlaps and destination torn variants. Default every potentially clashing selection to Skip; show stable selected-batch overlap information, but require explicit Keep separate only for clashes among planned creations or with existing destination records. No merge/update/replace in this flow.++### Rationale++The user approved a name-clash preview, not automatic content reconciliation. Existing destination editor combine remains the correction path. Skip makes repeated copying safe locally without new persisted provenance.++### Alternatives Considered++- **Merge matching names automatically**: destroys distinctions and cannot establish identity.+- **Merge/update option in preview**: requires field/fact reconciliation and more stale bases; separate from creating independent copies.+- **Block all overlaps**: prevents legitimate separate same-name records permitted by the existing model.++### Consequences++**Positive:** no existing record is overwritten; reader makes the identity decision.++**Negative:** explicit Keep separate can make destination extraction routing ambiguous to the reader (routing remains deterministic by tier/UUID); offline simultaneous copies are not exactly once and require existing reader correction.++---++## Decision 4: Direct links and complete shared series membership++**Date**: 2026-10-12+**Status**: accepted++### Context++`WorkLink` is undirected with reader-authored free-text type. Series names are not unique; a complete `SeriesMembership` carries UUID and position, and half-arrived fields are no membership. A relation graph may contain unrelated remote neighbors.++### Decision++Offer distinct available works directly linked by any type, or carrying the same complete series UUID. Exclude self and transitive-only neighbors; revalidate eligibility at acceptance. Saved relationships are required; copying neither creates nor changes them.++### Rationale++This matches current relations without guessing link-type meaning or inferring identity from series titles. Direct scope gives a bounded picker appropriate to the personal app.++### Alternatives Considered++- **Any work**: broader than the related/series request and removes the meaningful eligibility boundary.+- **Transitive closure**: can reach every work through a loose relation graph.+- **Whitelist relation types**: no managed vocabulary exists; localized/free-text types cannot safely determine eligibility.++### Consequences++**Positive:** uses existing data and preserves relation semantics.++**Negative:** reader must save a missing direct link/membership first; absent or half-arrived relationship evidence can temporarily hide a target.++---++## Historical requirements review and approval history++2026-10-12: Repository research and requirements self-check complete. First design critic and subsequent peer validation completed. Critic found uncertain-commit identification, whole-group owner/key reads, extraction consequences of Keep separate, stable Skip semantics and payload-basis oversensitivity. Draft contracts now use preallocated session UUIDs, whole-ID rereads, explicit rollback, deterministic-routing warning and payload-only freshness. Root recommended fresh derived copy keys over hidden retained-key transfer; this is proposed, not user-approved. No requirements/design/task approval recorded; no implementation started. Design research uses the proposed defaults solely to make their costs concrete.++Explanation self-validation: beginner — choose another book, choose names/places, review and make independent copies; the other book's chapter evidence does not travel. Intermediate — generic value plans plus one mixed-kind locked transaction, destination-owned UUIDs and stale basis refusal. Expert — source owner boundaries and retained keys remain explicit, no new wire format, no name-based convergence, no cross-device exactly-once guarantee. This pass surfaced the need to cover batch-internal clashes, retained-key conflicts and unknown commit outcomes; those are now explicit contracts.++Peer validation used two independent subagents (storage/identity and product/scope) after the first critic. PERSONAL_PROJECTS=1 selected external-model mode, but Codex/Kiro agent tools were not exposed; the agent definition permits subagent fallback. Both validated fresh keys, work-local evidence exclusion, whole-group checks and bounded eligibility. Product peer flagged uncertain-response requirements language, now explicit. Storage peer required whole-ID destination reads and locked kind/ID outcome checks, now explicit; an absent result cannot prove there was no intervening deletion, so no automatic retry is offered. Divergence: critic/storage accepted conservative acknowledgement even for Skip rows; product peer showed that it can describe a duplicate that will not exist. Adopt product peer’s planned-result acknowledgement while keeping informational selected-batch overlaps stable. Newly planned overlaps invalidate affected acknowledgements. This remains within proposed clash policy for user approval.++## Design-phase decisions and approval history++2026-10-12: User approved all three requirements defaults: payload, clash actions and destination eligibility. Decisions 2–4 are accepted. User requested an automatic offer after saving a work into a series, asking about copying from the preceding work; no automatic copying. Requirements 1–4 are approved and Requirement 5 records this addition. Design remains unapproved; no tasks or feature code.++### Decision 5: Save-event-scoped series copy offer++**Date**: 2026-10-12+**Status**: accepted++#### Context++Series membership changes through work metadata Save or series batch Save. Import, merge and reconciliation also write membership. There is no persisted copy-offer history, and observing membership on reload would repeatedly nag or prompt on restored data.++#### Decision++Offer only after a confirmed local reader join save finishes. Consume the event on decline/copy dismissal; retain no persistent offer history. Use saved series position for a unique predecessor; tied order requires an earlier-source picker. First/no-record cases omit the offer. Present one combined offer for batch additions.++#### Rationale++The prompting intent is attached to the reader action, not the existence of membership. Local events naturally prevent repeat prompts on reopen without schema/UserDefaults changes. Display title/UUID ties are deterministic presentation, not evidence of story order.++#### Alternatives Considered++- **Persist per-work/series dismissal state**: unnecessary for event-only prompting and adds lifecycle/backup/sync policy.+- **Observe membership on every reload**: nags, mistakes sync/import for reader intent and cannot distinguish no-op edits.+- **Always choose display-ordered previous row**: chooses tied story order arbitrarily.+- **Prompt for every batch destination**: produces a modal sequence; one combined choice is proportionate.++#### Consequences++**Positive:** no schema migration; prompt appears only in direct authoring paths, after Save; ties remain reader-owned.++**Negative:** no offer is replayed after process death/navigation; a deliberate leave/rejoin may offer again; closing a combined offer dismisses it for all added destinations, which stay manually reachable.++Explanation self-validation (design phase): beginner — adding the next book asks whether to bring familiar names over; saying no leaves the saved book in its series and copies nothing. Intermediate — two editor success hooks feed one app-local event coordinator, and a pure position projection chooses or asks for the source before the existing copy preview. Expert — metadata may commit before later work-editor steps refuse, so offer intent must survive retry locally without treating snapshot refresh as an event; ties and final batch state cannot use UI title/UUID tie-breaks. No persistent receipt/history is required for prompting. This surfaced partial-editor-save and multi-addition sequencing, now explicit in the design.++Design critic review completed after Req5 addition. Adopted actual resolved under-lock membership transition receipts for both interactive writer paths; old draft plus generic committed is insufficient join evidence. Pending partial-editor events now replace/clear on subsequent confirmed transitions and emit only final target. Automatic source choice is bounded to nearest strictly-lower saved position bucket before availability filtering; unavailable/empty nearest candidates never silently select an older book. Tied nearest bucket requires explicit choice; destination-position ties do not invent same-position precedence. Both editors exit inline edit mode rather than dismiss their detail screens. Peer validation follows this critic.++Post-critic explanation validation: beginner — the next saved book can ask about the immediately lower-position book; tied choices require choosing and declining never undoes joining. Intermediate — confirmed resolved transition receipts from two writer paths feed an app-local once-per-save event, then a nearest-position query feeds the normal preview. Expert — receipt creation occurs under the existing lock and only after successful save; pending joins are replaced/cleared across partial work-editor retries, availability filtering cannot redefine predecessor order, and late navigation invalidates presentation. These constraints cover the receipt and bounded-bucket revisions without adding persisted history.++Design peer validation: both storage/identity and product/scope peers support actual locked transition receipts, retained partial-editor events, nearest-position-before-availability and event-only prompting. Product recommendations incorporated: explain unavailable tied peers for one-option choice, label batch review as one addition, use Review before final Copy. Storage corrections incorporated: receipt addressed→resolved ID mapping, transaction-initial/final membership fold for redirect aliases, and reproject order/source set when accepting an offer; after explicit source confirmation the ordinary copy session uses its existing eligibility and commit gates. No additional persisted models are required. Batch dismiss-all vs return-to-list remains a genuine UI choice; recommendation is dismiss-all with manual reachability, awaiting design approval.++2026-10-12: User approved reviewed design checkpoint 78795d41 with “Approved. Create tasks and implement”. This includes bounded nearest-lower tie choice, once-per-save offers with deliberate rejoin eligible again, and dismissing the combined batch offer after reviewing one addition. Decision 5 accepted. Task planning and implementation are explicitly authorized, so no repeat task-approval pause applies. Dedicated branch T-2439/copy-work-records at /Users/arjen/Documents/Codex/2026-10-10/task/asterism-t2439 starts from remote main8aef9858 and carries only the approved spec commits. PR105/106 remain untouched. Recall applied: SwiftData rollback requires refault/reopen evidence, tests retain ModelContainer; accessibility queries require actual hierarchy and stable leaf identifiers.+++## Decision 6: Preserve copy review across an intentional correction visit++**Date**: 2026-10-12+**Status**: accepted implementation direction; runtime verification pending++### Context++The approved design requires existing correction navigation with the copy draft preserved. `AppScreens.workDetail` supplies `onResolveDuplicate` only for a source-Work duplicate set; it is not a generic Check Library route for an ordinary work containing torn records or a problematic destination. The legacy diagnostics boolean belongs to Today. `WideRootView.stackDetail` renders the last typed route, replacing the Work view during a diagnostics push, so view-owned suspended state alone would disappear on iPad/Mac.++### Decision++Use a typed diagnostics route on the originating stack and a separate generic Check Library callback. Dismiss the copy sheet before navigation. Retain only the suspended value session in app-local navigation state keyed to its stack/source host; explicitly Resume refreshes choices and preview. Keep the original uncertainty inspection gate and planned UUIDs across suspension. Retire obsolete sessions on normal host departure, discard or replacement and reject late resume publication.++### Rationale++This supplies the correction and cancellation contracts already approved for every layout without creating persisted offer/copy history, changing the library schema or adding a store writer. A generic Check Library action also permits a real ordinary-source rendered round trip without manufacturing a fault-only test seam.++### Alternatives Considered++- **Reuse source-Work duplicate callback**: absent for ordinary sources and routes the wrong problem when present.+- **Reuse Today diagnostics boolean**: cannot navigate on a current Works host.+- **Retain only Work view state**: the wide detail replaces that view during correction.+- **Persist the draft/history**: unnecessary for a single in-app correction visit and broadens restore/sync policy.++### Consequences++**Positive:** one explicit sheet/route at a time, accessible correction from ordinary sources, phone/iPad/Mac draft parity, original exact-ID uncertain-outcome recovery remains mandatory.++**Negative:** app-local lifetime needs navigation retirement tests; a destroyed host or app restart does not resurrect the review. This records an implementation discovery within the approved product contracts, not a new product decision or an implementation-complete claim.++## Decision 7: Advance confirmed partial-save membership and validate delayed offers++**Date**: 2026-10-12+**Status**: accepted implementation correction within approved design++### Context++A work metadata join/leave can commit before a later record step refuses. The loaded work snapshot may still describe the editor entry state. A competing picker can also delay presentation after an offer projection was read.++### Decision++Advance only the confirmed membership in the editor conflict basis from its typed receipt, preserving other fields and reader drafts. Compare membership by basis presence so a confirmed nil is not replaced by stale loaded membership. Before either host presents a delayed offer, re-read its saved projection and guard the coordinator generation and host obstructions.++### Rationale++This preserves deliberate leave/rejoin and partial-save retry semantics already approved, and silently drops a destination that left the series while presentation was delayed. Receipt reads remain explicit save evidence; reload never creates a join event.++### Alternatives considered++Reloading all drafts after a partial save would discard the refused record/link edits. Deriving membership from the original snapshot loses confirmed changes. Presenting cached offers violates the saved-membership gate.++### Consequences++Additional read-only projection before presentation; new native leave/refusal/rejoin and delayed-presentation regressions. Destination accessibility now states selected/not selected explicitly alongside existing context. Runtime verification is recorded separately.
diff --git a/specs/copy-work-records/design-review.md b/specs/copy-work-records/design-review.mdnew file mode 100644index 00000000..35a0959c--- /dev/null+++ b/specs/copy-work-records/design-review.md@@ -0,0 +1,149 @@+# Asterism — copy work records: design review++Prepared 12 October 2026. **Design approval checkpoint.** The three payload, clash and destination defaults are approved. This checkpoint includes the requested series-add offer. No copying code, implementation tasks, builds or tests have started.++After a work successfully joins a series through a saved work/series edit, offer **“Review characters and places from [preceding work]”**. Accepting fills in the normal copy interface’s source and destination; records remain unselected. Declining or cancelling copies nothing and keeps the saved membership.++## Recommended design choices++1. **Preceding work:** use the nearest strictly lower saved series position, never creation date/title/UUID ordering. If multiple books tie at that position, ask for an explicit source choice within that group, explaining unavailable peers. Never silently skip an empty/torn/unavailable predecessor for an older book. First work or no usable records means no offer; manual copying remains available.+2. **No repeated prompts:** consume the initiating save event after decline or copy-sheet dismissal. Reopening, unrelated edits, position-only edits, import and sync do not prompt. A deliberate saved leave/rejoin or move to another series can offer again. This needs no persisted dismissal history or schema change.+3. **Several works added together:** show one combined offer and let the reader review one destination. After that copy sheet closes, dismiss the whole offer; the other works remain reachable through manual copying. This avoids a sequence of prompts. Returning to the combined list is the alternative if you want to review several additions in one session.++**Does the design look good?** Approval covers the design and these offer defaults; task planning follows only after that approval.++## Review findings incorporated++Explanation validation, a design critic and two independent peers reviewed the addition. External Codex/Kiro tools were unavailable; the permitted subagent fallback supplied storage/identity and product/scope perspectives.++- Locked transaction receipts establish actual resolved membership transitions; an old editor snapshot and a generic success result cannot prove a join.+- Work-editor metadata can save before a later record/link step refuses. Pending offer events survive a successful retry, are replaced by another series join, and clear on leaving; cancellation/navigation discards the offer without undoing saved membership.+- Redirected work identities are resolved before deduplicating batch offers.+- The nearest preceding position is determined before availability filtering. Offer acceptance refreshes ordering/source choices and never silently changes the source.+- The normal copy flow retains its preview, clash acknowledgement, stale-state checks and one mixed character/place save boundary. Existing payload/backup/rollback requirements remain intact.++The full design and added requirement follow so this checkpoint can be reviewed by itself on the phone. Transit’s bounded duplicate-search retry again returned READ_TIMEOUT; ticket creation remains unconfirmed and the local draft is retained.++---++# Copy work records — design++Status: Design draft awaiting user approval. Requirements 1–4 and payload/clash/eligibility defaults are approved; Requirement 5 is the user-requested automatic offer after a saved series addition. No implementation or task planning is authorized by this document.++## Architecture and repository grounding++Add an app-only copy session from a saved work detail's actions while outside edit mode. The session chooses one destination, selects records and previews results; its toolbar Copy is its one save boundary. `WorkDetailView`/`WorkDetailModel` launch the session but do not reuse their staged record edits to write another work. This keeps cancellation and work-editor drafts independent (Req 1, 4).++Use `RecordRow` generics for character/place reads and creation. The persisted tables remain unchanged: characters attach through `Character.work`, places through `Place.workID`; both conformances supply `rows(of:)`, `make` and `attach`. `RecordGroups.swift` groups only by kind/application UUID, never name; two separate copies must therefore mint distinct UUIDs. Do not call existing combine or conversion operations: `LibraryRepository+RecordEditing.swift`'s combine moves content and suppression state within one work, and conversion changes kind, while this operation leaves the source untouched.++No schema, readiness-marker or archive-generation bump is needed for the recommended payload. There is no persisted provenance link or copy-history table. Names, aliases, notes, timestamps and ownership fit existing `Character`/`Place` and existing UUID-keyed archive records. CloudKit uses the existing non-unique/defaulted model columns and tolerates children arriving ahead of their owner.++### Pattern-extension audit++| Existing integration | Needs copy equivalent | Contract |+| --- | --- | --- |+| `RecordRow`, `RecordGroup`, `RecordAuthoredContent` | Yes | Read whole logical groups; unavailable torn selections never copy a representative variant silently. |+| `WorkRecordPresentation`, `RecordRanking` | Yes | Reuse display order and kind/name/alias/notes presentation for source choices; do not use facts to rank newly copied records as if locally evidenced. |+| `WorkDetailModel` record drafts / `CharacterEditorView` | No new writer | Copies become ordinary destination editor records; existing combine/delete/convert remain destination correction paths. |+| `LibraryRepository+WorkLinks`, `SeriesSupport`, `SeriesDirectory` | Yes, reads | Determine direct links and complete shared membership under lock; free-text type is a label, not an enum or whitelist. Deduplicate a work eligible by both routes. |+| `LibraryRepository+RecordExtraction` / matching keys | Yes, validation | Derive a fresh key for each copy; include destination retained keys and both sides’ explicit name/aliases in clash detection. No extraction call during preview/copy. |+| `DuplicateScan`, `DuplicateReconciler`, record resolution | No new mechanism | New UUIDs stay independent; same-UUID sync splits/torn groups follow existing rules. Concurrent distinct-UUID copies can coexist and require reader correction. |+| `ArchiveRecordBuilders`, `BackupV19Exporter` (predecessor character/place payload), `BackupImportRecords` | No new shape; add coverage | Existing record archive carries UUID/work/name/key/aliases/note/facts/timestamps. Export ordinary destination records; repeated archive import is UUID-idempotent. |+| `MarkdownExport`, `LibraryRepository+Export` | No record-transfer format | Copy does not broaden Markdown's existing Work/Entry export payload; backup is the record round-trip acceptance surface. |+| share-extension capture / `ShareCharacterChipsView` | No copy UI | Destination characters enter its normal work-scoped character projection; no related-work writer is exposed to the extension. |+| reconciliation and export-owed publication | Existing reader-write hooks | Publish successful destination changes through the same repository/provider refresh/export scheduling as existing record commits; no independent reconciler. |++## Components and contracts++New pure values live in `Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swift`; locked store operations live in `LibraryRepository+RecordCopy.swift`. App session model/view live beside `WorkMergeModel`/`WorkMergeView` and follow their value-draft/preview/refusal separation. The names below describe the contract, not a public API commitment.++```+RecordCopySelection(kind, sourceRecordID, copyChoice: skip | copy, acknowledgedClashes)+RecordCopyContentOptions(includeRecordNotes: Bool)+RecordCopyPreview(sourceWorkID, destinationWorkID, choices, basis, plannedRows)+previewRecordCopy(...) async throws -> RecordCopyPreview+commitRecordCopy(previewBasis, selections, options) async throws -> RecordCopyOutcome+```++Preview is read-only. Its basis captures selected groups’ torn state, ownership/key consistency and copied payload; source/destination writable Work group state; relevant eligibility evidence; and the complete same-kind destination name-key/name/alias surface. Use immutable Sendable values and application UUIDs, never `PersistentIdentifier`. Read selected source IDs and discovered destination IDs again through `RecordRow.rows(ids:)` after work-scoped fetches so every sibling of each logical identity is included. Refuse a selection whose sibling owners are absent/different from the source or whose retained keys disagree, even if authored content is non-torn. Compare only the copied payload (including notes when selected), identity/ownership/key consistency and torn state; a fact-only change does not invalidate a names-only preview.++Planned copy keys are normalized displayed name and explicit aliases. Destination keys also include its retained `nameKey`; source retained keys are inspected for consistency but are not transferred. Ignore empty normalized aliases. This is the existing locale-independent NFC/case-fold/article normalization. Compare within kind against every destination logical group, including torn groups, and every selected source group. Display concrete conflicting names, not only an ambiguous boolean. Start every potentially conflicted selection at Skip. Recompute actual clashes over planned creations plus existing destination records; a Keep separate confirmation acknowledges those concrete overlaps and warns that extraction may attach future facts to either record. Changes that add another planned overlap clear affected acknowledgements. Existing `RecordMatching` routes deterministically by current-name tier, then retained-key tier, then aliases, lowest UUID within a tier; duplicate intent is ambiguous even though routing is deterministic. Keep informational batch overlap labels stable over all selected records, including Skip rows, but do not require acknowledgement for an overlap where no conflicting record will be created. Deselecting a row removes its informational overlap too. An already-torn destination record is not overwritten and still contributes all variant and sibling match keys to the preview; destination owner/key inconsistencies refuse acceptance.++For an accepted copy use the session-planned fresh destination UUID, derive `nameKey` from the copied displayed name, preserve displayed name and aliases, include the exact source record note only if requested, and write no facts. A copy begins matching history as a new manual record; explicit aliases preserve only names the reader can see. Created/modified timestamps use the repository quantized clock at commit; source timestamps are not destination creation history. Attach using the appropriate `RecordRow` conformance; do not reuse source owner references. Copy no suppressions or coverage. Clear only destination candidate suppression for the new record's derived matching key, matching manual-create's re-created-record rule; do not clear unrelated alias or fact suppression state.++Commit opens one exclusive repository context, re-derives eligibility/groups/clashes and compares the preview basis before mutating. Refuse the whole request if any selected source is gone/torn/changed, either work is gone/torn/unwritable, relationship eligibility is lost, destination name surface changed, or clash acknowledgements do not cover the current plan. Insert both kinds in one transaction through `RepositorySaveStrategy`; any refusal or thrown save failure explicitly rolls back the whole batch (the locked-context helper itself does not do so). Re-fault before deriving failure evidence because SwiftData rollback does not restore in-memory `@Model` properties. Source remains read-only; no work metadata/link/membership timestamp is stamped merely to advertise record creation.++The session has one in-flight acceptance task, rejects repeated taps and retains its value draft on refusal. After confirmed success it becomes terminal and dismisses; a retry after a definite failed save gets a fresh preview. Allocate destination UUIDs in the immutable session plan before acceptance and retain them across an uncertain response. Re-query kind/UUID for planned creations only (not Skip rows), under the exclusive repository lock, including every same-ID sibling. All present with expected owner/key/payload means committed; partial/conflicting results refuse further acceptance and keep the draft with an inspection error. None present returns to a refreshed preview without automatically retrying: absence cannot distinguish an uncommitted operation from a later deletion. State that an explicit retry may recreate a copy deleted elsewhere, and retain the same planned IDs for that conscious retry. Names are never evidence that this session committed. Cross-device exactly-once copies are not promised: two offline devices may independently mint UUIDs, and existing record rules intentionally do not collapse by name. Do not add a receipt table to hide that limit.++## UI baseline++Source/destination navigation follows `WorkMergeView`'s work selection context. Record kinds and summaries use `RecordKindPresentation`, Work detail's record cards and `CharacterEditorView` labels, not an invented chip vocabulary. The sheet contains destination, character/place lists with scoped select-all, Include record notes, and preview lines carrying Copy/Skip and Keep separate confirmation only for actual planned clashes. The final Copy button shows planned count; zero creations disables it. Torn/absent/write refusals use existing record/work resolution navigation and preserve the copy draft. On iPad/Mac use existing sheet/column patterns and test escape/cancel, keyboard controls, VoiceOver names and long lists (Req 4.5).++## Future validation strategy++No builds/tests are run for this specification. Development uses a bounded shared slot and the Makefile phase policy; full UI gates belong to pre-push review rather than every edit.++| Requirement | Targeted future coverage |+| --- | --- |+| 1 | Pure eligible-work tests: direct link both directions/all types, same complete series UUID, both-route dedupe, equal titles/names, self/absent/torn/transitive exclusion. Real repository fixtures for split groups/owner reads. |+| 2 | Generic character/place payload tests: fresh UUID/owner/timestamps, fresh key for renamed source, explicit aliases, note option, zero facts/suppressions/coverage transferred; source byte-for-byte unchanged; destination editor/extraction matching works; V19/current backup export/import twice keeps independent IDs/content. |+| 3 | Name/current key/retained key/alias collisions, batch-internal collisions, torn destination variants, empty aliases, Unicode/article normalization, cross-kind independence, repeat copy Skip default; source/destination/eligibility changes after preview refuse without writes. |+| 4 | Real SwiftData save-strategy failure after mixed-kind insert; reopen to prove zero partial rows/suppression changes. Refusal preserves draft; double tap one local commit; cancel/reopen no writes; destination navigation and subsequent editor correction. |+| Rendered journeys | Focused new copy suite on dedicated phone and iPad fixtures: URL-free series books, direct-related works, both kinds, record-note preview, clashes/Keep separate, cancel, stale preview and accessibility/keyboard checks. Verify exact expected method identifiers and count. |++For pure eligibility and clash plans, table-driven permutations of selection/order and key sets verify order-independent clash detection and no source mutation; no new property-testing dependency is justified. Native store tests remain required for save/rollback/ownership; pure plan tests cannot substitute. Live CloudKit arrival behavior is not claimed by isolated tests; any two-device check requires separate device-run authorization and preserved library data.++## Series-add offer integration (Req 5)++Use an app-local save-completion event, not a derived condition observed on load. `WorkDetailModel.save` calls `LibraryProviding.updateWork`; `commitEditing` performs metadata, record, link and membership-removal steps before ending edit mode. The actual resolved pre/post membership and resolved destination UUID must be returned from the locked metadata transaction as an immutable transition receipt; a stale editor basis plus generic `.committed` is not join evidence. Capture the receipt before `onMutation` or reload, retain a pending offer after a confirmed join, and present only after `commitEditing` reaches terminal success. If a later step refuses, keep the event pending in that editor; a successful retry presents it once. A subsequent confirmed transition into another series replaces the pending destination/series; a confirmed leave clears it; same-series metadata/position changes preserve it. Emit only the final confirmed target, validated against saved membership, once. Cancel/navigation discards that pending event and never reverses the saved membership. `SeriesDetailModel.save` snapshots staged additions before `commitSeriesEdits`, intersects addition intent with actual resolved membership transitions returned by the locked series transaction, then raises one completion event after the committed callback and inline edit-mode exit. No prompt occurs on a staged selection.++A join event means previous complete membership had another series UUID or none, and the saved membership now names a series. Same-series position changes and no-op Save are not joins. Event identity is the local save session plus destination UUID; a small in-memory consumed-event set in the copy-offer coordinator prevents duplicate callbacks/reloads in that session. Do not persist offer history, add model columns or key a preference by series/work: no event is reconstructed on launch, so decline/cancel cannot nag on reopen. Explicit later leave/rejoin is a new reader action and can offer again. Offer dismissal is final for that event even if copying was cancelled.++Read saved series members through the repository after completion. Determine the nearest lower saved logical membership position from all complete locally known member groups before filtering for record/write availability. The predecessor candidates are only the group(s) at that nearest-lower position; do not broaden to older positions because the nearest bucket is tied, torn, unavailable or empty. One available non-torn candidate with no tied peer is prefilled. A tied nearest-lower bucket opens an explicit source chooser restricted to its available non-torn members with eligible records, even if only one such candidate is currently available; explain the tied position and name unavailable tied peers so this is a deliberate source confirmation, not an apparently pointless picker. No qualifying candidate means no offer. No strictly earlier position means no offer. Destination-position ties do not establish predecessor order among same-position peers: use the same strictly-lower bucket, never title/UUID tie-breaks or creation timestamps. The chooser uses existing series context labels including positions. If known membership evidence disagrees such that the nearest-lower bucket cannot be established, omit the automatic offer; the manual copy command remains available.++For a batch addition, read the final saved membership set; newly added works may be predecessors of another addition. Evaluate each destination, retain only nonempty eligible offers and present one combined destination list. Label this as reviewing one addition and point to the manual Copy action for the others. Use “Review characters and places from [source]” for a resolved offer action and reserve Copy for final acceptance. Choosing one opens the normal copy session; closing it consumes the whole batch offer and other destinations remain reachable manually. Reproject the nearest-lower position bucket when accepting an offer. If membership, ordering or the confirmed source-choice set changed, refresh/drop the offer and require a new source confirmation; never silently switch the source. Once the reader has confirmed the source and entered the ordinary copy session, use its existing eligibility/content/commit gates; later series reordering does not invalidate a deliberately chosen eligible source. an asynchronous offer read never bypasses copy commit gates. If the saved destination left the series or the host navigated away before presenting, drop the offer silently rather than presenting a stale modal.++### Series membership write parity audit++| Write/caller | Offer hook | Reason |+| --- | --- | --- |+| `WorkDetailModel.save` → `updateWork`; `commitEditing` terminal success | Yes | Direct reader joining through work editor; queue confirmed metadata membership change until the whole editor succeeds. |+| `SeriesDetailModel.save` → `commitSeriesEdits` | Yes | Direct reader staged additions; capture batch before clearing stagedAdditions and offer once after confirmed Save. |+| `NewWorkFormModel.save` → `createWork` | No | `NewWorkDraft` has no series membership; a later saved assignment uses the work editor hook. |+| `LibraryRepository+Series.deleteSeries` | No | Clears membership, never joins. |+| `LibraryRepository+WorkMerge` | No | Carries membership as merge semantics, not the reader's Add to series action. |+| `LibraryRepository+DuplicateResolution`, reconciliation | No | Carries/converges existing authored membership; no new reader join event. |+| `LibraryRepository+ConfirmImport.commitMemberships` / `+BackupImport` | No | Restore/import writes must not prompt for each restored work. |+| `AppLibraryModel` DEBUG scenario `updateWork` calls | No | Fixture population is not an interactive series join. |+| `LibraryProviding`, preview/query APIs and mocks | Yes, app receipt variants and reads | Add typed transition-receipt writer seams for the two app callers plus shared copy-offer projection; no global writer side effect or new event in extension. |+| `SeriesDetailView` / `WorkDetailView`, phone/iPad/Mac navigation hosts | Yes | Present one coordinator-owned offer after edit-mode exit and mutation/reload completion with no member picker/other modal active, not competing sheets; navigation/disappearance cancels stale presentation. |++Transition receipts are value/API additions, not persisted history. Keep existing `updateWork`/`commitSeriesEdits` contracts for other consumers; add app-facing receipt variants that share the same internal locked implementations and map their ordinary write outcome plus actual resolved membership changes, with no duplicate save. Receipts retain addressedWorkID→resolvedWorkID mapping because redirect resolution can target a surviving UUID different from the picker/editor identity. Intersect captured staged-addition intent by addressed ID, then deduplicate events by resolved ID. For multiple addressed IDs resolving to one target, use its transaction-initial pre-membership and final post-membership, not an intermediate loop state. Receipts are created only from a committed transaction, never a refusal or failed save. Add provider and mock parity for these variants; do not infer receipt data from load-time snapshots.++Offer projection values and predecessor eligibility logic belong beside `WorkRecordCopy` in Core; app-local queue/consumed events belong in `RecordCopyOfferCoordinator` beside the copy session model. The repository returns immutable offer projections and performs no UI side effects. Use existing sheet/picker presentation ownership and stable destination IDs; do not derive prompts from `snapshotGeneration`.++## Offer validation and design approval++Future targeted tests cover both editor paths; confirmed membership followed by record/link refusal then successful retry; cancelled/no-op/position-only saves; direct move between series; repeated callbacks/reload/relaunch; ties at destination and nearest-lower position; fractional/negative positions; first member; no available records; batch additions, addressed IDs redirecting to one survivor, predecessor position/member changes before opening the session, and stale host navigation. Include phone/iPad rendered acceptance that accepting an offer prefills the normal flow without selecting/copying anything, and Cancel preserves membership. Pure predecessor projection tests permute input ordering; display-title/creation-date changes must not alter the result.++Design recommendations awaiting approval: tied nearest-lower positions open a chooser restricted to that position bucket; same-position destination peers are not treated as predecessors; bulk additions produce one combined offer; decline/cancel consumes only the initiating save event and explicit leave/rejoin can offer again. No persisted history is needed. Does the design look good?+++---++## 5. Offer after adding a work to a series++As a reader, I want an offer to copy records after adding a work to a series, so that the preceding book's cast and setting are available without a separate search.++1. <a name="5.1"></a>WHEN a reader saves a work joining a series through the work editor or series editor, the system SHALL offer to review copying from the preceding work after the editor successfully finishes; it SHALL NOT copy records automatically.+2. <a name="5.2"></a>The system SHALL determine the predecessor from saved series positions, not creation dates or title tie-break order. WHEN the nearest strictly lower position contains multiple predecessor candidates, the system SHALL ask the reader to choose among available candidates at that position rather than infer one from a display tie-break; it SHALL NOT silently skip an unavailable predecessor for an older work.+3. <a name="5.3"></a>WHEN the destination is first in the series or there is no available eligible character/place record in the predecessor choices, the system SHALL omit the offer.+4. <a name="5.4"></a>Accepting an offer SHALL open the ordinary selection/preview flow with source and destination prefilled and no selected records; declining or cancelling SHALL leave the saved series membership intact and copy nothing.+5. <a name="5.5"></a>The system SHALL offer at most once for each successful series-joining save event; reloading, reopening, unrelated edits, position-only edits and sync/import arrivals SHALL NOT repeat it. A later saved leave/rejoin or move into another series MAY produce a new offer.+6. <a name="5.6"></a>WHEN one series save adds multiple works, the system SHALL present one offer containing eligible additions rather than a sequence of prompts, and let the reader choose which destination to review.++Additional acceptance examples: joining at position 3 after positions 1 and 2 offers position 2 even if position 1 was created later; joining at position 1 omits the offer; tied nearest preceding positions require a source choice; declining then editing notes produces no repeat; a batch addition produces one combined offer; failed/cancelled saves and CloudKit/import arrival produce none.++## Design decisions awaiting approval++The approved defaults are names/explicit aliases with fresh name-derived keys, optional record notes off, no extracted facts; Skip/explicit Keep separate without merging; and any direct link/shared complete-series UUID eligibility. New offer edge cases are reviewed in design: source choice for tied positions, one combined batch offer, and save-event-scoped suppression rather than persisted history. Does the design look good?
diff --git a/specs/copy-work-records/design.md b/specs/copy-work-records/design.mdnew file mode 100644index 00000000..010b12e9--- /dev/null+++ b/specs/copy-work-records/design.md@@ -0,0 +1,101 @@+# Copy work records — design++Status: Design approved by the user on 2026-10-12, including the series-add offer defaults. User explicitly authorized task planning and implementation. Approved design checkpoint: original specification commit 78795d41; implementation branch T-2439/copy-work-records.++## Architecture and repository grounding++Add an app-only copy session from a saved work detail's actions while outside edit mode. The session chooses one destination, selects records and previews results; its toolbar Copy is its one save boundary. `WorkDetailView`/`WorkDetailModel` launch the session but do not reuse their staged record edits to write another work. This keeps cancellation and work-editor drafts independent (Req 1, 4).++Use `RecordRow` generics for character/place reads and creation. The persisted tables remain unchanged: characters attach through `Character.work`, places through `Place.workID`; both conformances supply `rows(of:)`, `make` and `attach`. `RecordGroups.swift` groups only by kind/application UUID, never name; two separate copies must therefore mint distinct UUIDs. Do not call existing combine or conversion operations: `LibraryRepository+RecordEditing.swift`'s combine moves content and suppression state within one work, and conversion changes kind, while this operation leaves the source untouched.++No schema, readiness-marker or archive-generation bump is needed for the recommended payload. There is no persisted provenance link or copy-history table. Names, aliases, notes, timestamps and ownership fit existing `Character`/`Place` and existing UUID-keyed archive records. CloudKit uses the existing non-unique/defaulted model columns and tolerates children arriving ahead of their owner.++### Pattern-extension audit++| Existing integration | Needs copy equivalent | Contract |+| --- | --- | --- |+| `RecordRow`, `RecordGroup`, `RecordAuthoredContent` | Yes | Read whole logical groups; unavailable torn selections never copy a representative variant silently. |+| `WorkRecordPresentation`, `RecordRanking` | Yes | Reuse display order and kind/name/alias/notes presentation for source choices; do not use facts to rank newly copied records as if locally evidenced. |+| `WorkDetailModel` record drafts / `CharacterEditorView` | No new writer | Copies become ordinary destination editor records; existing combine/delete/convert remain destination correction paths. |+| `LibraryRepository+WorkLinks`, `SeriesSupport`, `SeriesDirectory` | Yes, reads | Determine direct links and complete shared membership under lock; free-text type is a label, not an enum or whitelist. Deduplicate a work eligible by both routes. |+| `LibraryRepository+RecordExtraction` / matching keys | Yes, validation | Derive a fresh key for each copy; include destination retained keys and both sides’ explicit name/aliases in clash detection. No extraction call during preview/copy. |+| `DuplicateScan`, `DuplicateReconciler`, record resolution | No new mechanism | New UUIDs stay independent; same-UUID sync splits/torn groups follow existing rules. Concurrent distinct-UUID copies can coexist and require reader correction. |+| `ArchiveRecordBuilders`, `BackupV19Exporter` (predecessor character/place payload), `BackupImportRecords` | No new shape; add coverage | Existing record archive carries UUID/work/name/key/aliases/note/facts/timestamps. Export ordinary destination records; repeated archive import is UUID-idempotent. |+| `MarkdownExport`, `LibraryRepository+Export` | No record-transfer format | Copy does not broaden Markdown's existing Work/Entry export payload; backup is the record round-trip acceptance surface. |+| share-extension capture / `ShareCharacterChipsView` | No copy UI | Destination characters enter its normal work-scoped character projection; no related-work writer is exposed to the extension. |+| reconciliation and export-owed publication | Existing reader-write hooks | Publish successful destination changes through the same repository/provider refresh/export scheduling as existing record commits; no independent reconciler. |++## Components and contracts++New pure values live in `Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swift`; locked store operations live in `LibraryRepository+RecordCopy.swift`. App session model/view live beside `WorkMergeModel`/`WorkMergeView` and follow their value-draft/preview/refusal separation. The names below describe the contract, not a public API commitment.++```+RecordCopySelection(kind, sourceRecordID, copyChoice: skip | copy, acknowledgedClashes)+RecordCopyContentOptions(includeRecordNotes: Bool)+RecordCopyPreview(sourceWorkID, destinationWorkID, choices, basis, plannedRows)+previewRecordCopy(...) async throws -> RecordCopyPreview+commitRecordCopy(previewBasis, selections, options) async throws -> RecordCopyOutcome+```++Preview is read-only. Its basis captures selected groups’ torn state, ownership/key consistency and copied payload; source/destination writable Work group state; relevant eligibility evidence; and the complete same-kind destination name-key/name/alias surface. Use immutable Sendable values and application UUIDs, never `PersistentIdentifier`. Read selected source IDs and discovered destination IDs again through `RecordRow.rows(ids:)` after work-scoped fetches so every sibling of each logical identity is included. Refuse a selection whose sibling owners are absent/different from the source or whose retained keys disagree, even if authored content is non-torn. Compare only the copied payload (including notes when selected), identity/ownership/key consistency and torn state; a fact-only change does not invalidate a names-only preview.++Planned copy keys are normalized displayed name and explicit aliases. Destination keys also include its retained `nameKey`; source retained keys are inspected for consistency but are not transferred. Ignore empty normalized aliases. This is the existing locale-independent NFC/case-fold/article normalization. Compare within kind against every destination logical group, including torn groups, and every selected source group. Display concrete conflicting names, not only an ambiguous boolean. Start every potentially conflicted selection at Skip. Recompute actual clashes over planned creations plus existing destination records; a Keep separate confirmation acknowledges those concrete overlaps and warns that extraction may attach future facts to either record. Changes that add another planned overlap clear affected acknowledgements. Existing `RecordMatching` routes deterministically by current-name tier, then retained-key tier, then aliases, lowest UUID within a tier; duplicate intent is ambiguous even though routing is deterministic. Keep informational batch overlap labels stable over all selected records, including Skip rows, but do not require acknowledgement for an overlap where no conflicting record will be created. Deselecting a row removes its informational overlap too. An already-torn destination record is not overwritten and still contributes all variant and sibling match keys to the preview; destination owner/key inconsistencies refuse acceptance.++For an accepted copy use the session-planned fresh destination UUID, derive `nameKey` from the copied displayed name, preserve displayed name and aliases, include the exact source record note only if requested, and write no facts. A copy begins matching history as a new manual record; explicit aliases preserve only names the reader can see. Created/modified timestamps use the repository quantized clock at commit; source timestamps are not destination creation history. Attach using the appropriate `RecordRow` conformance; do not reuse source owner references. Copy no suppressions or coverage. Clear only destination candidate suppression for the new record's derived matching key, matching manual-create's re-created-record rule; do not clear unrelated alias or fact suppression state.++Commit opens one exclusive repository context, re-derives eligibility/groups/clashes and compares the preview basis before mutating. Refuse the whole request if any selected source is gone/torn/changed, either work is gone/torn/unwritable, relationship eligibility is lost, destination name surface changed, or clash acknowledgements do not cover the current plan. Insert both kinds in one transaction through `RepositorySaveStrategy`; any refusal or thrown save failure explicitly rolls back the whole batch (the locked-context helper itself does not do so). Re-fault before deriving failure evidence because SwiftData rollback does not restore in-memory `@Model` properties. Source remains read-only; no work metadata/link/membership timestamp is stamped merely to advertise record creation.++The session has one in-flight acceptance task, rejects repeated taps and retains its value draft on refusal. After confirmed success it becomes terminal and dismisses; a retry after a definite failed save gets a fresh preview. Allocate destination UUIDs in the immutable session plan before acceptance and retain them across an uncertain response. Re-query kind/UUID for planned creations only (not Skip rows), under the exclusive repository lock, including every same-ID sibling. All present with expected owner/key/payload means committed; partial/conflicting results refuse further acceptance and keep the draft with an inspection error. None present returns to a refreshed preview without automatically retrying: absence cannot distinguish an uncommitted operation from a later deletion. State that an explicit retry may recreate a copy deleted elsewhere, and retain the same planned IDs for that conscious retry. Names are never evidence that this session committed. Cross-device exactly-once copies are not promised: two offline devices may independently mint UUIDs, and existing record rules intentionally do not collapse by name. Do not add a receipt table to hide that limit.++## UI baseline++Source/destination navigation follows `WorkMergeView`'s work selection context. Record kinds and summaries use `RecordKindPresentation`, Work detail's record cards and `CharacterEditorView` labels, not an invented chip vocabulary. The sheet contains destination, character/place lists with scoped select-all, Include record notes, and preview lines carrying Copy/Skip and Keep separate confirmation only for actual planned clashes. The final Copy button shows planned count; zero creations disables it. Torn/absent/write refusals use existing record/work resolution navigation and preserve the copy draft. On iPad/Mac use existing sheet/column patterns and test escape/cancel, keyboard controls, VoiceOver names and long lists (Req 4.5).++## Future validation strategy++No builds/tests are run for this specification. Development uses a bounded shared slot and the Makefile phase policy; full UI gates belong to pre-push review rather than every edit.++| Requirement | Targeted future coverage |+| --- | --- |+| 1 | Pure eligible-work tests: direct link both directions/all types, same complete series UUID, both-route dedupe, equal titles/names, self/absent/torn/transitive exclusion. Real repository fixtures for split groups/owner reads. |+| 2 | Generic character/place payload tests: fresh UUID/owner/timestamps, fresh key for renamed source, explicit aliases, note option, zero facts/suppressions/coverage transferred; source byte-for-byte unchanged; destination editor/extraction matching works; V19/current backup export/import twice keeps independent IDs/content. |+| 3 | Name/current key/retained key/alias collisions, batch-internal collisions, torn destination variants, empty aliases, Unicode/article normalization, cross-kind independence, repeat copy Skip default; source/destination/eligibility changes after preview refuse without writes. |+| 4 | Real SwiftData save-strategy failure after mixed-kind insert; reopen to prove zero partial rows/suppression changes. Refusal preserves draft; double tap one local commit; cancel/reopen no writes; destination navigation and subsequent editor correction. |+| Rendered journeys | Focused new copy suite on dedicated phone and iPad fixtures: URL-free series books, direct-related works, both kinds, record-note preview, clashes/Keep separate, cancel, stale preview and accessibility/keyboard checks. Verify exact expected method identifiers and count. |++For pure eligibility and clash plans, table-driven permutations of selection/order and key sets verify order-independent clash detection and no source mutation; no new property-testing dependency is justified. Native store tests remain required for save/rollback/ownership; pure plan tests cannot substitute. Live CloudKit arrival behavior is not claimed by isolated tests; any two-device check requires separate device-run authorization and preserved library data.++## Series-add offer integration (Req 5)++Use an app-local save-completion event, not a derived condition observed on load. `WorkDetailModel.save` calls `LibraryProviding.updateWork`; `commitEditing` performs metadata, record, link and membership-removal steps before ending edit mode. The actual resolved pre/post membership and resolved destination UUID must be returned from the locked metadata transaction as an immutable transition receipt; a stale editor basis plus generic `.committed` is not join evidence. Capture the receipt before `onMutation` or reload, retain a pending offer after a confirmed join, and present only after `commitEditing` reaches terminal success. If a later step refuses, keep the event pending in that editor; a successful retry presents it once. A subsequent confirmed transition into another series replaces the pending destination/series; a confirmed leave clears it; same-series metadata/position changes preserve it. Emit only the final confirmed target, validated against saved membership, once. Cancel/navigation discards that pending event and never reverses the saved membership. `SeriesDetailModel.save` snapshots staged additions before `commitSeriesEdits`, intersects addition intent with actual resolved membership transitions returned by the locked series transaction, then raises one completion event after the committed callback and inline edit-mode exit. No prompt occurs on a staged selection.++A join event means previous complete membership had another series UUID or none, and the saved membership now names a series. Same-series position changes and no-op Save are not joins. Event identity is the local save session plus destination UUID; a small in-memory consumed-event set in the copy-offer coordinator prevents duplicate callbacks/reloads in that session. Do not persist offer history, add model columns or key a preference by series/work: no event is reconstructed on launch, so decline/cancel cannot nag on reopen. Explicit later leave/rejoin is a new reader action and can offer again. Offer dismissal is final for that event even if copying was cancelled.++Read saved series members through the repository after completion. Determine the nearest lower saved logical membership position from all complete locally known member groups before filtering for record/write availability. The predecessor candidates are only the group(s) at that nearest-lower position; do not broaden to older positions because the nearest bucket is tied, torn, unavailable or empty. One available non-torn candidate with no tied peer is prefilled. A tied nearest-lower bucket opens an explicit source chooser restricted to its available non-torn members with eligible records, even if only one such candidate is currently available; explain the tied position and name unavailable tied peers so this is a deliberate source confirmation, not an apparently pointless picker. No qualifying candidate means no offer. No strictly earlier position means no offer. Destination-position ties do not establish predecessor order among same-position peers: use the same strictly-lower bucket, never title/UUID tie-breaks or creation timestamps. The chooser uses existing series context labels including positions. If known membership evidence disagrees such that the nearest-lower bucket cannot be established, omit the automatic offer; the manual copy command remains available.++For a batch addition, read the final saved membership set; newly added works may be predecessors of another addition. Evaluate each destination, retain only nonempty eligible offers and present one combined destination list. Label this as reviewing one addition and point to the manual Copy action for the others. Use “Review characters and places from [source]” for a resolved offer action and reserve Copy for final acceptance. Choosing one opens the normal copy session; closing it consumes the whole batch offer and other destinations remain reachable manually. Reproject the nearest-lower position bucket when accepting an offer. If membership, ordering or the confirmed source-choice set changed, refresh/drop the offer and require a new source confirmation; never silently switch the source. Once the reader has confirmed the source and entered the ordinary copy session, use its existing eligibility/content/commit gates; later series reordering does not invalidate a deliberately chosen eligible source. an asynchronous offer read never bypasses copy commit gates. If the saved destination left the series or the host navigated away before presenting, drop the offer silently rather than presenting a stale modal.++### Series membership write parity audit++| Write/caller | Offer hook | Reason |+| --- | --- | --- |+| `WorkDetailModel.save` → `updateWork`; `commitEditing` terminal success | Yes | Direct reader joining through work editor; queue confirmed metadata membership change until the whole editor succeeds. |+| `SeriesDetailModel.save` → `commitSeriesEdits` | Yes | Direct reader staged additions; capture batch before clearing stagedAdditions and offer once after confirmed Save. |+| `NewWorkFormModel.save` → `createWork` | No | `NewWorkDraft` has no series membership; a later saved assignment uses the work editor hook. |+| `LibraryRepository+Series.deleteSeries` | No | Clears membership, never joins. |+| `LibraryRepository+WorkMerge` | No | Carries membership as merge semantics, not the reader's Add to series action. |+| `LibraryRepository+DuplicateResolution`, reconciliation | No | Carries/converges existing authored membership; no new reader join event. |+| `LibraryRepository+ConfirmImport.commitMemberships` / `+BackupImport` | No | Restore/import writes must not prompt for each restored work. |+| `AppLibraryModel` DEBUG scenario `updateWork` calls | No | Fixture population is not an interactive series join. |+| `LibraryProviding`, preview/query APIs and mocks | Yes, app receipt variants and reads | Add typed transition-receipt writer seams for the two app callers plus shared copy-offer projection; no global writer side effect or new event in extension. |+| `SeriesDetailView` / `WorkDetailView`, phone/iPad/Mac navigation hosts | Yes | Present one coordinator-owned offer after edit-mode exit and mutation/reload completion with no member picker/other modal active, not competing sheets; navigation/disappearance cancels stale presentation. |++Transition receipts are value/API additions, not persisted history. Keep existing `updateWork`/`commitSeriesEdits` contracts for other consumers; add app-facing receipt variants that share the same internal locked implementations and map their ordinary write outcome plus actual resolved membership changes, with no duplicate save. Receipts retain addressedWorkID→resolvedWorkID mapping because redirect resolution can target a surviving UUID different from the picker/editor identity. Intersect captured staged-addition intent by addressed ID, then deduplicate events by resolved ID. For multiple addressed IDs resolving to one target, use its transaction-initial pre-membership and final post-membership, not an intermediate loop state. Receipts are created only from a committed transaction, never a refusal or failed save. Add provider and mock parity for these variants; do not infer receipt data from load-time snapshots.++Offer projection values and predecessor eligibility logic belong beside `WorkRecordCopy` in Core; app-local queue/consumed events belong in `RecordCopyOfferCoordinator` beside the copy session model. The repository returns immutable offer projections and performs no UI side effects. Use existing sheet/picker presentation ownership and stable destination IDs; do not derive prompts from `snapshotGeneration`.++## Offer validation and design approval++Future targeted tests cover both editor paths; confirmed membership followed by record/link refusal then successful retry; cancelled/no-op/position-only saves; direct move between series; repeated callbacks/reload/relaunch; ties at destination and nearest-lower position; fractional/negative positions; first member; no available records; batch additions, addressed IDs redirecting to one survivor, predecessor position/member changes before opening the session, and stale host navigation. Include phone/iPad rendered acceptance that accepting an offer prefills the normal flow without selecting/copying anything, and Cancel preserves membership. Pure predecessor projection tests permute input ordering; display-title/creation-date changes must not alter the result.++Approved design defaults: tied nearest-lower positions open a chooser restricted to that position bucket; same-position destination peers are not treated as predecessors; bulk additions produce one combined offer; decline/cancel consumes only the initiating save event and explicit leave/rejoin can offer again. No persisted history is needed.
diff --git a/specs/copy-work-records/implementation.md b/specs/copy-work-records/implementation.mdnew file mode 100644index 00000000..ac973173--- /dev/null+++ b/specs/copy-work-records/implementation.md@@ -0,0 +1,225 @@+# T-2439 implementation and verification++User approved reviewed design78795d41 with “Approved. Create tasks and implement”. Requirements and offer defaults are approved; task planning and implementation need no repeated approval. Fourteen Rune tasks in one stream span Core contracts1–6 and App flows7–14. Planning/source checkpoint e07d880b on T-2439/copy-work-records in the dedicated asterism-t2439 worktree; base remote main8aef9858. PR105/106 and original spec worktree remain untouched.++T-2439 is implemented and source-reviewed in draft PR107: https://github.com/ArjenSchwarz/asterism/pull/107. All 14 implementation tasks are complete. The branch is rebased onto main bdbae0d5; original commits remain recoverable at `refs/backup/t2439-before-alias-fix-20261012`.++The historical alias-chip failure has now been reproduced and traced to the UI-test helper tapping the tab bar, rather than missing application aliases. Only test navigation changed: require full pill viewport/tab clearance, verify work detail after the tap, and use the stable Today identifier on both List and wide ScrollView. Alias/fact/citation assertions remain intact. All four affected iPad consumers passed on corrected source; final phone selection passed all four affected consumers and all 13 copying/offer methods (17/17). Fresh unfiltered Core passed 3,870 summary declarations with opt-in skips retained, official fast passed 456, and signed Mac/full native passed 1,738 declarations / 1,794 invocations with zero failures/skips. Final evidence stems are pr107-alias-final-core, pr107-alias-final-fast, pr107-alias-final-native, pr107-alias-green-ipad3 and pr107-final-focused-phone under /tmp. See [bugfix report](../bugfixes/alias-chip-tap-enters-tab-bar/report.md).++The previous full-UI outcomes below remain historical evidence, including original failures, two opt-in skips and the unfinalized watchdog bundle. Focused verification does not turn those scopes into a unified green full-phone gate. No merge or device install.++## Historical delivery checkpoint before alias investigation++T-2439 is implemented and source-reviewed in qualified draft PR107: https://github.com/ArjenSchwarz/asterism/pull/107. The design review and previous delivery below are historical checkpoints; copying implementation was authorized after that delivery. Final UI acceptance has an unresolved existing character-extraction journey and is not green.++Current state: Core tasks 1–6 remain committed at ad71e6b1; app tasks 7–14 are committed at 5f1eae6c and source-reviewed, with all 14 Rune implementation tasks complete. Fresh unfiltered Core (3,870 declarations) and signed Mac/full native (1,734 declarations / 1,790 invocations) passed. All 13 copying/offer journeys passed in the final phone continuation; all 13 also have retained passing targeted iPad evidence. The full iPad gate passed all 30 expected identities. All 227 expected phone identities are accounted for across the user-interrupted gate, bounded continuation and exact remaining-case follow-up; original failures, two opt-in skips and the watchdog outcome remain preserved. The accessibility failure passed its single retry; the unchanged alias-chip assertion failed its single retry and remains flagged. There is no unified green phone/full-UI verdict. All owned test commands drained and both dedicated simulators are Shutdown; no further heavy checks are queued. Qualified evidence is published with the draft; final UI acceptance remains blocked as described below.++Recall applied: retained ModelContainer lifetimes, SwiftData rollback/refault and actual SwiftUI accessibility identifiers. No schema/history table, new dependency, automatic copy, merge, deployment or physical-device install is authorized.++Final reconciliation: /tmp/t2439-final-ui-reconciliation.json. Resource release: /tmp/t2439-final-owned-release-pressure.json and /tmp/asterism-t2439-heavy-lane.json. Historical failures below remain evidence, not accepted green exceptions.++## Core plan attempts++- `/tmp/asterism-t2439-core-plan-red.log`: exit2 before compilation; default Clang/SwiftPM cache access denied by sandbox. Infrastructure-only, no test result.+- `/tmp/asterism-t2439-core-plan-red2.log`: exit2 after compiler reached the new tests; missing RecordCopyRecord/new contracts. Compile-only red, zero executions.+- Paired green: `/tmp/asterism-t2439-core-plan-green.log`, eight expected declarations after adding the hidden-source-retained-key regression. Exited0: all eight expected declarations in one suite passed (0.006 s test duration, 81.42 s build). Root inspected the actual executed names/count. No source edits during that run. Untouched FoundationModels sampling deprecation diagnostics are recorded separately from new warnings.++## Store contract attempts++Initial store red failed compilation because preview/repository seams were absent, with zero executions. `/tmp/asterism-t2439-core-store-green.log` exited0: eight declarations/15 parameterized invocations passed (0.647 s tests, 69.77 s build), then all owned processes drained. Outcome recovery subsequently aligned with the approved exclusive lock and ignores later destination facts when owner/key/copied payload remain unchanged. Extra regressions cover destination whole-ID inconsistencies, reused IDs/Skip inspection exclusion, actual extraction matching, unavailable works and torn/repeated clashes. Expanded store green2 exited0 after 14 declarations/26 invocations passed (0.917 s), with owned processes drained. No compiler warnings in changed copy files; untouched intelligence deprecations and NoEpisode unnecessary-try diagnostics remain recorded. Failed-save coverage now shuts down and reopens the real temporary store. Source choices reuse RecordRanking and WorkPickerCandidate context; plan identities are kind/UUID composites.++## Membership receipt and offer attempts++Receipt red exited2 because receipt/offer contracts were missing; compile-only, zero executions. First paired green also exited2 before execution: three new URL-free NewWorkDraft fixture calls omitted the existing required hostname argument, with downstream type-inference diagnostics. Corrected fixture calls retain all assertions; second green exited0: all eight declarations/invocations passed (0.222 s tests, 61.96 s build), followed by clear owned-process inventory. Both failed attempts were fully drained and remain preserved.++Core phase critique found no implementation blocker. Before broad gates, it requested real-store coverage for known partial/split membership and tied nearest predecessors with unavailable record siblings; those additions are being written. The full native source inventory has 1,600 Swift Testing declarations in 90 files; that is not a parameterized invocation count or execution claim. Official fast manifest has 456 identifiers. Dedicated T2439 phone/iPad simulators are verified on iOS27; no physical-device installation. No broad run or code commit is claimed yet.++The critic-requested store cases passed in `/tmp/asterism-t2439-core-offer-green3.log`: 11 declarations/15 invocations, 0.442 s tests and 28.36 s build, exit0/drained. Current new coverage is 33 declarations/49 invocations across three suites; the earlier 30/42 checkpoint is retained. Read-only critic delta confirms the actual partial/split/tied-unavailable cases and ordinary/receipt refusal parity, with no remaining Core source blocker.++Next authorized sequential gate batch, not results: unfiltered Core (CORE_TEST empty), official fast, test-quick with signed Mac embedded-extension dependency/full native units, then the two existing Work/Series Save/Cancel UI consumers on dedicated phone and iPad. Expected UI identifiers are WorkDetailConnectionsUITests/testThePickerCreatesASeriesThatSurvivesACancelAndCommitsAPosition and SeriesUITests/testTheSeriesEditorRepositionsAddsAndRemovesMembers. No full UI development run. Each job must exit and drain before the next; post-test diagnostic collectors may be capped only with exact owned-process evidence. No source edits during the frozen batch.++## Core phase gate progress++Unfiltered Core `/tmp/asterism-t2439-core-full.log` exited0 and drained. Four product summaries report 42/8 suites, 304/20, 229/13 and 3,295/308, totaling 3,870 declarations; existing opt-in M4 skips are retained and not called executed passes. The final Core product took 174.435 s, cached build0.56 s. All 33 new declarations/49 invocations executed and passed. No compiler warnings in this incremental gate; previous untouched-source diagnostics remain preserved. Invalid-store fixture CoreData messages accompanied asserted passing cases, not new failure verdicts. Root hash check found all eight frozen source/test files unchanged during this run. Official fast is running next; signed Mac/native and targeted existing UI have no result yet.++Official fast `/tmp/asterism-t2439-fast.log` exited0 and drained: all 456 manifest identifiers verified, product summaries304/20 suites and152/12 suites passed (0.102 s/0.556 s). Signed Mac/full native test-quick is running next on Asterism T2439 Phone with private DerivedData and a unique result bundle; no SKIP_MAC/signing override, install or Mac launch. Source inventory expects1,600 native declarations/1,635 invocations; no native/Mac pass claimed until actual exit/results.++Signed Mac test-quick dependency reports BUILD SUCCEEDED: app and embedded Mac extension signed and embed assertion present. Read-only signature verification first failed under the sandbox with CSSMERR_TP_NOT_TRUSTED; the existing trust-access verification retried outside the sandbox and passed for the app (deep/strict) and embedded extension. No keychain/trust/permission settings changed. Native phone build/test remains running in the same sequential test-quick job; no native result claimed yet.++## Full native failure and continuation++The first full native gate exited2/Xcode65 and fully drained with no diagnostic cap. Structured results show1,670 declarations (1,669 passed, one failed, zero skipped), and1,713 invocations (1,712 passed, one failed). The failed identifier is AppLibraryModelTests/independentStatusDoesNotConsumeTheRoutedEditor. The actual crash report shows EXC_BAD_ACCESS/pointer-auth failure in Swift release/Array.append through MockLibraryProvider.workDetail and WorkDetailModel reload/save. The shared unchecked-Sendable mock has unsynchronized callLog mutations; the proposed correction synchronizes that test recorder without changing product behavior or assertions. Evidence: /tmp/asterism-t2439-native-full.xcresult, corresponding log/summary/tests JSON and /Users/arjen/Library/Logs/DiagnosticReports/Asterism-2026-10-12-161229.ips. No UI jobs or source commit followed the failure.++Correction to earlier inventory: the1,600/1,635 estimate missed70 same-line @MainActor @Test declarations. Source recount confirms1,670 declarations and17 parameterized declarations/60 cases, totaling1,713 invocations, matching actual structured results. Earlier estimates remain historical, not execution evidence.++The root briefly misidentified an old repeated T-2416 approval as the active task and reported its merged PR104. Parent corrected this explicitly: active authorization is T-2439, user approval Sentinel_fdd8643ce9c481919fb362726325f4c6, reviewed design78795d41, through implementation and draft PR. No work was lost or reverted; resume from uncommitted Core source and preserved failed artifacts. PR105/106 and T-2416 remain untouched.++Source correction is confined to MockLibraryProvider and one AppLibraryModelTests regression. A separate call-log lock protects get/set and the whole _modify mutation; existing recorder-lock writers do not recursively acquire the same lock. Work-detail count read/increment share its existing recorder lock. The regression runs8 workers ×64 reloads plus mutation markers, requiring all512 reload events/1,024 total log entries and stable snapshots. Root and independent critic reviewed lock ordering, absence of bypasses and preserved assertions; no source blocker. Runtime verification is pending. Targeted AppLibraryModel suite expects89 declarations/invocations; refreshed full native expects1,671 declarations/1,714 invocations. No product source changed for this correction; previous Core/fast evidence remains reusable only with source-hash confirmation.++Targeted helper correction run /tmp/asterism-t2439-native-repair-targeted.xcresult exited0 and all owned processes drained. Actual chosen AppLibraryModelTests suite has19 declarations/invocations, all passed, no failures/skips/runtime warnings. Both sharedMockRecorderPreservesConcurrentCallsAndSnapshots and independentStatusDoesNotConsumeTheRoutedEditor executed. The earlier89 estimate counted all suites in AppLibraryModelTests.swift; root verified the selected suite boundary and19 source declarations. This is a manifest correction, not a missing selected-test waiver or a claim that all89 ran. Global full-native inventory remains1,671/1,714. Core production/test hashes match prior passing Core/fast evidence. Fresh full-native test-quick is authorized next; no result claimed yet.++Fresh full-native /tmp/asterism-t2439-native-full2.xcresult reports Passed with1,671 declarations, zero failures/skips/runtime warnings. Raw summary reports118 suites/29.228s test duration; structured interval70.465s. Parameterized inventory reconciliation and owned process drain are recorded by the worker receipt; the targeted legacy phone checks have begun. The signed Mac dependency again reports build success. Previous failed native evidence is retained, and no new broad Core/fast run was triggered by the test-helper-only correction.++Full-native reconciliation is complete:1,671 declarations/1,714 invocations passed, zero failures/skips/structured runtime warnings, actual make exit0 and owned process drain. The two selected legacy phone UI identifiers both passed (Series editor57.484s; Work editor102.132s; selected suite159.616s). Phone result finalization/actual exit and iPad checks are still pending at this checkpoint; passing test markers alone do not declare the entire UI job complete.++Phone legacy UI job exited0, both expected identifiers passed, zero failures/skips, and all owned processes drained. The authorized diagnostic-only TERM cap applied at136s to simctl diagnose PID88238/PPID87185 after both methods completed; Xcode finalized normally. Four structured Environment warnings remain (Calendar twice, Optional<CivilDay> twice). These are not hidden or called warning-free. The same two methods on the dedicated iPad are now starting.++The first targeted iPad attempt failed both selected methods before their intended membership assertions: SeriesUITests could not reach Library using its phone-oriented helper (42.315s), and WorkDetailConnectionsUITests could not find recent-list as CollectionView (66.966s). Selected suite109.281s, two failures/zero passed; command finalization and hierarchy inspection are pending. These are actual failed verification attempts, not an accepted baseline or proof of product behavior. Any portable fixture correction must retain the original Save/Cancel/membership assertions and be independently source-reviewed before a fresh affected iPad run.++First iPad job finalized with make exit2, zero passed/two failed/no skips or structured runtime warnings; owned processes drained after authorized diagnostic-collector TERM at143s (PID90200/PPID89181). Actual full AX hierarchy D2BF7856-7330-42BB-B068-2C7811792AA4.txt proves an834×1210 portrait window, collapsed sidebar, recent-list ScrollView and nested Library controls with the same frame. Query-chain-only attachments are not used as hierarchy proof.++A three-file UI-test-only correction follows existing WideLayout firstMatch/type-agnostic query and openAllWorks bounded-frame tap conventions. Both legacy readiness queries retain their identifier/timeout but use anyElement. Shared selectTab retains normal hittable taps; its fallback requires a collapsed sidebar, existing/nonempty control and full frame containment within the app. No orientation, production/native source or membership/Save/Cancel assertion changed. Root and independent critic reviewed the exact delta. The same two iPad methods, followed by the same two phone methods because the helper is shared, are authorized next. Previous Core/fast/signed Mac/native results remain supported by unchanged source hashes; no equivalent broad repeat is justified for this UI-fixture-only change.++The second iPad attempt reaches the real editors but fails both original persistence journeys (Series61.191s; suite157.709s). Raw interaction logs show both Save actions computed hit point {-1,-1}, so this does not establish repository Save/refusal behavior. In Work detail the title-field-gone check passed immediately, but the final saved-series-row assertion correctly failed; disappearance of a possibly offscreen field is not success evidence. Result finalization/actual Save-frame hierarchy inspection remain pending. No production changes or phone rerun followed the failure.++Second iPad job exited2 and drained with two failed/zero skipped/zero structured runtime warnings. Its diagnostic-only TERM cap was at139s, PID93608/PPID91998. Root and worker inspected the full Work AX hierarchy: Save784,36,36×36 is inside834×1210, position2.5 remains focused with keyboard below, editor still open. Both also viewed the unmodified Series video frame at55s (/tmp/asterism-t2439-ipad2-series-frame.png): visible enabled top-right Save, Rising draft3, keyboard below, no app error. Read-only AVFoundation frame decoding first failed under sandbox (exit133/sysctl denial); the same read-only decode succeeded with existing access (exit0). The deprecated API warning belongs only to the temporary decode utility, not repository source.++The narrowly scoped test helper tapEditorSave waits for the existing first-match control, asserts enabled, retains normal hittable taps and permits a fallback only after nonempty/full-app-frame assertions. Both selected journeys each have one Save tap; only those two sites changed. Work retains title-gone and final saved-series checks and adds actual edit-button appearance to prove view mode. Root and independent critic reviewed the exact delta; all prior assertions remain. The third iPad attempt and subsequent current-helper phone confirmation are pending.++Third iPad attempt also failed both methods (Series59.735s, Work95.733s, suite155.468s), make exit2, zero skips/runtime warnings and owned process drain; diagnostic-only cap154s PID96300/PPID95273. The stronger Work edit-button assertion catches the editor remaining open. Actual Save-time UIEvent logs route touches to UIRemoteKeyboardWindow (filtered app-diagnostic-events.txt623/631 and3061/3069). Root and worker viewed Series after-Save frame30s: keyboard gone but draft3/editor still open, no app error. There is no direct handler/save/refusal telemetry; this is not proof that a repository writer ran.++A next bounded test preparation, pending source review, activates the actual enabled Hide keyboard control only when present, with nonempty/full-window checks and a keyboard-gone assertion, then re-resolves Save. This removes the observed keyboard-window interaction before the intended Save rather than repeatedly tapping Save or changing product behavior. All earlier failed artifacts remain preserved; no Core/App source change or phone follow-up has occurred.++Fourth iPad attempt safely stops before Hide/Save because the keyboard control is outside app bounds: both methods failed (Series24.485s, Work59.943s), make exit2, no skips, two structured Calendar/CivilDay Environment warnings. All owned processes drained; diagnostic-only cap135s PID99307/PPID98510. Attribute diagnostics report Hide frame733,1410.5,99×64.5 in keyboard windowContext3642525562/display1, while app frame0,0,834×1210 has context2300960907/display0 (Series21286–21296, Work95814–95824, app95901–95913). No Hide or Save action followed the guard. No further speculative retry is authorized.++Root directs a coherent Core source checkpoint containing the five Core production files, three Core test suites, passing native mock-recorder correction/regression and completed Core tasks. The three UI-harness files remain preserved uncommitted for App integration. Current checkpoint retains original UI sources matching the passed initial phone pair; legacy iPad supplementary checks remain explicitly open. Source review/Core/fast/signed Mac/native results are not restated as complete feature acceptance. App tasks7–14 will own the new copy/offer rendered coverage and final required phone/iPad gates. This is progress on independent reviewed contracts, not a waiver or a claimed green iPad result.++Core checkpoint ad71e6b15959844ae54eb2c417a33f033e9ef9d8 committed exactly11 authorized files (+1,735/−24); no push. Root verified its paths/body and clear index. Native mock fix and all Core contracts are included; three UI-harness files and root docs remain dirty/preserved. The checkpoint explicitly records the open legacy iPad gate and pending App integration/final acceptance.++App task7 initial12-declaration session cohort: first native selection failed before compilation because default Clang/SwiftPM caches were denied (infrastructure-only, zero executions). Identical selection with existing authorized native/cache access exited2 for expected missing WorkRecordCopyModel/concrete mock seams (compile-only red, zero executions), then drained. Task7 marked complete via Rune; task8 green preparation and additional behavioral cases are underway. No new runtime pass is claimed yet. Core checkpoint and its failed legacy iPad artifacts remain intact.++Transit checkpoint update is currently unavailable: a bounded full read returned READ_TIMEOUT; one identical retry hit transport timeout. No checkpoint write or status change was attempted without a confirmed read. The earlier verified task remains last-known in-progress, and this does not block App implementation.++Session green /tmp/asterism-t2439-app-session-green.xcresult exited0 and drained: all19 expected declarations/invocations passed, no failures/skips/runtime warnings,0.109s test duration. Frozen source hashes unchanged. Additional cases cover inspection single-flight, late preview responses/row-review gating, destination-added clash default Skip, planned overlap consent and read-only inspection retry. Source fixes preserve available selections, block concurrent acceptance/inspection, clear stale refusal errors after reviewed refresh and retain unavailable-record/retry notices. Four compiler warnings were in untouched IntentLibraryBrokerTests/AppLibraryModelTests/SettingsImportTests (captured vars/redundant require); none in new model/tests or changed mock. Rune8 complete; App9–14 source preparation continues with no other heavy job queued.++Interim App session critique found no source blocker: late reads/closure, stable planned IDs, single-flight submission/inspection, explicit absent-result retry and clash-consent refresh match the approved contracts. Final caller integration must use loaded/resolved work identity; full App phase review remains pending.++Manual UI task9 red /tmp/asterism-t2439-app-manual-ui-red.xcresult exited2/Xcode65 and drained: exactly one expected declaration/invocation failed at the missing outside-edit Copy action; zero skips, two existing Environment Calendar/CivilDay runtime warnings. No diagnostic cap. The other three drafted manual-copy methods were not selected and are not claimed executed. Rune9 complete; task10 view/factory and isolated App DEBUG fixture are being implemented without Core changes.++Manual-view pre-run review identified two suspension integration blockers before green: resuming a blocked uncertain outcome must retain the original inspection gate, and a late resume refresh must not publish a sheet after host navigation. The worker is adding behavioral regressions and lifetime guards. Destination unavailability also needs the existing Check Library route. No green batch has started on this source state; task10 is not complete.++Task10 source pre-run corrections are complete: suspended uncertain/blocked state retains its original outcome contract; navigation retires an in-flight resumed read and host generations guard late sheet publication; startup applies an offered destination only once. Additional cases cover these paths plus loaded/resolved factory identity. The authorized frozen sequential batch expects25 native declarations/invocations and four manual UI methods per dedicated phone/iPad, stopping after any failed/drain-incomplete job. This is a run plan, not a pass claim.++First task10 native green attempt stopped at compilation (exit2, zero executions): new success-presentation file lacked AsterismCore import. Required import added; failed attempt retained, owned processes drained, same25-case native selection rerun with fresh artifact.++Independent task10 integration critique found two remaining blockers before queued UI: the existing onResolveDuplicate callback routes only a source-Work duplicate set and cannot serve generic Check Library correction for ordinary source records/destination/uncertain copies; preview controls also incorrectly require Keep separate for informational selected-Skip overlap. The worker is directed to add independent correction navigation and prospective actual-clash controls with meaningful rendered coverage, only after draining current native work. No UI green verdict or task10 completion is claimed.++Revised task10 batch source review clears the prospective actual-clash controls and per-stack typed diagnostics route. Navigation-owned RecordCopyReviewHostState preserves a suspended draft only for intentional diagnostics/back across wide host recreation, retires it on source/tab/unrelated route departure and rejects late resume results. Legacy diagnostics callers retain their default stack. Two new rendered methods cover a selected overlapping peer kept Skip and ordinary-source Check Library/resume. Updated expected native selection is118 declarations/123 invocations:25 session,6 navigation/11 parameterized invocations and87 existing AppNavigation cases. UI expects six exact methods on each dedicated phone/iPad; no new result is claimed before exit/reconciliation.++Manual native4 /tmp/asterism-t2439-app-manual-native4.xcresult exited0 and drained:90 declarations/95 invocations passed, zero skips/runtime warnings, frozen source unchanged. Expected118/123 was a file-level overcount: AppNavigationTests.swift contains59 AppNavigationTests declarations and28 separate AppNavigationTodayTests declarations; only the59 suite was selected. All25 copy-session and6 new navigation declarations/11 invocations ran. The disjoint28-case Today suite is owed, not waived, before the six phone/iPad manual methods. Earlier compile-only green3 also lacked AsterismPresentation import in the new copy view; fixed with all failed artifacts preserved. Independent revised task10 critique confirms both correction-route and informational-clash blockers resolved on source review, with no new lifetime/data-safety blocker.++User then authorized fixed Meddy Release installation first, followed by a separate combined Devsterism build of ready PR105/106. T2439 heavy work is paused with owned process inventory empty; task10 remains pending, no queued UI started and unfinished copying is not included in the installation. Source work and all original PR branches remain preserved.++Meddy installed first and released its slot. The separate testing/devsterism-pr105-pr106 checkout frozen atcc16a63a then built and installed successfully with the explicitly authorized Makefile Development target (make exit0, owned jobs drained). Standalone deep/strict signature verification exited0; signed app uses group/iCloud.me.nore.ig.Asterism.dev and embedded extension has no iCloud entitlement. Device inventory confirms both regular Asterism and Devsterism installed. SchemaV20 is byte-identical to remote main; unfinished T2439 is absent from that build. Installation receipt is outside this repository at /Users/arjen/Documents/Codex/2026-10-10/task/asterism-dev-pr105-pr106-preparation.json. No regular Release install, reset/uninstall or merge.++T2439 lane resumes its owed disjoint28 Today navigation cases, then six manual phone and six manual iPad methods; actual source remains frozen and offer drafts stay unapplied. Independent draft critique found a late-save-event admission blocker across awaited editor callbacks/new sessions; worker is adding captured session/generation checks and held-callback regressions in preparation before applying tasks11–14.++The owed Today navigation cohort passed in /tmp/asterism-t2439-app-manual-today-native.xcresult:28 declarations/invocations, make exit0/drained, no skips/runtime/compiler warnings,0.066s. Frozen sources unchanged. Targeted native totals are118 declarations/123 invocations across disjoint90/95 and28/28 runs; not a single combined-run claim.++First six-method manual phone /tmp/asterism-t2439-app-manual-phone.xcresult exited2/Xcode65 and drained:one pass/five failures, zero skips,12 existing Calendar/CivilDay Environment runtime warnings; no diagnostic cap. All five failures stopped at URL-free Work lookup before copy assertions. Ordinary-serial outside-edit action case passed. Actual full AX F7F5FC2B-A338-4834-BF91-1DE4C485757E.txt133 shows work-row identifier and exact Open Work Book one (no trailing space); the old prefix required a trailing space. The test-local correction preserves substantive title/identity checks and scrolls to actual hittability. Root reviewed source+hierarchy; corrected six-case phone2 and conditional same six iPad cases are authorized, frozen, stopping on failure. No product/native/Core delta for this correction and no broad gate rerun.++Phone2 /tmp/asterism-t2439-app-manual-phone2.xcresult exited2/Xcode65 and drained:four passes/two failures, six declarations/invocations, zero skips,12 existing Environment warnings and no diagnostic cap. Cancellation/reopen, ordinary-source Check Library roundtrip, outside-edit action and existing clash-warning flow passed. Mixed copy stopped at a lazy offscreen Harbour row; selected-Skip overlap revealed an actual List-row multi-button bug. Full AX22A6C2F0 shows Place header below viewport with Harbour absent; AX38B49630 shows Ada/Nightjar unselected and Copy0 after Select all.++Selection HStack and preview-row actions now use existing borderless button style so every action owns its tap; the mixed test scrolls to Harbour through the existing helper. The overlap test retains exact both-selected assertions; repeat-copy retains its warning/acceptance assertions and adds independent Skip with no alert/zero creations. Root source reviewed the bounded correction. Next affected phone selection is three exact methods (Mixed, InformationalOverlap, Repeat), then all six iPad methods only after pass/drain. Runtime outcomes remain pending; first failures are preserved and no full UI development gate was run.++Unapplied offer drafts have also corrected late event admission with captured save identity/generation and retired/deferred queue handling. Early source critique found and resolved visible-offer replacement; canceled queued IDs now retire with the host. These drafts and their behavioral tests are still uncompiled/unapplied until task10 rendered verification completes.++Phone3 targeted correction run /tmp/asterism-t2439-app-manual-phone3.xcresult exited2/drained:three expected methods/two passed (selected-Skip overlap and Repeat including independent Skip), one Mixed note assertion failed, zero skips, six existing Environment warnings; no cap. The selected-Skip case verifies both source selections and Copy1 without Keep separate. The Mixed note query was scoped too broadly and could target source text rather than actual preview; actual preview-note Text now has kind/UUID leaf identifier and exact payload assertion after bounded read-only reveal.++Phone4 /tmp/asterism-t2439-app-manual-phone4.xcresult exited2/drained:one expected method failed before notes because Ada label was queried after scrolling it out of the lazy list; two existing warnings, zero skips. Owned completed diagnostic collector38699/PPID37965 was TERM-capped at157s, with exact result/dedicated-phone linkage recorded; no runner/build/system service was terminated. Full AXE844A40C shows Copy2 and Harbour selected while Ada is absent above viewport, proving the two-record plan remained intact. Assertions now read Ada before scrolling, Harbour after its tap, wait for enabled Copy2, verify notes switch0→1 and actual preview-note payload. Read-only reveal asserts existence/hittability. Root reviewed this test-only correction; one Mixed phone5 then six iPad methods are authorized, frozen and pending results.++## T-2439 takeover evidence (2026-10-12)++Verified c17004ce and all seven existing commits; all uncommitted app source/test changes preserved. Prior process inventory drained before commands. Series-offer preparation in /tmp was applied only after all ten original files matched byte-for-byte, with backups at /tmp/asterism-t2439-takeover-backup. Core manifest source SHA256 matches all five production files; existing unfiltered Core3295/308 pass is exact-source evidence, not a new execution. Native full1671/1714 is historical and does not cover new app sources.++First native offer/copy/navigation run executed61 declarations and failed one leave-series case; original /tmp/asterism-t2439-takeover-offer-native.log and .xcresult preserved. Confirmed membership receipt now advances only the membership baseline during partial editor saves. Delayed offers re-read before presentation and reject retired generations. Second native selection passed62 declarations across5 suites; /tmp/asterism-t2439-takeover-offer-native2.log and .xcresult. Review then found confirmed nil membership fallback; corrected by checking basis presence and adding leave/refusal/rejoin regression, awaiting next native execution.++Required four pre-push skill reviewers found no reuse blocker; efficiency suggestions are nonblocking and unmeasured. Spec reviewer identified delayed presentation issue, now fixed and regression-tested; review of the nil membership fix remains pending. Transit dedupe/full-read/revision-guarded in-progress checkpoint update committed, receipt /tmp/t2439-takeover-transit-update.json. No feature PR existed at takeover. Current phone12 journey run and source snapshot preserved at /tmp/asterism-t2439-takeover-copy-offer-phone*; verdict pending. No installed product or PR105/106 changed.++## Implementation explanation++### Beginner++Choose Copy characters and places on a saved work, choose a related destination and select the names to reuse. Nothing is selected or saved automatically. Notes are optional; quoted facts stay with their original work. Matching names begin at Skip; Keep separate explicitly creates another independent record. A series Save can suggest reviewing the nearest earlier book, while declining keeps the series membership.++### Intermediate++Immutable Core projections carry eligibility, selected payload, matching surfaces and planned destination UUIDs. One locked mixed-kind repository transaction revalidates that basis before inserting ordinary destination records. The app owns value drafts and one presentation flow. Two interactive editor receipt variants report actual under-lock membership transitions; one save-scoped coordinator produces a single batch offer only after terminal editor success. Nearest-position ties remain explicit source choices.++### Expert++Whole-ID sibling reads reject torn ownership/key identity even when work-scoped fetches look coherent. Copies derive fresh name keys, carry only explicit aliases/optional notes, exclude facts/coverage/suppressions and preserve existing metadata. Refusals and save failures roll back/refault. Uncertain responses inspect exact planned kind/UUID/payload and block blind retries; absence requires conscious retry because another device may have deleted a committed copy. Partial editor saves advance only confirmed membership conflict evidence, including nil; stale host generations cannot publish late offers or resumed drafts. Presentation re-reads saved order/membership, and explicit source confirmation then enters the ordinary copy gates. No new persisted history/schema or cross-device exactly-once promise.++### Completeness assessment++Core contracts and both app entry points are implemented and source-reviewed. The corrected full native gate passed1734 declarations/1790 invocations and the signed Mac build. Current-input Core3870 declarations passed. All13 feature UI methods have passing targeted phone/iPad evidence across recorded selections. Full phone/iPad acceptance remains pending; no green final UI acceptance claim is made by this explanation. Physical-device, live CloudKit delivery and unhosted Mac rendering are outside the authorised simulator verification.++Final native gate /tmp/asterism-t2439-takeover-native-final.log and .xcresult exited0/drained: signed Mac build passed; all1734 declarations/1790 invocations across123 suites passed, zero failures/skips/runtime warnings. Structured tree has28 parameterized declarations/84 argument nodes; converted executed-leaf JUnit is /tmp/t2439-review-inputs/native-final.xml. Leave/refusal/rejoin regression passed. Source hashes frozen in /tmp/asterism-t2439-takeover-final-source.json; subsequent difference is only the UI retained-record test correction. Phone2 uses13 methods; batch review-one/cancel and series-prefill/no-selection checks passed so far, final verdict pending.++Phone2 exited2 and drained:13 declarations/invocations,12passed/1failed, zero skips,24 existing Environment Calendar/CivilDay runtime warnings. All six manual methods passed, including notes activation/preview, mixed copy and ordinary destination correction. Batch-decline failed only at its direct offscreen Reader assertion. That test now scrolls into the ordinary record editor and asserts its exact name; /tmp/asterism-t2439-takeover-batch-phone.xcresult reports1/1pass, zero skips and TEST SUCCEEDED. Monitoring wrapper exited1 after test completion on a ps header conversion; actual make exit was not captured, and this infrastructure failure is preserved in its receipt. Fresh ps found no active build/test/diagnose processes; parser corrected. Earlier failures are unchanged.++Core source-backed guards enumerate app files, so an unfiltered current-input package gate is running rather than treating previous Core production hashes alone as full acceptance evidence. Official fixed fast cohort has no such changed app-file input; earlier456-identifier pass remains scoped evidence. iPad targeted and broad UI gates remain owed.++Current-input unfiltered package gate /tmp/asterism-t2439-takeover-core-final.log exited0/drained after205.38s:42+304+229+3295=3870 declarations across349 suites, no compiler warnings. Existing opt-in performance skips retain their original scope; all new copy/offer store contracts pass.++First thirteen-method iPad run /tmp/asterism-t2439-takeover-copy-offer-ipad.xcresult exited2/drained:11passed/2failed, zero skips,22 existing Calendar/CivilDay runtime warnings. All six manual-copy methods passed, including mixed notes/correction and retained resolution draft. Batch review's action was absent from the visible lazy list after choosing a destination (actual AX preserved); series reopen tried selecting Library rather than using its existing index after Back. Test-only corrections add bounded scrolling for Review and an explicit series-index return assertion; two-method follow-up is running. Production and native-test sources remain unchanged since their final gates.++Two-method iPad follow-up /tmp/asterism-t2439-takeover-offer-ipad2.xcresult exited0/drained:2passed/0failed/0skips. Its owned post-test diagnostic collector was capped after150s; original receipt preserves exact PID63927/parent62894 and command. No test or assertion was skipped. All13 feature methods now have passing targeted phone/iPad evidence across recorded selections, not a claimed single green13-method run. Production source unchanged since signed Mac/full-native and current-input unfiltered Core gates.++User then requested the lane for a separate PR105 phone install and old-owner PR106 work. Current bounded batch fully drained; fresh ps had no active owned build/test/diagnose commands. Heavy lane released with no queued T2439 jobs at /tmp/asterism-t2439-heavy-lane.json. Source/review continues; no new heavy batch until install handoff completes. T2439 full phone/iPad UI acceptance and remote draft PR remain owed. Installed combined Devsterism and original PR branches are untouched.++## Final phone acceptance interrupted for user install priority++The resumed unfiltered make test-ui command used unchanged5f1eae6c source, a dedicated phone and fresh /tmp/asterism-t2439-final-full-phone.xcresult. No extra selection/skip flags were added. User then requested prompt interruption to prioritise tonight's fixed PR105 reinstall rather than wait through the full suite. Only the verified owned xcodebuild PID2491 (parent2490/group2488) received SIGINT. Its children drained; fresh ps showed no owned build/test/diagnose commands. Make exited2 after interruption (xcodebuild Error75); this is an interrupted acceptance attempt, not a product-failure full-suite verdict.++Before interruption,35 execution instances completed:34passed and1observed accessibility failure, representing32 distinct source declarations (launch configuration repeats included). The observed failure was AccessibilityJourneyUITests/testTheSeriesAndLinkControlsStayReachableAtLargestDynamicType at UIJourneySupport.swift:479, unable to reach All Works from Library, before any copying flow. Keep that failure unchanged; one targeted retry is owed when authorised. The next ChapterNotes spine case was interrupted, not classified as a product failure.195 expected phone declarations remain; their exact identifiers and completed identities are saved in /tmp/t2439-phone-interruption.json. Do not repeat completed methods merely to replace the interrupted verdict. Full iPad acceptance30 declarations is still owed.++Lane released for fixed PR105 reinstall with no queued T2439 jobs; current ownership receipt /tmp/t2439-current-lane-ownership.json. No next heavy batch before install handoff. Source remains committed and reviewed; no source/approval claim is weakened by this user-directed interruption. Draft PR/push/remote-head verification remain pending.++Raw interrupted xcresult summary is preserved separately: resultFailed,33 distinct test entries,31passed/2failed/0skipped. One failed entry is the observed accessibility All Works failure; the other is the user-interrupted active spine case. Completed log instances remain35=34passed/1observed failure because launch variants repeat. Do not equate raw Failed with two product regressions, or erase the raw verdict.+++## Final qualified acceptance and draft PR (2026-10-12)++Production/source-test hashes remain identical to the reviewed 5f1eae6c checkpoint. Original commits and all earlier failure verdicts remain preserved. PR107 was created as a draft and verified against local HEAD and `git ls-remote`; no main push, merge, device installation, live-data reset or permission change occurred. PR105/106 source was not edited.++The user-authorized isolated phone/iPad runs used distinct destinations and DerivedData. Concrete host pressure prompted PR106's owner to drain its own commands; T2439's iPad had already completed, leaving one T2439 phone runner. No unrelated process or shared service was stopped. One bounded process inventory found 3,144 processes, with WindowServer/Time Machine and the current executing app among leading CPU users; no abandoned T2439 worker was verified. These identify contributors, not a sole cause.++| Scope | Actual outcome | Evidence |+| --- | --- | --- |+| Full iPad `make test-ui-ipad` | Exit 0; all 30 expected identities passed, zero skips/missing/extra; 14 Calendar/CivilDay environment warnings | `/tmp/asterism-t2439-final-full-ipad.xcresult`, `/tmp/t2439-final-ipad-verified.json` |+| Original full phone attempt | User-interrupted; 35 completed execution instances / 32 unique declarations, 34 passed and one accessibility failure; raw Failed bundle also contains the canceled active case | `/tmp/asterism-t2439-final-full-phone.xcresult`, `/tmp/t2439-phone-interruption.json` |+| Exact remaining 195-case continuation | Watchdog at 9,002.6 seconds; child exit -15; 186 completed raw XCTest verdicts: 183 passed, one alias-chip failure, two opt-in M4 skips; all 13 T2439 journeys passed | `/tmp/asterism-t2439-final-phone-remainder.log`, corresponding receipt and staging `.xcresult` |+| Final exact tail plus single failure retries | Make exit 2, no watchdog timeout; all 11 expected identities executed: 10 passed, one alias-chip failure; all nine carried-over identities passed; accessibility retry passed | `/tmp/asterism-t2439-final-phone-tail-retry.xcresult`, corresponding receipt |++The timed-out continuation's xcresult is unfinalized: `Info.plist` is absent and xcresulttool cannot read it. Its completed results are raw-log evidence, not a fabricated structured/full-suite verdict. The staging bundle and error receipt are retained. Test identities reconcile without missing/extra cases: original 32 + continuation 186 + final nine = 227; two failure retries are separately counted. Existing M4 skips are not executed passes. Post-test diagnostic collectors in completed iPad/tail jobs exceeded 150 seconds and received an exact owned-process TERM cap after tests completed; their commands then finalized and drained.++Remaining acceptance issue: `CharacterExtractionUITests/testACitationInTheFactGutterOpensTheCitedNote` repeats at line 587, “The kept alias is a chip beside the name”, before citation navigation or copying. This existing journey is outside the T2439 interface; no baseline comparison establishes its origin. Under the user's bounded policy it received one targeted retry, then was flagged without unrelated source/test edits or further attempts. The final tail contains 18 Calendar/CivilDay environment warnings. The earlier accessibility failure remains recorded even though its single retry passed. Neither retries nor combined scopes erase the original failures or create a green full-phone verdict.++At resource release (15:22 UTC), exact final xcodebuild/diagnostic PIDs were absent and both owned simulators were Shutdown. No tests remain queued. The bounded pressure sample reported 46% free memory, 24,674.56 MiB swap used and load 316.40 / 415.78 / 467.48: improved from initial readings but still high. PR106's owner received the actual release and evidence paths. The final review keeps a needs-changes severity for acceptance, while the feature remains source-reviewed and available in a qualified draft.+++## PR107 pr-pilot review refresh (2026-10-13)++User tested the optimized installed42b source and requested pr-pilot plus a separate UI/UX follow-up. Idea T2451 (5178E640-2B61-4E20-924B-B4E808D53C8C) was deduplicated, created and freshly verified in Asterism. Specific pain points remain unspecified; no redesign requirements were invented. No newer physical install or merge was performed.++The current local-review agent posted its single-pass review at https://github.com/ArjenSchwarz/asterism/pull/107#issuecomment-6140958400. It found no approved-spec functional blocker, but identified a lost optional-offer-read explanation, unnecessary destination/later-series-member record reads, and Voice Control action labels missing their visible title. The coordinator now retains a nonblocking read notice across empty/partial offers and event retirement, renders it in Work/Series hosts and the offer sheet, and clears it with a new event or host cancellation. Two new regressions cover failed and partial reads without copying anything. Record counting excludes destination/same-position/later members while preserving all ordering evidence, ties and unavailable-peer rules. Selection rows carry the selected trait; choice labels include the visible action title.++Rebased all14 prior commits onto origin/main fba443e9 (merged PR105); the sole conflict was specs/OVERVIEW.md and both existing main sections were preserved. The installed source is retained at refs/backup/t2439-before-pr-pilot-main-20261013. An inherited main PlatformSeam failure was fixed by relocating the unchanged cover-drop adapter body into existing Support/PlatformModifiers.swift, without widening the seam allowlist or changing assertions. Body SHA256 before/after: 0d159a0ecc4277c66fbf3f018747568b5678f9723fa5ceb941c9c99f4a6d8d52. No cover behaviour changed.++| Refreshed scope | Actual outcome | Evidence |+| --- | --- | --- |+| Unfiltered serial Core | Exit0; 3875 JUnit declarations, zero failures,55 existing opt-in skips | /tmp/pr107-pr-pilot/core-swift-testing.xml, core-receipt.json |+| Official fast identifier cohort within Core | All456 exact manifest identifiers passed; no missing/unexpected cohort declarations; no separate redundant fast execution | /tmp/pr107-pr-pilot/fast-cohort-reconciliation.json |+| Signed Mac app/embedded extension + full native | Exit0;1756 declarations/1832 invocations, zero failures/skips/structured runtime warnings; two new coordinator regressions passed | /tmp/pr107-pr-pilot/native.xcresult, native-receipt.json |+| Initial focused phone | Exit2;17/17 expected identities executed,15passed/2failed, zero skips;32 existing Calendar/CivilDay environment warnings | /tmp/pr107-pr-pilot/focused-phone.xcresult |+| Exact two-case phone correction | Exit0;2/2passed, zero skips/missing/extra;4 Calendar/CivilDay environment warnings | /tmp/pr107-pr-pilot/focused-phone-retry.xcresult |+| Focused iPad | Exit0;5/5 expected identities passed, zero skips/missing/extra | /tmp/pr107-pr-pilot/focused-ipad.xcresult |++The initial two phone failures were exact selectors still expecting Copy Ada/Skip Ada after the reviewed accessibility labels became Copy this record, Ada/Skip this record, Ada. Corrected only those two selector strings; every original clash, selection, payload and warning assertion remains intact. The original failed result is not rewritten as a green17-method run. All17 selected identities have passing evidence across the15 original successes and two corrected reruns. iPad verifies mixed notes/correction, series-join presentation, batch decline and both choice actions. Frozen-source receipts confirm no source changes during each run. Product/native/Core inputs remain identical to their full passing gates after the UI-only selector correction. No broad gate was repeated.++Core and native compiler warnings are recorded, not hidden: six distinct Core source-warning categories and17 native warning occurrences came from files byte-identical to installed42b; metadata/sysroot diagnostics are retained in the logs. No warning originates in the reviewed delta. Signed Development app/extension identities and isolated dev App Group were verified; nothing was launched or installed on a physical device.++Reuse, quality, efficiency and spec reviewers found no delta blocker; a further quality review confirmed the exact selector correction and assertion preservation. All historical full-phone failures, retries, two M4 skips, interruptions and unfinalised watchdog evidence remain preserved. This refresh does not establish a green unfiltered full-phone acceptance gate. PR107 remains draft pending final review; T2439 is not Done. Current source review and remote verification are linked in the PR overview. Transit full reads intermittently returned READ_TIMEOUT before mutation; any unconfirmed checkpoint update remains explicit.++The design remains independent copies and an optional series-save offer. Readers get an explanation if the optional offer cannot be read; successful membership saves stay successful. Availability counting avoids future books without changing predecessor choice. The app retains event-scoped presentation and uncertainty handling, while no persisted history, schema or merge semantics are added.
diff --git a/specs/copy-work-records/requirements-review.md b/specs/copy-work-records/requirements-review.mdnew file mode 100644index 00000000..6fe11d6c--- /dev/null+++ b/specs/copy-work-records/requirements-review.md@@ -0,0 +1,101 @@+# Asterism — copy work records: approved requirements checkpoint++The user approved all three product defaults on 12 October 2026: names/explicit aliases with a fresh matching key and optional notes off; Skip or explicit Keep separate without merge/update; direct links of any type or complete shared-series identity, excluding transitive links. Independent destination copies remain the agreed direction.++The user then requested an offer after saving a work into a series. Requirement 5 captures that request; ordering, batch and repeated-offer recommendations are part of the next design checkpoint. This file records requirements approval and does not authorize copying implementation. See design-review.md for the current approval question.++Transit creation remains blocked: the bounded retry again returned READ_TIMEOUT. No ticket has been created.++---++# Copy characters and places between works++Status: Requirements 1–4 and their three product defaults approved by the user on 2026-10-12. Requirement 5 records the requested post-series-add offer; its edge-case recommendations await design review. Specification only; no implementation authorization for copying.++Readers can copy selected characters, places, or both from one work to a related work or another member of its series. Copies belong to the destination and can be edited independently. A preview exposes name clashes before anything is written.++## Definitions and boundaries++A record is one logical character or place, identified by kind and application UUID; synchronized rows of that UUID are not separate choices. A related work is a directly linked work in either direction, irrespective of the free-text link type. A series peer shares the same complete series-membership UUID, not merely its displayed series name; a missing series-directory row does not negate matching complete membership. The eligibility boundary, payload and clash policy are approved.++The initial copy payload is the displayed name and explicit aliases. A copy starts its matching key from its displayed name, like a manually created record; the source retained key is not transferred as a hidden historical name. A session-level **Include record notes** option is off initially. Extracted facts, their source quotes/citations, extraction coverage and suppression decisions are excluded. These are work-scoped evidence, not portable identity metadata. The preview states exactly what is included and excluded.++## 1. Choose destination and records++As a reader, I want to choose a related destination and the records to copy, so that I can reuse a cast or setting without retyping it.++1. <a name="1.1"></a>WHEN the reader starts copying from a saved work, the system SHALL offer other locally available works that have a direct related-work link to it or share its complete series membership.+2. <a name="1.2"></a>The system SHALL exclude the source itself, distinguish destinations with the same title using existing work-picker context, and identify whether each destination is linked, a series peer, or both.+3. <a name="1.3"></a>WHEN there are no eligible destinations, the system SHALL explain that a relationship or series membership must be saved first; it SHALL NOT create one as a side effect of copying.+4. <a name="1.4"></a>The system SHALL let the reader select characters, places, or both, with individual selection and select-all/clear-selection controls per kind; no record SHALL be selected initially.+5. <a name="1.5"></a>The system SHALL present each logical record once, with name, kind and available aliases/record-note preview; torn records SHALL be visibly unavailable until resolved through the existing resolution flow.+6. <a name="1.6"></a>WHERE a work or destination is missing, torn, or unavailable for writes, the system SHALL prevent copying and preserve the reader's current selection.++## 2. Independent content and evidence++As a reader, I want the new work to own its copies, so that editing a sequel's character does not alter the earlier book.++1. <a name="2.1"></a>WHEN copying succeeds, the destination SHALL gain independent records of the selected kinds with the previewed names and aliases; editing or deleting either copy SHALL NOT alter the other work's records.+2. <a name="2.2"></a>The preview SHALL default to names and explicit aliases, disclose that earlier names are included only when listed as aliases, offer a single optional inclusion of the selected records' free-text notes, and display those notes before accepting their inclusion.+3. <a name="2.3"></a>The system SHALL exclude extracted facts, evidence quotes, source references, extraction coverage and suppression decisions; it SHALL state that these are not copied and SHALL NOT misrepresent source-work evidence as evidence from the destination.+4. <a name="2.4"></a>Copying SHALL NOT transfer entries, generic work notes, ratings, reading progress, URLs, covers, creators, work types, relationship links or series positions.+5. <a name="2.5"></a>After creation, copies SHALL participate in the existing destination record editor, extraction matching, duplicate resolution, deletion and backup round-trip behavior; source changes SHALL NOT propagate into copies.++## 3. Preview and name clashes++As a reader, I want to inspect clashes before copying, so that a similar name never silently overwrites another character or place.++1. <a name="3.1"></a>Before accepting a copy, the system SHALL show the destination, selected records, content-inclusion choice and planned result for every selected record; acceptance SHALL be disabled with no planned creations.+2. <a name="3.2"></a>WHEN a selected record has a planned name/alias matching key overlapping a displayed name, retained matching key or alias of a same-kind destination record, or another selected record, the preview SHALL show every affected record and the overlapping names.+3. <a name="3.3"></a>WHEN a possible clash exists, the system SHALL default that selection to Skip; WHEN planned creations overlap each other or existing destination records, the system SHALL require explicit Keep separate confirmation before creating those records; copying SHALL NOT merge, overwrite or delete an existing record. The confirmation SHALL warn that future extracted facts can route to either same-name record according to existing matching rules. The preview SHALL retain possible overlap information for skipped selected records but SHALL require acknowledgement only for overlaps involving planned creations and existing destination records.+4. <a name="3.4"></a>Characters and places SHALL remain separate namespaces; the same spelling across kinds SHALL NOT block copying or change either kind.+5. <a name="3.5"></a>WHEN the reader repeats a copy, existing copies SHALL appear as possible name clashes; the system SHALL NOT silently create another identical record. The reader MAY explicitly keep a separate record.+6. <a name="3.6"></a>WHEN the source copied content or ownership/key consistency, selected record set, destination matching names, relationship eligibility or write availability changes after preview, acceptance SHALL write nothing and request a refreshed preview while preserving selections that remain available.++## 4. Commit, cancellation and feedback++As a reader, I want one explicit acceptance step, so that a cancelled or failed copy never leaves a partial cast in another work.++1. <a name="4.1"></a>Opening the copy flow, selecting records, changing inclusion choices and previewing SHALL NOT write library data; cancelling SHALL leave both works unchanged.+2. <a name="4.2"></a>WHEN the reader accepts the preview, either all planned character and place copies SHALL commit or none SHALL commit; a confirmed failure SHALL retain the draft and display an actionable error. IF the response is unconfirmed, the system SHALL state that it is checking whether copying completed and block another acceptance until that check finishes.+3. <a name="4.3"></a>While acceptance is pending, the system SHALL prevent a second acceptance; a successful response SHALL identify the destination and created/skipped counts and offer navigation to the destination.+4. <a name="4.4"></a>The system SHALL leave source records, both works' existing metadata, links and series membership unchanged; removing the relationship later SHALL NOT delete existing copies.+5. <a name="4.5"></a>On phone, iPad and Mac, selection and preview controls SHALL follow existing record-editor and work-picker patterns, expose record kind and selection to accessibility, and support keyboard selection/acceptance where the platform supports it.++## Acceptance examples++| Example | Observable result |+| --- | --- |+| Book 1 and URL-free Book 2 share a series; choose two characters and one place | Preview identifies Book 2, notes off and facts excluded; one acceptance creates exactly three independent records. |+| Works have a direct link typed “alternate universe” but no series | Destination is offered in either direction; arbitrary type text does not determine eligibility. |+| A links B and B links C, but A does not link C | C is not offered unless A and C also share a complete series membership. |+| Two different series both named “Books” | Matching names do not make their members eligible. |+| Source “The Queen” aliases “Her Majesty”; destination “Queen” or alias “Her Majesty” | Preview shows clash using existing normalization; Skip initially, explicit Keep separate makes a new independent record. |+| Source has retained key “bob”, renamed “Robert”, alias “Bobby” | Copy carries Robert/Bobby; its new matching key is Robert, so hidden Bob routing is not transferred. Destination Bob alone is not a clash; explicit Bobby is. |+| Character “London” and place “London” | Both can copy; no cross-kind clash. |+| Two same-kind selected records share an alias | Batch-internal clash is shown before acceptance; if one stays Skip, copying the other alone requires no Keep separate acknowledgement unless the destination also overlaps. |+| Source has cited facts and a free-text note | Names/aliases copy; note copies only when included; facts/citations/quotes never claim destination evidence. |+| Save fails after preparing a character and a place | Neither appears after reopening the repository; draft remains retryable. |+| Selected copied content changes or destination gains a matching alias while preview is open | Old acceptance writes nothing; refreshed preview exposes the new content/clash. |+| Repeat copy, cancel preview, or delete the relationship after success | Repeat needs clash handling; cancel writes nothing; removing link preserves copies. |++## Non-goals++Shared global character/place identity, ongoing synchronization between works, moves, automatic record merging, entry/fact transfer, transitive relationship traversal, bulk copying to multiple destinations, creating relationships inside this flow, a persistent copy-history table, import/export format changes, and share-extension copy UI are out of scope. The manual note chips enhancement is a separate feature.++## 5. Offer after adding a work to a series++As a reader, I want an offer to copy records after adding a work to a series, so that the preceding book's cast and setting are available without a separate search.++1. <a name="5.1"></a>WHEN a reader saves a work joining a series through the work editor or series editor, the system SHALL offer to review copying from the preceding work after the editor successfully finishes; it SHALL NOT copy records automatically.+2. <a name="5.2"></a>The system SHALL determine the predecessor from saved series positions, not creation dates or title tie-break order. WHEN the nearest strictly lower position contains multiple predecessor candidates, the system SHALL ask the reader to choose among available candidates at that position rather than infer one from a display tie-break; it SHALL NOT silently skip an unavailable predecessor for an older work.+3. <a name="5.3"></a>WHEN the destination is first in the series or there is no available eligible character/place record in the predecessor choices, the system SHALL omit the offer.+4. <a name="5.4"></a>Accepting an offer SHALL open the ordinary selection/preview flow with source and destination prefilled and no selected records; declining or cancelling SHALL leave the saved series membership intact and copy nothing.+5. <a name="5.5"></a>The system SHALL offer at most once for each successful series-joining save event; reloading, reopening, unrelated edits, position-only edits and sync/import arrivals SHALL NOT repeat it. A later saved leave/rejoin or move into another series MAY produce a new offer.+6. <a name="5.6"></a>WHEN one series save adds multiple works, the system SHALL present one offer containing eligible additions rather than a sequence of prompts, and let the reader choose which destination to review.++Additional acceptance examples: joining at position 3 after positions 1 and 2 offers position 2 even if position 1 was created later; joining at position 1 omits the offer; tied nearest preceding positions require a source choice; declining then editing notes produces no repeat; a batch addition produces one combined offer; failed/cancelled saves and CloudKit/import arrival produce none.++## Design decisions awaiting approval++The approved defaults are names/explicit aliases with fresh name-derived keys, optional record notes off, no extracted facts; Skip/explicit Keep separate without merging; and any direct link/shared complete-series UUID eligibility. New offer edge cases are reviewed in design: source choice for tied positions, one combined batch offer, and save-event-scoped suppression rather than persisted history. Does the design look good?
diff --git a/specs/copy-work-records/requirements.md b/specs/copy-work-records/requirements.mdnew file mode 100644index 00000000..bc73496d--- /dev/null+++ b/specs/copy-work-records/requirements.md@@ -0,0 +1,91 @@+# Copy characters and places between works++Status: Requirements 1–4 and their three product defaults approved by the user on 2026-10-12. Requirement 5 and its offer defaults were approved with the design on 2026-10-12. The user explicitly authorized task planning and implementation.++Readers can copy selected characters, places, or both from one work to a related work or another member of its series. Copies belong to the destination and can be edited independently. A preview exposes name clashes before anything is written.++## Definitions and boundaries++A record is one logical character or place, identified by kind and application UUID; synchronized rows of that UUID are not separate choices. A related work is a directly linked work in either direction, irrespective of the free-text link type. A series peer shares the same complete series-membership UUID, not merely its displayed series name; a missing series-directory row does not negate matching complete membership. The eligibility boundary, payload and clash policy are approved.++The initial copy payload is the displayed name and explicit aliases. A copy starts its matching key from its displayed name, like a manually created record; the source retained key is not transferred as a hidden historical name. A session-level **Include record notes** option is off initially. Extracted facts, their source quotes/citations, extraction coverage and suppression decisions are excluded. These are work-scoped evidence, not portable identity metadata. The preview states exactly what is included and excluded.++## 1. Choose destination and records++As a reader, I want to choose a related destination and the records to copy, so that I can reuse a cast or setting without retyping it.++1. <a name="1.1"></a>WHEN the reader starts copying from a saved work, the system SHALL offer other locally available works that have a direct related-work link to it or share its complete series membership.+2. <a name="1.2"></a>The system SHALL exclude the source itself, distinguish destinations with the same title using existing work-picker context, and identify whether each destination is linked, a series peer, or both.+3. <a name="1.3"></a>WHEN there are no eligible destinations, the system SHALL explain that a relationship or series membership must be saved first; it SHALL NOT create one as a side effect of copying.+4. <a name="1.4"></a>The system SHALL let the reader select characters, places, or both, with individual selection and select-all/clear-selection controls per kind; no record SHALL be selected initially.+5. <a name="1.5"></a>The system SHALL present each logical record once, with name, kind and available aliases/record-note preview; torn records SHALL be visibly unavailable until resolved through the existing resolution flow.+6. <a name="1.6"></a>WHERE a work or destination is missing, torn, or unavailable for writes, the system SHALL prevent copying and preserve the reader's current selection.++## 2. Independent content and evidence++As a reader, I want the new work to own its copies, so that editing a sequel's character does not alter the earlier book.++1. <a name="2.1"></a>WHEN copying succeeds, the destination SHALL gain independent records of the selected kinds with the previewed names and aliases; editing or deleting either copy SHALL NOT alter the other work's records.+2. <a name="2.2"></a>The preview SHALL default to names and explicit aliases, disclose that earlier names are included only when listed as aliases, offer a single optional inclusion of the selected records' free-text notes, and display those notes before accepting their inclusion.+3. <a name="2.3"></a>The system SHALL exclude extracted facts, evidence quotes, source references, extraction coverage and suppression decisions; it SHALL state that these are not copied and SHALL NOT misrepresent source-work evidence as evidence from the destination.+4. <a name="2.4"></a>Copying SHALL NOT transfer entries, generic work notes, ratings, reading progress, URLs, covers, creators, work types, relationship links or series positions.+5. <a name="2.5"></a>After creation, copies SHALL participate in the existing destination record editor, extraction matching, duplicate resolution, deletion and backup round-trip behavior; source changes SHALL NOT propagate into copies.++## 3. Preview and name clashes++As a reader, I want to inspect clashes before copying, so that a similar name never silently overwrites another character or place.++1. <a name="3.1"></a>Before accepting a copy, the system SHALL show the destination, selected records, content-inclusion choice and planned result for every selected record; acceptance SHALL be disabled with no planned creations.+2. <a name="3.2"></a>WHEN a selected record has a planned name/alias matching key overlapping a displayed name, retained matching key or alias of a same-kind destination record, or another selected record, the preview SHALL show every affected record and the overlapping names.+3. <a name="3.3"></a>WHEN a possible clash exists, the system SHALL default that selection to Skip; WHEN planned creations overlap each other or existing destination records, the system SHALL require explicit Keep separate confirmation before creating those records; copying SHALL NOT merge, overwrite or delete an existing record. The confirmation SHALL warn that future extracted facts can route to either same-name record according to existing matching rules. The preview SHALL retain possible overlap information for skipped selected records but SHALL require acknowledgement only for overlaps involving planned creations and existing destination records.+4. <a name="3.4"></a>Characters and places SHALL remain separate namespaces; the same spelling across kinds SHALL NOT block copying or change either kind.+5. <a name="3.5"></a>WHEN the reader repeats a copy, existing copies SHALL appear as possible name clashes; the system SHALL NOT silently create another identical record. The reader MAY explicitly keep a separate record.+6. <a name="3.6"></a>WHEN the source copied content or ownership/key consistency, selected record set, destination matching names, relationship eligibility or write availability changes after preview, acceptance SHALL write nothing and request a refreshed preview while preserving selections that remain available.++## 4. Commit, cancellation and feedback++As a reader, I want one explicit acceptance step, so that a cancelled or failed copy never leaves a partial cast in another work.++1. <a name="4.1"></a>Opening the copy flow, selecting records, changing inclusion choices and previewing SHALL NOT write library data; cancelling SHALL leave both works unchanged.+2. <a name="4.2"></a>WHEN the reader accepts the preview, either all planned character and place copies SHALL commit or none SHALL commit; a confirmed failure SHALL retain the draft and display an actionable error. IF the response is unconfirmed, the system SHALL state that it is checking whether copying completed and block another acceptance until that check finishes.+3. <a name="4.3"></a>While acceptance is pending, the system SHALL prevent a second acceptance; a successful response SHALL identify the destination and created/skipped counts and offer navigation to the destination.+4. <a name="4.4"></a>The system SHALL leave source records, both works' existing metadata, links and series membership unchanged; removing the relationship later SHALL NOT delete existing copies.+5. <a name="4.5"></a>On phone, iPad and Mac, selection and preview controls SHALL follow existing record-editor and work-picker patterns, expose record kind and selection to accessibility, and support keyboard selection/acceptance where the platform supports it.++## Acceptance examples++| Example | Observable result |+| --- | --- |+| Book 1 and URL-free Book 2 share a series; choose two characters and one place | Preview identifies Book 2, notes off and facts excluded; one acceptance creates exactly three independent records. |+| Works have a direct link typed “alternate universe” but no series | Destination is offered in either direction; arbitrary type text does not determine eligibility. |+| A links B and B links C, but A does not link C | C is not offered unless A and C also share a complete series membership. |+| Two different series both named “Books” | Matching names do not make their members eligible. |+| Source “The Queen” aliases “Her Majesty”; destination “Queen” or alias “Her Majesty” | Preview shows clash using existing normalization; Skip initially, explicit Keep separate makes a new independent record. |+| Source has retained key “bob”, renamed “Robert”, alias “Bobby” | Copy carries Robert/Bobby; its new matching key is Robert, so hidden Bob routing is not transferred. Destination Bob alone is not a clash; explicit Bobby is. |+| Character “London” and place “London” | Both can copy; no cross-kind clash. |+| Two same-kind selected records share an alias | Batch-internal clash is shown before acceptance; if one stays Skip, copying the other alone requires no Keep separate acknowledgement unless the destination also overlaps. |+| Source has cited facts and a free-text note | Names/aliases copy; note copies only when included; facts/citations/quotes never claim destination evidence. |+| Save fails after preparing a character and a place | Neither appears after reopening the repository; draft remains retryable. |+| Selected copied content changes or destination gains a matching alias while preview is open | Old acceptance writes nothing; refreshed preview exposes the new content/clash. |+| Repeat copy, cancel preview, or delete the relationship after success | Repeat needs clash handling; cancel writes nothing; removing link preserves copies. |++## Non-goals++Shared global character/place identity, ongoing synchronization between works, moves, automatic record merging, entry/fact transfer, transitive relationship traversal, bulk copying to multiple destinations, creating relationships inside this flow, a persistent copy-history table, import/export format changes, and share-extension copy UI are out of scope. The manual note chips enhancement is a separate feature.++## 5. Offer after adding a work to a series++As a reader, I want an offer to copy records after adding a work to a series, so that the preceding book's cast and setting are available without a separate search.++1. <a name="5.1"></a>WHEN a reader saves a work joining a series through the work editor or series editor, the system SHALL offer to review copying from the preceding work after the editor successfully finishes; it SHALL NOT copy records automatically.+2. <a name="5.2"></a>The system SHALL determine the predecessor from saved series positions, not creation dates or title tie-break order. WHEN the nearest strictly lower position contains multiple predecessor candidates, the system SHALL ask the reader to choose among available candidates at that position rather than infer one from a display tie-break; it SHALL NOT silently skip an unavailable predecessor for an older work.+3. <a name="5.3"></a>WHEN the destination is first in the series or there is no available eligible character/place record in the predecessor choices, the system SHALL omit the offer.+4. <a name="5.4"></a>Accepting an offer SHALL open the ordinary selection/preview flow with source and destination prefilled and no selected records; declining or cancelling SHALL leave the saved series membership intact and copy nothing.+5. <a name="5.5"></a>The system SHALL offer at most once for each successful series-joining save event; reloading, reopening, unrelated edits, position-only edits and sync/import arrivals SHALL NOT repeat it. A later saved leave/rejoin or move into another series MAY produce a new offer.+6. <a name="5.6"></a>WHEN one series save adds multiple works, the system SHALL present one offer containing eligible additions rather than a sequence of prompts, and let the reader choose which destination to review.++Additional acceptance examples: joining at position 3 after positions 1 and 2 offers position 2 even if position 1 was created later; joining at position 1 omits the offer; tied nearest preceding positions require a source choice; declining then editing notes produces no repeat; a batch addition produces one combined offer; failed/cancelled saves and CloudKit/import arrival produce none.++## Approved design decisions++The approved defaults are names/explicit aliases with fresh name-derived keys, optional record notes off, no extracted facts; Skip/explicit Keep separate without merging; and any direct link/shared complete-series UUID eligibility. Approved offer edge cases are source choice for tied positions, one combined batch offer, and save-event-scoped suppression rather than persisted history. User authorized task planning and implementation on 2026-10-12.
diff --git a/specs/copy-work-records/tasks.md b/specs/copy-work-records/tasks.mdnew file mode 100644index 00000000..3e275b5e--- /dev/null+++ b/specs/copy-work-records/tasks.md@@ -0,0 +1,141 @@+---+references:+ - requirements.md+ - design.md+ - decision_log.md+---+# T-2439 Copy work records++## Core contracts++- [x] 1. Red: write destination eligibility and copy-plan clash tests <!-- id:90dsmk6 -->+ - Use table-driven input permutations: direct link both directions/arbitrary types, complete shared UUID incl absent series directory, no transitive/self target, duplicate titles/series names and both-route dedupe.+ - Cover logical kind/UUID choices, no initial selection, torn exclusions, fresh normalized keys from displayed names, explicit aliases, notes off/on, facts/evidence excluded and no work metadata transfer.+ - Cover current names/destination retained keys/aliases/Unicode/article normalization, empty aliases, cross-kind independence, batch overlaps, initial Skip, acknowledgement only among planned creations, changed overlap invalidates confirmation, repeat-copy detection.+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5)+ - References: Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swift, Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyTests.swift++- [x] 2. Green: implement eligible destinations and immutable clash/payload plans <!-- id:90dsmk7 -->+ - Use immutable Sendable values and session-planned destination UUIDs; no new persisted models, dependencies or property-testing library.+ - Reuse RecordNameKey, WorkPickerOrdering and record presentation/ranking; preview shows concrete clash members, includes skipped informational overlaps and distinguishes creation choice from Keep separate acknowledgement.+ - Blocked-by: 90dsmk6 (Red: write destination eligibility and copy-plan clash tests)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5)+ - References: Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swift, Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyTests.swift++- [x] 3. Red: write real-store preview, atomic copy and uncertain-outcome tests <!-- id:90dsmk8 -->+ - Retain real ModelContainer fixtures; read work-scoped then whole-ID groups for both kinds. Test same-ID siblings with off-owner/absent owner/conflicting key, torn source/destination, missing or unwritable work and complete eligibility recheck.+ - Assert mixed character/place creation has fresh planned UUIDs, destination ownership and quantized timestamps, fresh current-name key, zero facts/coverage/source suppressions transferred; only derived destination candidate suppression clears. Source, existing destination records and both Work metadata rows stay unchanged.+ - Inject save failure after both kinds are inserted; reopen/refault to prove no partial rows or suppression changes. Stale copied payload/owner/torn state/destination matching surface/link/series changes refuse all writes; fact-only changes do not invalidate unchanged non-torn payload.+ - Inspect outcome by locked kind/planned-created UUID with all sibling owner/key/payload checks: all present succeeds, none refreshes without automatic retry, partial/conflicting result refuses. Skip UUIDs never enter outcome inspection.+ - Exercise existing destination edit/delete/extraction matching plus current backup export/import twice: copies retain independent IDs/ownership/content and importing again is idempotent; no Markdown/archive format expansion.+ - Blocked-by: 90dsmk7 (Green: implement eligible destinations and immutable clash/payload plans)+ - Stream: 1+ - Requirements: [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.4](requirements.md#4.4)+ - References: Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swift, Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift, Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift, Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportRecordsTests.swift++- [x] 4. Green: implement locked record copying and exact-ID outcome inspection <!-- id:90dsmk9 -->+ - Add shared read/projection/provider seams and one exclusive-context mixed-kind write using RecordRow.make/attach and RepositorySaveStrategy.+ - Explicitly rollback both refusal and thrown save failure; refault after rollback. Do not call combine/convert, run extraction/reconciliation inside preview, stamp Work metadata or add history/provenance columns.+ - Uncertain explicit retry revalidates same planned UUIDs and warns possible recreation after intervening deletion; no cross-device exactly-once claim.+ - Blocked-by: 90dsmk8 (Red: write real-store preview, atomic copy and uncertain-outcome tests)+ - Stream: 1+ - Requirements: [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [2.5](requirements.md#2.5), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.4](requirements.md#4.4)+ - References: Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swift, Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift, Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift, Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportRecordsTests.swift++- [x] 5. Red: write membership transition receipt and predecessor projection tests <!-- id:90dsmka -->+ - Real locked writer tests distinguish actual resolved nil/different-series→membership joins from stale basis, no-op, same-series position change, failed save and refusal. Verify both ordinary writer APIs retain existing behavior.+ - Receipt addressed→resolved mappings survive redirects; multiple addressed edits resolving one survivor report transaction-initial membership/final membership once. Batch addition intent intersects addressed IDs then dedupes resolved IDs.+ - Predecessor cases: strictly lower greatest saved position incl gaps/fractional/negative values; creation/title/UUID/input order never determines predecessor. Nearest tied bucket asks only that bucket, tied destination peers are not prior works.+ - Determine nearest bucket before availability: no skipping torn/unavailable/empty nearest to older work, no offer for first/no eligible records/inconsistent membership order; include unavailable tied-peer context. Read final batch state; new additions can be predecessor candidates.+ - Reproject on offer acceptance and refresh/drop changed order/source set without silent replacement; after explicit source confirmation normal copy eligibility applies.+ - Blocked-by: 90dsmk9 (Green: implement locked record copying and exact-ID outcome inspection)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6)+ - References: Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift, Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift, Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift, Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swift, Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift, Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyOfferTests.swift++- [x] 6. Green: implement receipt writer variants and bounded series offer projections <!-- id:90dsmkb -->+ - Preserve existing updateWork/commitSeriesEdits contracts via app-facing receipt variants backed by the same internal locked transaction, with no double save.+ - Return receipts only after successful save using existing GroupOrdering complete-membership interpretation. Projection is read-only and no writer creates UI events for import/merge/reconcile/fixtures.+ - Blocked-by: 90dsmka (Red: write membership transition receipt and predecessor projection tests)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6)+ - References: Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift, Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift, Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift, Packages/AsterismCore/Sources/AsterismCore/WorkRecordCopy.swift, Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift, Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyOfferTests.swift++## App flows++- [x] 7. Red: write manual copy session model tests <!-- id:90dsmkc -->+ - Native model tests cover destination/source choices, per-kind select-all/clear, no selection initially, note inclusion/preview, planned Copy/Skip and actual clash acknowledgement invalidation.+ - Gate acceptance: zero planned rows disabled, one in-flight task/double taps, definite failure/refusal retains draft, Cancel writes nothing, confirmed success terminal with destination and created/skipped counts.+ - Keep planned IDs across uncertain response and inspect before reacceptance; none refreshes with conscious retry warning, partial/conflicting IDs stay blocked. Stale async loads cannot replace newer selections or reopen cancelled sessions.+ - Destination success refresh uses normal mutation/export hooks; edits/deletes/extraction of independent copies remain destination-owned. No ModelContext in app and no network/extraction side effects.+ - Blocked-by: 90dsmkb (Green: implement receipt writer variants and bounded series offer projections)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)+ - References: Asterism/Asterism/ViewModels/WorkRecordCopyModel.swift, Asterism/AsterismTests/WorkRecordCopyModelTests.swift, Asterism/AsterismTests/MockLibraryProvider.swift++- [x] 8. Green: implement manual copy session model and provider adapters <!-- id:90dsmkd -->+ - Add value-draft session using repository preview/commit/outcome APIs and injectable provider seams; update mocks concretely, not permissive default fake receipts.+ - Integrate ordinary error/resolution wording without calling load() to discard drafts on conflict; Cancel/close retires async work and clears presentation.+ - Blocked-by: 90dsmkc (Red: write manual copy session model tests)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)+ - References: Asterism/Asterism/ViewModels/WorkRecordCopyModel.swift, Asterism/AsterismTests/WorkRecordCopyModelTests.swift, Asterism/AsterismTests/MockLibraryProvider.swift++- [x] 9. Red: write manual-copy rendered selection and correction journeys <!-- id:90dsmke -->+ - Seed isolated URL-free related/series books, characters and places, aliases, record notes/facts, same-name records and torn choices. Assert selecting both kinds, Include notes preview, no facts transfer, zero-count Save disabled, repeat clash and explicit Keep separate warning.+ - Assert Cancel/reopen no mutation; successful Copy navigates to destination and normal record editor can correct/combine/delete independently without changing source; stale preview/refusal preserves selection.+ - Phone and targeted iPad journey coverage uses actual hierarchy/stable leaf identifiers. Verify long titles/aliases, kind/selection accessibility, keyboard/escape where supported; existing record/editor/work-picker patterns are visual baseline.+ - Record expected XCTest IDs before bounded make test-only runs and compare actual execution, not exit/discovery alone. Mac app/extension compile is required; do not claim unhosted Mac rendering from simulator tests.+ - Blocked-by: 90dsmkd (Green: implement manual copy session model and provider adapters)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5)+ - References: Asterism/Asterism/Views/WorkDetailView.swift, Asterism/Asterism/Views/WorkRecordCopyView.swift, Asterism/Asterism/ViewModels/WorkDetailModel.swift, Asterism/Asterism/ViewModels/AppLibraryModel.swift, Asterism/AsterismUITests/WorkRecordCopyUITests.swift++- [x] 10. Green: implement Work detail copy action and native selection/preview view <!-- id:90dsmkf -->+ - Expose app-only Copy action outside Work detail edit mode; wire one owned sheet to model/provider, existing RecordKindPresentation summaries and normal resolution/navigation.+ - Keep membership/work metadata untouched by manual copying; source and destination remain explicit; no copy UI/writer in share extension, no automatic selection.+ - Blocked-by: 90dsmke (Red: write manual-copy rendered selection and correction journeys)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [1.4](requirements.md#1.4), [1.5](requirements.md#1.5), [1.6](requirements.md#1.6), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5)+ - References: Asterism/Asterism/Views/WorkDetailView.swift, Asterism/Asterism/Views/WorkRecordCopyView.swift, Asterism/Asterism/ViewModels/WorkDetailModel.swift, Asterism/Asterism/ViewModels/AppLibraryModel.swift, Asterism/AsterismUITests/WorkRecordCopyUITests.swift++- [x] 11. Red: write series offer coordinator and both editor success-hook tests <!-- id:90dsmkg -->+ - Drive Work editor real commit sequencing: metadata join then record/link refusal emits no modal; retry emits once, later confirmed different-series replaces pending receipt, confirmed leave clears, same-series changes preserve; Cancel/navigation consumes without undoing saved membership.+ - Series editor captures staged addition addressed IDs before clear, intersects committed receipt transitions, dedupes resolved destinations and queues one final-state batch offer only after inline edit exit and mutation/reload.+ - Test event-only suppression across repeated callbacks/reloads/unrelated edits/position edits/reopen; import/merge/reconcile/fixtures never emit, explicit later leave/rejoin or another-series join may emit again.+ - Coordinator rejects obsolete host generations/navigation or left-series destinations; offer acceptance reprojects ties/order/available records and never silently changes source. Closing chosen copy flow consumes whole batch; other destinations retain manual access.+ - Blocked-by: 90dsmkf (Green: implement Work detail copy action and native selection/preview view)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [4.1](requirements.md#4.1), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)+ - References: Asterism/Asterism/ViewModels/RecordCopyOfferCoordinator.swift, Asterism/Asterism/ViewModels/WorkDetailModel.swift, Asterism/Asterism/ViewModels/SeriesModels.swift, Asterism/AsterismTests/RecordCopyOfferCoordinatorTests.swift, Asterism/AsterismTests/SeriesModelsTests.swift, Asterism/AsterismTests/WorkDetailSeriesCopyOfferTests.swift++- [x] 12. Green: implement once-per-save coordinator and confirmed join editor hooks <!-- id:90dsmkh -->+ - Wire only two interactive editor paths to typed receipt variants; capture before mutation/load and defer event presentation until full terminal success. Do not derive event from snapshotGeneration or stored membership on load.+ - App-local queue and consumed save-event IDs only; no schema, UserDefaults or persisted once-ever history. Open ordinary copy model with source/destination prefilled and no selections; use one presentation owner.+ - Blocked-by: 90dsmkg (Red: write series offer coordinator and both editor success-hook tests)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [4.1](requirements.md#4.1), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)+ - References: Asterism/Asterism/ViewModels/RecordCopyOfferCoordinator.swift, Asterism/Asterism/ViewModels/WorkDetailModel.swift, Asterism/Asterism/ViewModels/SeriesModels.swift, Asterism/AsterismTests/RecordCopyOfferCoordinatorTests.swift, Asterism/AsterismTests/SeriesModelsTests.swift, Asterism/AsterismTests/WorkDetailSeriesCopyOfferTests.swift++- [x] 13. Red: write post-series-save rendered offer and accessibility journeys <!-- id:90dsmki -->+ - Isolated phone/iPad rendered tests cover both inline editor paths: saved join offers Review, accepting prefills source/destination but copies/selects nothing, decline/copy Cancel preserves membership and creates no records.+ - Cover unique predecessor, tied nearest source chooser with unavailable-peer explanation, first/no-record/no-order suppression and no backwards fallback, same-position destination peer, changed order while offer open, no prompt after no-op/position-only edits or reopen.+ - Batch addition renders one list labelled reviewing one destination, chosen flow closure consumes all batch offers with manual Copy accessible; no modal stack/member picker collision and navigation invalidates queued presentation.+ - Use existing native picker/sheet patterns and stable accessible leaf IDs; verify actual method execution and targeted wide-layout consumers. Preserve all existing assertions; full UI gates reserved for pre-push-review.+ - Blocked-by: 90dsmkh (Green: implement once-per-save coordinator and confirmed join editor hooks)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [4.1](requirements.md#4.1), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5)+ - References: Asterism/Asterism/Views/WorkDetailView.swift, Asterism/Asterism/Views/SeriesDetailView.swift, Asterism/Asterism/Views/RecordCopyOfferView.swift, Asterism/AsterismUITests/WorkRecordCopyOfferUITests.swift, Asterism/AsterismUITests/SeriesUITests.swift, Asterism/AsterismUITests/WideLayoutUITests.swift++- [x] 14. Green: implement review-offer presentation for Work and Series detail hosts <!-- id:90dsmkj -->+ - Render coordinator offers only after edit-mode exit and mutation/reload with no active competing modal. Use Review wording, Copy only in final preview; display series positions/context and concrete tied-source explanations.+ - Integrate dismissal/escape/keyboard/VoiceOver and host disappearance with coordinator consumption; do not change export/import/migration, relationship creation or deployment behavior.+ - Blocked-by: 90dsmki (Red: write post-series-save rendered offer and accessibility journeys)+ - Stream: 1+ - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [5.6](requirements.md#5.6), [4.1](requirements.md#4.1), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5)+ - References: Asterism/Asterism/Views/WorkDetailView.swift, Asterism/Asterism/Views/SeriesDetailView.swift, Asterism/Asterism/Views/RecordCopyOfferView.swift, Asterism/AsterismUITests/WorkRecordCopyOfferUITests.swift, Asterism/AsterismUITests/SeriesUITests.swift, Asterism/AsterismUITests/WideLayoutUITests.swift+++Implementation tasks above are complete. Final acceptance remains qualified: all 13 feature phone journeys and full iPad 30 passed; all 227 phone identities are accounted for across preserved interrupted/bounded scopes. The alias-chip journey repeated on its sole historical retry; later investigation proved a UI-test tap into the tab bar and corrected the scoped helper while preserving assertions. Current exact-source checks are in implementation.md and the bugfix report. Two M4 skips and the unfinalized watchdog bundle remain explicit. See implementation.md and draft PR107. This is not a green full-UI verdict.
diff --git a/specs/cover-image-drop/decision_log.md b/specs/cover-image-drop/decision_log.mdnew file mode 100644index 00000000..addd4d12--- /dev/null+++ b/specs/cover-image-drop/decision_log.md@@ -0,0 +1,41 @@+# Decisions — T-2433++| ID | Date | Decision | Evidence / authority |+|---|---|---|---|+| Q1 | 2026-10-11 | Use smolspec for one local input gesture | Exact Transit ticket requests image-file drag/drop; current cover pipeline settles crop, draft, Save/Cancel and encoding. No schema/public boundary/contested central architecture. Source peer agrees. |+| Q2 | 2026-10-11 | Reuse crop/draft/Save, accept local image sources only | Existing work-thumbnails requirements 2/3/5 and current file-picker implementation; drop does not extend paste's remote URL-fetch behavior. |+| Q3 | 2026-10-11 | User's current implementation approval authorises settled scope and feature branch | User explicitly asked to implement T-2433 with T-2436; no repeated phase/name/branch approval for already settled choices. Branch `T-2433/cover-drop-and-chapter-confirmation` from merged main `8aef9858`. |+| Q4 | 2026-10-11 | Preserve exact read failures and successful UUID scope | Full display-ID reads timed out; exact UUID full read succeeded with empty comments and Asterism project. No inferred ticket scope. |+| Q5 | 2026-10-11 | Keep heavyweight jobs serial and initially source-only | Halo owns lane; write source/tests now and request slot before executing. No merge/deployment authorised. |++Source: T-2433 `5C9B5B73-96FB-4C0C-A4D6-01E3A26E760B`, full revision `r1:a10d22f48503f6cccf94ba58730bc4d73811ad3dc8b512eda6a9b99ae47dbb17`: “Allow the setting of a cover image by dragging and dropping the image file. Useful for example with Amazon sites where it can't scan for them.”++Review completion: clean-context beginner/intermediate/expert explanation and source-peer/design-critic reviews found no escalation trigger. Incorporated provider/representation fallback, deferred failure guidance, five inherited formats, submission guard, explicit navigation retirement and honest rendered-drag coverage limits. No explanation artifact was saved.++Provider lifetime evidence: [Apple NSItemProvider file-representation documentation](https://developer.apple.com/documentation/foundation/nsitemprovider/loadfilerepresentation%28fortypeidentifier%3Acompletionhandler%3A%29) states that the temporary copy is deleted when the completion handler returns. The adapter consumes its bytes inside that lifetime.++Static implementation review additionally requires a synchronous admission-token snapshot before scheduling the drop task: navigation or a newer pick can occur before that task starts. The queued task must not adopt the replacement session. A genuine queued-admission fixture is included in the scoped test cohort; all 21 parameterized new drop cases subsequently passed in the focused native cohort.++## Verified implementation checkpoint — 2026-10-12++The parent granted the exclusive serial lane, leaving user Xcode indexing untouched. Frozen source passed focused Core/native checks, unfiltered package, fast, signed Mac app/embedded-extension compile, unfiltered native and exactly two crop Cancel/Save UI journeys. The two source commits are `af2d84df` (T-2436) and `e434b7de` (T-2433). No baseline behavioral red is claimed. Runtime/compiler warnings and exact discovery counts are preserved in [implementation evidence](implementation.md).++Implementation tasks are complete for draft review. Full phone/iPad UI acceptance, actual external-file drag and incoming extension rendering remain explicit acceptance subparts; prior T-2416 Mac/live CloudKit limits remain. No merge, deployment or live-data change is authorized or performed.++## Final UI batch authority and preserved verdict++After Halo drained, the parent granted one final phone gate followed by the two iPad suites. Existing passing Core/native/fast/Mac gates are reused. The full phone gate failed the unrelated Settings role-reordering method; one exact retry is permitted and cannot replace the failed full-gate verdict. The full iPad gate failed an unchanged day-selection test at a Monday week boundary. The one exact phone role retry passed; the one exact iPad inspector retry reproduced the missing yesterday strip. Flag the inspector fixture for separate follow-up and preserve both original failed full-gate verdicts. No broad repeats, assertion weakening or source edits are planned for unrelated failures. Actual external drag and incoming share remain blocked on supported isolated hosts; final source re-review of all seven files found no remaining blocker.++## Q6 — Generic advertisement is not encoded-format permission++2026-10-12. Owner feedback confirms the intended Cover target was used. Native red proves that public.image-only providers are refused before decoding. Admit the generic image representation using the existing loader while retaining the five-format byte check. Do not change Menu hit testing or identify the user's source-app payload without actual evidence. Native green is not external-drag acceptance.++## 2026-10-13: Keep List layout and bridge native iOS drop routing++Owner Safari and Files gestures on the installed diagnostic app still did nothing. No scoped phone log archive was obtained: macOS device log collection requires administrator authentication; the user-run app/category/two-minute collection is pending. Absence of that archive is not evidence of absent phone callbacks.++A controlled private iOS 26.5 Safari comparison used the same real synthetic PNG drag and byte-identical source/visible Cover bounds. The List control failed before any callback; moving the same editor content outside List delivered public.png/public.url, decoded 600×900 PNG and opened crop. The final outside-List Cancel journey passed. This identifies a List-hosted integration failure on this simulator, not the exact phone cause or a universal UIKit mechanism. Earlier paired Cancel failure and invalid AX-only arrangement remain recorded.++Rejected disposable comparisons include Menu target, broad item filter, caption target, rectangular content shape, row DropDelegate and whole-List DropDelegate: none delivered the drag. A field-scoped UIKit surface keeps the existing layout and passes actual production Safari drag/crop/Cancel. Ordinary input remains with the existing Menu. The initial UIKit guard rejected native targeting events and failed; the corrected surface switches over public ordinary UIEvent types and permits UIKit interaction events via @unknown default, without a private numeric event constant.++Four independent reuse, quality, efficiency and spec reviewers found no code blocker. Direct delegate rejection/transition tests remain optional additional boundary coverage; existing model guards cover unsupported representations and editor/submission/session retirement. Phone, actual Files drag, Save/reopen and broader rendered acceptance remain open. No new phone build/install/launch or merge is authorized for this source fix.
diff --git a/specs/cover-image-drop/implementation.md b/specs/cover-image-drop/implementation.mdnew file mode 100644index 00000000..bbd8391b--- /dev/null+++ b/specs/cover-image-drop/implementation.md@@ -0,0 +1,160 @@+# T-2433/T-2436 implementation and verification++Base: merged Asterism main `8aef9858`. Plan commit: `28343a2e`. Worktree: `/Users/arjen/Documents/Codex/2026-10-10/task/asterism-t2433-t2436`; branch `T-2433/cover-drop-and-chapter-confirmation`. Source commits: T-2436 `af2d84df`; T-2433 `e434b7de`. Original checkout retains its unrelated untracked `specs/general/`.++## T-2433+Source changes cover `WorkDetailModel.swift`, `WorkDetailView.swift`, `WorkDetailThumbnailTests.swift` and the existing test-only `MockLibraryProvider` submission gate. The drop target retains the Cover menu/accessibility and highlights eligible drags. The adapter loads supported image and local-file representations, consumes provider temporary bytes inside callback lifetime, decodes before selecting a winner, avoids remote URL/text fetching, and reuses crop/draft/Save.++A separate in-memory admission generation is reserved synchronously for each eligible drop. Generation plus existing thumbnail-session guards protect queued/in-flight loading, navigation, newer picks, work cancellation, read-only transitions and Save submission. Saving retires pending picks; page disappearance explicitly retires the thumbnail presentation. Invalid accepted loads preserve the cover draft with file guidance only after fallback candidates are exhausted. Unsupported public URL/text drops preserve session/crop/guidance.++Ten new native regression declarations describe 21 parameterized cases: crop/Save/Cancel, first-decodable representation/provider fallback, local and temporary file lifetime, remote/text rejection, invalid/unreadable content, delayed success/failure, navigation, Save/submission, read-only work, queued admission and queued/in-flight newer-drop precedence. All ten declarations / 21 cases executed successfully in the focused native cohort.++Source peer, clean-context explanation and design critique are complete; the final admission ordering recheck found no remaining source blocker. Focused checks passed: Core 101 tests in five suites and native 64 tests in three suites. Required pre-commit checks and the two focused downstream UI journeys also passed. Existing external-file drag delivery lacks an automated source in the current UI fixtures; provider tests will not establish real native drag rendering. Downstream crop/Save/Cancel journeys passed in isolated fixtures, while actual Mac/iPad file drag remains an explicit rendered acceptance subpart.++## T-2436+The three-file source patch adds an initial-expansion value predicate, uses it in the common extension chapter-choice view, and adds two focused projection regressions. Ordinary optional choices are collapsed behind Choose chapter; mandatory ambiguity, multiple-chapters-per-page defaults and correction remain available. Resolver decisions, Save guards and writes are unchanged. Narrow independent source review found no blocker. Projection tests and extension compilation passed. Incoming extension rendering remains unverified.++## Verification scope+The parent granted this thread the exclusive serial verification lane after confirming no agent build/test job was active. User Xcode SourceKit background indexing remained untouched. All jobs ran serially using private caches and a dedicated simulator, with the source patch frozen throughout. The subsequent parent-authorized final UI batch runs one full phone gate then the two iPad suites. No Mac user-library launch, live CloudKit changes, merge or explicit installation was performed.++The affected Core selection covered chapter projection/capture state, thumbnail codec and thumbnail repository consumers; the native selection covered Work detail thumbnails, Find Cover and extension wiring. Required unfiltered package, fast, signed Mac compile and native gates passed. The exact downstream UI selection covered crop Cancel and crop Save. Provider tests establish input processing; existing rendered journeys establish downstream UI, not external-file drag delivery. Actual Mac/iPad file drag and incoming share-extension rendering remain acceptance subparts because the current harness lacks an isolated external provider/extension host.++No remaining product decision or new user approval is needed for the settled implementation. Draft review can proceed; both final full UI gates have failed unrelated methods, and remaining real-device/rendered checks are incomplete.++## Executed focused evidence++- Core focused1: exit 0, 101 tests / five suites, 2.952 seconds test duration. Both new chapter-presentation declarations executed. Log: `/tmp/t2433-t2436-core-focused1.log`.+- Native focused1: exit 0, 64 declarations / 77 parameterized invocations in three suites; zero failures/skips and no structured runtime warning. All ten new drop declarations / 21 cases executed. Log and result: `/tmp/t2433-t2436-native1.log`, `/tmp/t2433-t2436-native1.xcresult`; summary: `/tmp/t2433-t2436-native1-summary.json`.+- Native console also emitted expected mock Work URL `notConfigured` and simulator CVPixelBuffer `-6680` messages on passing codec paths. Compilation emitted unchanged FoundationModels deprecated-initializer / NoEpisode unnecessary-try warnings and skipped AppIntents metadata tooling. No patch source introduced a compiler warning.+- Baseline behavioral red was not obtained: the new drop API and presentation predicate were absent before this patch. Missing-API compilation is not claimed as a runtime regression demonstration.++The parent subsequently granted one final phone/iPad UI batch. The phone full gate failed one unrelated Settings role-reordering method; its original failure remains authoritative even if the permitted targeted retry passes. This branch remains a draft; passing affected checks does not establish a green full UI verdict or erase the previous T-2416 acceptance limits.++## Required gate receipts++- Unfiltered `make test-core`: exit 0. XML reports 3,839 testcase elements across package products: 3,784 passing and 55 skipped, zero failures/errors. Core product accounts for 3,264 elements / 305 suites (3,209 passing / 55 opt-in skips), 172.796 seconds. Other products contribute 42 / eight, 304 / 20 and 229 / 13. Log `/tmp/t2433-t2436-core-full1.log`; XML `/tmp/t2433-t2436-core-full1-swift-testing.xml`. Existing corrupt-store fixture diagnostics are expected and are not test failures.+- `make test-fast`: exit 0; 456 tests / 32 suites (Presentation 304 / 20 and Core 152 / 12). Log `/tmp/t2433-t2436-fast1.log`.+- Signed Mac app/embedded-extension compile and unfiltered `make test-quick`: exit 0. Development app and embedded Mac extension built, signed with Team `V24684SCZN`, and passed deep/strict signature verification using read-only system trust access; no keychain changes. Native discovery executed 1,680 declarations / 1,734 parameterized invocations in 118 suites, zero failures/skips/structured runtime warnings, 32.594 seconds test duration. Log/result prefix `/tmp/t2433-t2436-native-full1`; summary `/tmp/t2433-t2436-native-full1-summary.json`. The Mac compile additionally reports the unchanged `RuleSuggestionCoordinator.swift:344` captured-self concurrency warning.+- Exact rendered cohort: `WorkCoverUITests/testFindCoverOffersACandidateAndOpensTheCropStep` (crop Cancel) and `WorkCoverUITests/testScanPageReachesACoverTheHeadDidNotDeclare` (crop Save). Both passed: two tests, zero failures/skips, 98.192 seconds test execution / 158.759 seconds structured elapsed. Four structured runtime warnings report Calendar/CivilDay Environment access outside an installed View. Log/result prefix `/tmp/t2433-cover-ui1`; summary `/tmp/t2433-cover-ui1-summary.json`. No visual-appearance verdict or external drag screenshot is claimed. All native jobs drained before commits.++Final UI results and remaining acceptance: [exact gate, targeted journeys and isolation blockers](remaining-acceptance.md). Actual external-file drag and incoming extension rendering remain blocked on isolated supported hosts.++## Final UI batch — tested source `9d799f11655362b781d23e0273e4ebc4895cc997`++The parent granted the exclusive lane after Halo drained. Previously passing Core, fast, native and Mac gates were reused. All seven modified source/test files remained frozen, and final independent source review found no remaining source blocker.++- Phone `make test-ui`: make exit 2 / xcodebuild 65, full verdict **Failed**. All 214 expected distinct method IDs across 35 suites matched discovery (no missing/unexpected IDs): 211 passed, one failed, two opt-in measurement skips. Dynamic launch configurations produced 217 invocations: 214 passed, one failed, two skipped. Runner elapsed 8,287.253 seconds; structured elapsed 8,348.879 seconds. Structured warnings: 212 (106 Calendar and 106 CivilDay Environment access warnings), with no diagnostic cap. Log/result prefix `/tmp/t2433-t2436-final-phone-ui`; expected/actual comparison `/tmp/t2433-t2436-final-phone-ui-inventory-comparison.json`.+- Failure: `CreatorRolesSettingsUITests/testReorderingTheActiveRolesCommitsAndSurvivesLeavingTheScreen`, line 296, Req 2.5. The drag left `[author, artist, translator, letterer, editor]` unchanged and the waiter timed out (38.463 seconds). This Settings role-reordering path is outside the cover/chapter patch. All WorkCover and ChapterNotes methods passed. The single permitted exact retry is recorded separately below; there is no full phone rerun.+- iPad `make test-ui-ipad`: make exit 2 / xcodebuild 65, full verdict **Failed**. All 30 expected method IDs across two suites matched (no missing/unexpected): 29 passing / one failing / no skips. Runner duration 752.043 seconds; structured elapsed 1,393.268 seconds includes the logged 600-second simulator diagnostic-collector timeout. Fourteen structured runtime warnings (seven Calendar / seven CivilDay). Log/result prefix `/tmp/t2433-t2436-final-ipad-ui`; inventory comparison `/tmp/t2433-t2436-final-ipad-ui-inventory-comparison.json`. The single failure is `WideLayoutUITests/testClosingInspectorAndChangingDayClearItsSelection`, line 850: no matching `today-strip-2026-10-11`, 28.185 seconds. Source inspection shows the Monday boundary puts yesterday in the previous week; this unchanged test directly taps yesterday without the previous-week navigation used by a nearby test. This is an evidence-based fixture explanation, not a baseline runtime pass. One exact retry is permitted.+- One exact phone role retry: exit 0, one passing / zero failures/skips/runtime warnings; runner 37.339 seconds / structured 78.142 seconds. Prefix `/tmp/t2433-t2436-final-role-retry1`. This isolated pass does not replace the failed full-phone verdict.+- One exact iPad inspector retry: reproduced the same missing `today-strip-2026-10-11` assertion, make exit 2 / xcodebuild 65, zero passing / one failing / no skips/runtime warnings, runner duration 27.991 seconds / structured 79.242 seconds; no diagnostic cap. **Flagged for separate fixture follow-up**, with no source/assertion edit and no further run. Original phone role artifacts include a debug hierarchy and screen recording in `/tmp/t2433-t2436-final-phone-role-attachments`; iPad inspector artifacts in `/tmp/t2433-t2436-final-ipad-inspector-attachments` include hierarchy `1C0F69F6-F833-47E1-9983-40F096B0FC1B.txt` and recording `3B908E98-3AD3-4D6D-B869-F46D08A93BDB.mp4`. No PNG or visual-appearance verdict is claimed.++Provider assertions, crop journeys and this app UI gate do not establish actual external-file drag delivery or incoming extension rendering. No appearance verdict is inferred from test success.++Final lane receipt: `/tmp/t2433-t2436-final-ui-receipt.json`. All verification jobs drained; no further native job is active or queued. No source fix, full rerun, merge, explicit install or live-data operation followed these failures.++## Confirmed owner feedback — generic image admission++The owner confirmed dragging onto the Cover circle in Edit Work on the standalone installed PR105 head c7b380aa. The report is treated as a real failure, not an incorrect gesture. Source investigation found a provider-admission gap: only specific encoded types and file URLs were requested, so a provider advertising only public.image was rejected before bytes could be inspected. No source-app attribution is established; a focused question is pending.++Two native declarations/four cases reproduce this gap. The tests-only red selected the whole WorkDetailThumbnailTests suite: 42 declarations/55 invocations, 40/51 passed and the two/four new cases failed exactly at admission; make exited2/Xcode65 and drained. Adding generic image to the existing requested types passes the same 42/55 selection, exit0/drained, no skips or structured runtime warnings. Logs/results are /tmp/asterism-pr105-cover-generic-{red,green}.log/.xcresult. Valid generic data and temporary-file callbacks reach the existing crop; TIFF/BMP bytes advertised as generic images remain refused by the existing five-format decoder guard. No conversion to unrestricted image formats, writer change or broad hit-area change was made.++Actual cross-app drag delivery is still unverified. Supported CUA inventory lacked Simulator; attempts to obtain its bundle/path failed, and Device Hub selected an Apple Watch window. No watch interaction or live Mac library operation followed. Existing app UI tests have no external Photos/Files host or multitasking bootstrap. A downstream crop shortcut is not a substitute for real drag. The cover target is attached outside the full-width captioned field and its 44-point Menu label; source alone does not establish a native hit-testing defect.++### Beginner explanation+The editor can now consider a dragged picture even when its source calls it simply an image. It still checks the file, opens the usual crop screen and waits for Save. The confirmed phone gesture remains an open runtime check.++### Intermediate explanation+Adding UTType.image to coverDropTypes admits generic image representations into the existing ordered data/file loader. Session/admission guards, callback-scoped temporary-file reads, draft preservation and actual encoded-format validation remain unchanged. Regression tests exercise provider callbacks rather than a forced crop shortcut.++### Expert explanation+Admission and decoding remain separate boundaries. A generic advertised type broadens eligible transfer representations without broadening accepted encoded formats. Returning acceptance schedules the existing guarded task; it does not certify usable bytes, crop completion or persistence. Tests retain the lifetime/race/rollback semantics, while source-app representation and OS drop-target delivery require a genuine external drag.++### Completeness assessment+Generic-image admission is implemented and native red/green is recorded. Fresh signed Mac/full native/package/fast gates are in progress. Actual external drag and incoming extension rendering remain unverified; historical full UI failure verdicts are preserved and no full UI rerun is part of this feedback fix.++Review follow-up: the first generic-admission green is provisional. Specification review found that a concrete TIFF/BMP advertisement also conforms to image and would wrongly retire an existing crop. A distinct concrete-unsupported-provider regression and exact-generic-advertisement guard are being verified; the opaque generic-image byte refusal remains a separate required case. No source-clear or delivered-fix verdict is claimed from the provisional green.++Fresh unfiltered package validation after the chapter fix passed, make exit0/drained. The actual structured file is /tmp/asterism-pr105-fix-core-swift-testing.xml (Swift6 suffix): 3,841 testcase elements, 3,786 passed, 55 existing opt-in skips, zero failures/errors. Product declaration counts are 42 ConstellationKit, 304 Presentation, 229 Intelligence and 3,266 Core. All thirteen ChapterCaptureResolverTests declarations executed/passed. Existing fresh-cache compiler warnings are retained; no changed Core file warning is claimed. The later concrete unsupported-image correction is App-only; package source hashes must remain identical for this result to be reused.++Concrete unsupported-provider follow-up: red2 selected 43 declarations/57 invocations, 42/55 passed and the new one/two cases failed with eight assertions at unintended admission/session retirement/guidance. Actual make exit2/Xcode65 and drain were checked; the exact owned post-test diagnostic collector was gracefully terminated at197seconds, with runner/xcodebuild untouched. Green2 reuses one shared predicate for admission and candidate loading: generic image requires an exact registered public.image identifier, while supported concrete types/file URLs retain conformance matching. The same43/57 selection now passes, makeexit0/drained, nofailures/skips/structuredruntimewarnings. Both artifacts are /tmp/asterism-pr105-cover-generic-{red2,green2}.xcresult with matching logs. Specification re-review confirms the unsupported-only preservation finding is resolved; earlier provisional green is retained as historical evidence. Actual external drag remains unverified.++Fresh final fix checks: official fast gate passes456 manifest IDs (304 Presentation +152 Core), exit0/drained, with456 actual XML cases and nofailures/skips/errors. Fullnative/signedMac run completed exit2/Xcode65:1,683 declarations/1,740 invocations,1,682/1,739 passed and one/one failed, no skips/structured runtime warnings. The only failure is the untouched PendingCaptureWatcherTests/theWatcherReopensADeletedDirectory() arrival timeout. Signed Mac compilation/embed and independent deep/strict app and Mac-extension signature verification pass; the Mac app was not launched. The five-file source patch is unchanged before/after. The original full-native failure remains authoritative; one exact watcher retry is allowed, not another full run. Logs/results prefix /tmp/asterism-pr105-fix-full-native; fast proof prefix /tmp/asterism-pr105-fix-fast. A shell-selection quoting failure happened before xcodebuild on the first exact-retry command (0executions/noresult); the selector quoting is being corrected without changing source or selection.++The single exact watcher retry passed one declaration/one invocation, exit0/drained, no skips/structured runtime warnings (0.720s method). Source remains unchanged; the original full-native failed verdict is not replaced. Source/test fix commit1d7e4e2953570617ebd804bd1a66d7088ca29280 contains exactly the five reviewed source/test files. No physical device installation follows this commit; latest owner instruction requires a new explicit approval before any installation.++A genuine external-drag diagnostic was prepared with a synthetic600x900 PNG and real Photos-to-Cover XCTest drag, with no model/crop shortcut. First inventory executed one method and failed at the existing wide Library navigation helper before Photos/editor; it provides no drag verdict. It ran on dedicated AsterismT2416iPad855A118C-CF25-4990-B8E7-342F3F4B6129, importing only that synthetic image, using a fresh UUID temporary Asterism library with nil CloudKit. Actual hierarchy shows collapsed sidebar-toggle; inventory2 corrects only the temporary diagnostic's setup using this observed control. The temporary test is not part of the committed source or final acceptance suite. Root/agents preserve all original results and do not operate the user's real Mac library.++## External-drag investigation: concrete simulator-host blocker++Inventory2 passed one inventory method and captured the real Cover No cover target plus the uniquely named synthetic Photos image. The Photos What's New modal was observed and dismissed in inventory3. A bounds-validated corner gesture resized Photos to375x627; inventory3 passed and the image was visible, but the editor remained in the background. Inventory4's observed Window Controls tap crashed simulator backboardd with SIGABRT in Metal texture validation/CoreAnimation rendering; the runner reported Test crashed with signal kill, makeexit2/Xcode65. No popup snapshot/editor reactivation/photo drag was reached. A final bounded probe avoided that control, but Photos activation itself caused another backboardd/Metal crash before the visible source/target arrangement or drag. It also failed one method, makeexit2/Xcode65. Neither was an Asterism crash or proof of a product drop failure.++All jobs drained, temporary test source was removed, and no further probe is queued. Actual external image drag was never executed; delivery remains unverified. Root does not mark the owner's reported gesture fixed from provider regressions. The unresolved source-app/payload question remains relevant. The shortest owner verification is an approved fresh Devsterism installation followed by the same image gesture; latest instruction prohibits that installation without fresh user approval. No physical installation afterc7b380aa was performed. Receipts, synthetic image, exported hierarchies/screenshots and both .ips reports are under/tmp/asterism-pr105-external-probe/. Inventory-only passes are not acceptance passes.++PR105 feedback code commit1d7e4e29 and documentation commits preserve the original native and historical UI failed verdicts; no full UI rerun was made. Review HTML is archived locally inside this task workspace, outside the existing Pulsar feed. Default publication was rejected by automatic approval review for possible private-source export to an unspecified destination; source inspection proved archive-only file I/O and an explicit workspace directory provided a safer local-only alternative. No existing feed/server/configuration was updated.+++## Owner-tested reinstall and Safari/Files diagnostic — 2026-10-12++The owner explicitly requested reinstalling standalone PR105 `beb8e6d6`. The approved Makefile route built, signed and installed Development `me.nore.ig.Asterism.dev` on The Dark Side (`00008150-000C49940AE2401C`), exit 0/drained. Deep/strict app and strict iOS extension signature checks passed with normal host trust access; Development team, containers, display name, V20 schema and source matched. Both phone apps remained installed, and regular Asterism's installation URL was unchanged. No reset, uninstall or app launch occurred. Receipt: `/Users/arjen/Documents/Codex/2026-10-12/task-3/pr105-reinstall-completed.json`.++The owner then confirmed **Safari and Files still fail to drop an image onto the Cover coloured circle in Edit Work on the phone**. The provider admission fix is therefore insufficient for the reported case. No later phone install is requested; `04263660` removes detected-chapter correction from sharing entirely and is source-only on PR105.++A destination-specific diagnostic used a disposable source archive at `beb8e6d6`, private `/tmp/pr105-safari-files-native-cache`, fresh UUID temporary fixture libraries with nil CloudKit, and synthetic 600×900/400×400 PNGs served only on loopback. T2439's simulator `F79AE4CB…`, caches and global CUA focus were untouched. No model, paste, Find Cover or crop shortcut was used.++- Fresh iOS 26.5 diagnostic `28ADE819…`: name selection first failed with destination error 70 and zero methods. Exact-UDID compilation succeeded, but launch stalled before any test method; the owned group was interrupted after 8m24s. The result contains a synthetic canceled-runner error, not a delivered drag. The launch log recorded CoreSimulator invalid-state/server-died errors; the diagnostic simulator is Shutdown.+- Warm prior PR105 iPad `855A118C…`, iOS 27: inventory3 passed one method reaching the real editor, Safari and Files. Inventory4 failed one method because existing Safari activation returned an empty accessibility query although its screenshot showed Safari; no image navigation or drag occurred. Only its verified owned post-test collector was capped at 213 seconds, retaining failed verdict.+- Inventory5 passed one method after fresh Safari launch. Real HTTP requests loaded both PNGs and the portrait download link. No usable Files fixture was established: inventory6's real Files Browse snapshot shows On My iPad is Empty.+- Inventory6 passed one method and established nonoverlapping source/target geometry: Safari window resized from `(0,0,834,1210)` to `(230,305,375,486)`, image `(238,549,180,271)` hittable, Cover `(735,612.5,55,56)` hittable and outside Safari. Its exact owned post-test collector was capped at 221 seconds; make exited 0. This is setup evidence, not acceptance.+- The subsequent real-drag probe added only drop-target/provider-admission logging to the disposable WorkDetailView; admitted types and handler behavior were unchanged. It crashed before the `actual-drag-start` attachment, while opening the source host after Files Browse. Result: one crashed method, make exit 2/Xcode 65. `backboardd` report `F3A165FE-3A6A-4D20-BB19-BE9BEF99BC5B.ips` records SIGABRT in Metal texture validation/CoreAnimation, not an Asterism crash. Scoped `PR105DropProbe` log is empty. **Zero real image drag gestures reached the Cover handler, and zero provider identifiers were captured.**++Bounded investigation stops at this concrete simulator-host blocker. The synthetic server was stopped, all owned jobs drained, and the original source checkout is clean after the chapter fix. No speculative hit-area/provider patch follows. Phone failure remains authoritative; actual Safari/Files provider delivery, phone hit testing, crop/save persistence and incoming share rendering remain unverified. Artifacts and copied diagnostic source are preserved under `/tmp/pr105-safari-files-*` and `/Users/arjen/Documents/Codex/2026-10-12/task-3/pr105-safari-files-probe/`.+++## Supported alternative runtime and visual-target correction — 2026-10-12++A read-only edit-tree review found no explicit competing gesture: the card borders/specular edge and drop highlight disable hit testing; the header's simultaneous long press is view-mode-only; the caption wrapper adds layout only. Drop is attached to the wrapper around the Menu. This does not prove native Menu/List delivery, and no speculative target-area change is made.++The private iOS 26.5 destination `28ADE819-2E07-4D97-8EE3-E7D5FD723ACB` completed explicit bootstatus readiness in 10 seconds, then passed one editor/Safari/Files inventory method. Its owned post-test collector was capped at354 seconds, retaining make exit0 and results. A sanitized logging-only diagnostic copy from `21cb7d7a` was prepared without changing layout, accepted types, admission, file lifetime or supported codecs. An expanded View trace initially failed compilation by accessing private isSubmitting; that field was kept inside the model and the View used canAccept instead. The corrected source setup executed/passed one method and make exit0. The trace is opt-in and excludes URLs, filenames, image contents and library records.++The bounded Safari gesture probe then executed one native image press-and-drag, but failed its crop assertion (one method failed, make exit2/Xcode65). **This was not a valid Cover-delivery test:** pre-drag and post-drag screenshots show Safari floating over the wallpaper with Asterism absent; the gesture opened a new Safari image window. Background AX falsely provided hittable Cover bounds `(745,636.5,45,56)`. The trace sink worked and recorded view.ready with editing=true, readOnly=false and canAccept=true, but no target, drop, admission or decoding callback. No application refusal or provider identifier is established. Geometry/isHittable alone is insufficient; both source and actual Cover must be visually confirmed in the same stage before another gesture.++All owned probes and synthetic server drained. Parent reported extreme host load/about32GB swap and prohibited adding heavy diagnostic work until pressure improves. The next exact resource is the already-ready private iOS26.5 destination, with Asterism itself arranged as a visible window alongside the source, followed by an inspected pre-drag screenshot. T2439's destination and global simulator settings remain untouched. If that visible arrangement cannot be provided, direct phone input needs approval for the smallest logging-only diagnostic build/launch. The staged patch, phone capture steps, trace and visual counterexample are in `/Users/arjen/Documents/Codex/2026-10-12/task-3/pr105-drop-diagnostics/`. No phone install/launch or production drop fix followed this investigation.+++## Validated Safari native drag and bounded target comparisons — 2026-10-12++After the focused runtime lane was released, the private iOS 26.5 destination `28ADE819-2E07-4D97-8EE3-E7D5FD723ACB` was responsive enough for cached, serial native probes. Resizing Asterism itself before freshly launching Safari produced a visually verified simultaneous stage: the actual coloured Cover circle was exposed at left and the synthetic direct PNG at right. This supersedes the earlier invalid AX-only arrangement; those failed/invalid artifacts remain historical evidence.++The original-target run `/tmp/pr105-validated-safari-drag2.xcresult` executed one native gesture and failed its crop assertion, make exit 2/Xcode 65. The recording shows the 600×900 synthetic PNG lifted from Safari, moved over the visible Cover, and bounced back. Logging was enabled and emitted `view.ready` with editing/admission true, but emitted no target/drop callback, admission, provider load or decode stage. The actual delivered provider identifiers remain unknown. This establishes a failed native Safari attempt before model decoding, without proving a particular hit-testing, OS filtering, or provider cause.++Four disposable-source comparisons also failed to open crop and logged no target/drop callback: the same handler/types directly on Menu (`/tmp/pr105-menu-target-ab1.xcresult`, one failed method); a broad diagnostic `public.item` filter on Menu (`/tmp/pr105-menu-item-observation1.xcresult`, one); the original wrapper/types with the Cover caption as gesture destination (`/tmp/pr105-caption-drop-observation1.xcresult`, one); and a rectangular outer content shape (`/tmp/pr105-target-shape-files-picker1.xcresult`, two failed methods including Files preparation). Every run completed make exit 2/Xcode 65 and drained. These comparisons are observations, not product fixes, and were never applied to this worktree or installed on the phone.++Safari's native share sheet visibly offered Save to Files for the PNG. The first preparation inventory passed but its action left the share sheet open; a subsequent explicit Cell/save-picker validation failed to find the required action/picker. No real Files source file or Files drag was validated. Owner-reported Files failure remains distinct from this incomplete automated setup.++No cover-drop source fix was committed from these negative results. The opt-in, logging-only patch is prepared and `git apply --check` passes against head `3ff49da4`; its payload excludes UI probes and comparison changes. A fresh approved diagnostic phone install/launch plus the owner's Safari and Files gestures is the remaining direct path to capture where those real attempts stop. No further physical install/launch occurred after the approved `beb8e6d6` reinstall. The private simulator is shut down; native runners, frame extraction and temporary loopback fixture server are drained. Outcomes, sanitized traces, lifted-image frames and the prepared patch are in `/Users/arjen/Documents/Codex/2026-10-12/task-3/pr105-drop-diagnostics/`; `pr105-follow-through-outcome.json` records the current limitation. Historical broad failures are retained and no broad suite was rerun.++## Verified localized native drop correction — 2026-10-13++The historical no-fix/no-install checkpoints above describe their dates; they are superseded by this source fix and the separately approved logging-only diagnostic phone install. That phone package is based on fb959350 and does not contain this new native surface. Its receipt is `/Users/arjen/Documents/Codex/2026-10-12/task-3/pr105-phone-diagnostic/installation.json`. User-reported Safari/Files failures remain authoritative for that package. Scoped device log retrieval remains blocked on user administrator authentication; no archive or phone callback evidence was collected.++### Beginner explanation+The Cover field now receives a real iOS image drag through a native drop interaction. The screen stays in the same place, and the existing menu still works. A delivered image opens the same crop editor; Cancel keeps the previous cover.++### Intermediate explanation+`CoverDropTarget` selects a transparent UIViewRepresentable/UIDropInteraction overlay on iOS and retains SwiftUI onDrop on macOS. The overlay spans the existing Cover field without changing layout. Ordinary public input events pass through; native interaction hit testing reaches the surface. Session eligibility uses the existing `WorkDetailModel.hasCoverDropRepresentation`; accepted providers enter unchanged `beginCoverDrop`, whose session retirement, decoding and editing guards remain authoritative.++### Expert explanation+The change isolates input routing from provider loading and crop publication. Native canHandle/update/perform each recheck current eligibility; update/perform also require local field bounds. Target state writes are deduplicated and cleared on exit/end/drop. The model predicate is now internal for shared admission, with its body unchanged. No private event raw value is shipped: known ordinary UIEvent cases return nil and @unknown default forwards UIKit interaction targeting. This introduces an iOS-specific transport dependency, with no persistence/schema or codec change. Native delegate boundary transitions are not directly mocked; model guards and actual rendered delivery cover the principal paths.++### Source-matched focused verification+`/tmp/pr105-native-surface-regression2.xcresult` passed, make exit 0: 48 test declarations/methods (46 native declarations plus two UI methods), 68 parameterized invocations, zero failures/skips. Selected suites were WorkDetailThumbnailTests and CoverDropSurfaceTests, plus actual `SafariFilesCoverInventoryUITests/testInsideListNativeSafariDrop` and the existing uncovered-work Cover menu journey. The production List view received a real Safari 600×900 synthetic PNG drag; crop opened, Cancel closed it, and No cover remained. The crop screenshot was visually inspected. This is external Safari delivery on the private iOS26.5 iPad simulator, not phone or Files proof. Test-only harness and logs stay outside the worktree.++Signed `make build-mac` passed using Asterism Development/Development; app deep/strict and embedded Mac extension strict signature verification passed (bundle me.nore.ig.Asterism.dev, team V24684SCZN). Mac app was never launched. Four focused reviewers found no actionable code issue.++Historical broad results remain unchanged: package 3,786 passes/55 skips; fast 456 passes; full native 1,739/1,740 with original watcher failure and exact retry 1/1; prior phone/iPad unrelated failures and targeted retry outcomes. No broad suite was rerun. Rejected routing probes and initial native-surface failure remain preserved; `/tmp/pr105-list-target-regression1` was a wrong-source-directory job cancelled with exit130/Xcode75, not a valid drag check. Runtime Environment warnings remain in the passing focused logs.++### Completeness assessment+Native iOS field routing and shared validation are implemented; real production Safari crop/Cancel and ordinary Menu behavior are verified on the private simulator. Files source preparation remains incomplete, phone source-fix delivery is unverified, and external drag Save/reopen, invalid-file rendering and actual extension-share rendering remain outstanding. The chapter automatic correction action was separately removed at 04263660; no share-sheet correction action is reintroduced. No phone action or merge follows this commit.++The final bounded Files setup inventory completed one method, make exit0, at `/tmp/pr105-drop-diagnostic-native-cache/Logs/Test/Test-Asterism Development-2026.10.13_09-18-39-+1100.xcresult`. A label-based Save to Files cell was tapped, but inspected post-action screenshots still show the share sheet; no native save picker, actual Files file or Files drag was established. This is an inventory receipt, not Files acceptance. No further preparation loop follows.
diff --git a/specs/cover-image-drop/remaining-acceptance.md b/specs/cover-image-drop/remaining-acceptance.mdnew file mode 100644index 00000000..2a1993a8--- /dev/null+++ b/specs/cover-image-drop/remaining-acceptance.md@@ -0,0 +1,67 @@+# T-2433/T-2436 final UI gate and remaining acceptance++## Lane authority and acceptance status++On 12 October 2026, read-only process inventory found no `xcodebuild`, `swift-test`, `xctest` or `simctl diagnose` process other than the inventory command itself. The implementation worker also confirmed no active or queued native job. Asterism releases the lane to Halo and requests the next slot **after Halo's coherent batch drains**. Do not start these checks merely because background indexing is absent; parent coordination grants the slot. Leave user Xcode/indexing untouched.++PR [105](https://github.com/ArjenSchwarz/asterism/pull/105) remains a draft. Acceptance is incomplete. No merge or explicit install command is authorized by this preparation. The parent subsequently granted the exclusive final UI slot after Halo drained. The full phone gate ran once and failed one unrelated Settings role method; the full iPad gate also ran once and failed one unrelated day-selection method. The single role retry passed; the single iPad inspector retry reproduced its failure and remains flagged. All verification jobs have drained and the lane is released. Actual drag/share journeys remain pending; no success is inferred from provider/model tests.++## Existing evidence to reuse++Source commits `af2d84df` and `e434b7de` passed the focused checks, unfiltered package gate, fast gate, signed Mac compile, unfiltered `make test-quick` and two crop Cancel/Save journeys. Documentation-only follow-up does not invalidate that evidence. Do **not** rerun those broad suites unchanged. See [implementation](implementation.md) for actual discovery, warning and skip receipts.++## One final UI acceptance gate++Use the existing dedicated `Asterism T2416 Phone` (`1CBFA2E9-AB12-41C1-9852-15D5D5C1EF38`) and `Asterism T2416 iPad` (`855A118C-CF25-4990-B8E7-342F3F4B6129`) simulators. Both were shutdown at preparation and reused for this batch. Use the current Development scheme, private DerivedData and sequential Makefile targets:++```sh+make test-ui SIMULATOR='Asterism T2416 Phone' DERIVED_DATA=/tmp/asterism-t2416-native PIPE_PRETTY= XCODE_TEST_FLAGS='-resultBundlePath /tmp/t2433-t2436-final-phone-ui.xcresult'+make test-ui-ipad IPAD_SIMULATOR='Asterism T2416 iPad' DERIVED_DATA=/tmp/asterism-t2416-native PIPE_PRETTY= XCODE_TEST_FLAGS='-resultBundlePath /tmp/t2433-t2436-final-ipad-ui.xcresult'+```++Capture each command's exit code and complete log separately. Run once serially, phone then iPad, after the slot is granted. Do not add selection/skip overrides. `test-ui` contains the repository's normal two iPad-suite exclusions; `test-ui-ipad` executes those two suites. Keep Makefile serial flags intact. The already-passed unfiltered native gate satisfies the unchanged unit half of the final gate; it is not repeated.++Pre-run source inventory: 214 phone method declarations across 35 XCTest suites; 30 iPad declarations (27 `WideLayoutUITests`, three `WideLayoutAccessibilityUITests`). Exact method identifiers are retained in `/tmp/asterism-t2433-t2436-final-ui-inventory.json`. Compare with actual xcresult discovery and execution, not merely source counts. Preserve all failures, skips, warnings, diagnostic delays, expected/actual identifiers and tested source identity. A missing identifier, failure or incomplete run prevents a green full UI verdict. Investigate a failure on its actual evidence; do not shrink the gate or weaken assertions. The user permits one exact targeted retry for an unrelated failed method, then flagging it; preserve the full-gate failure even if that retry passes. No full reruns are authorized.++The UI fixtures set `ASTERISM_UI_TEST_SCENARIO` and a fresh validated UUID `ASTERISM_UI_TEST_RUN_ID`. `UITestLaunchSupport.swift:492` puts their libraries under `AsterismUITests/<UUID>` in temporary storage, outside the App Group. This gate remains simulator-only. It does not certify actual drag delivery or incoming extension presentation.++## T-2433 actual external-file drag++Required targeted journey uses the OS's real dragged file provider, with JPEG/PNG fixture files having distinct dimensions, rather than calling `acceptDroppedProviders` from a test. In an isolated Mac profile or supported isolated iPad test host:++1. Open a fixture work in edit mode; drag a local file from Finder/Files onto Cover. Verify eligible highlight, crop opening and intended image, then Cancel crop and verify the previous draft cover remains.+2. Drop again, crop, Save work, reopen and verify the new cover. Cancel another work edit and verify its saved cover is unchanged.+3. With an existing draft, drop an invalid image/file and verify draft retention plus file guidance. Drag a remote URL/plain text and verify rejection without fetching or disturbing the draft.+4. Leave editing while a provider load is pending; verify it cannot open a crop later. Admit a newer valid file while an older load is pending and verify the newer image survives. The deterministic timing assertions remain covered by native provider tests; real drag timing may require a controlled external provider host.++Prepared local fixture directory: `/tmp/asterism-t2433-drag-acceptance-fixtures/` contains `portrait-600x900.jpg` (copied from repository `thumbnail-golden-600x900.jpg`), `square-transparent-100x100.png` (copied from `thumbnail-source-transparent.png`), deliberately undecodable `invalid-image.png`, and `remote-url.txt` describing the remote-only rejection case. `sips` confirmed JPEG 600×900 and PNG 100×100. The text file itself is not a URL provider; that negative case requires dragging an actual URL/plain-text provider from a supported external source. Files have not been imported into a simulator, dropped or installed anywhere.++Blocker: `WorkCoverUITests` launches only Asterism and has no external Finder/Files file source, native drag session fixture or provider-delivery harness. Its Find Cover stub reaches the downstream crop but is not a file drag. Neither `simctl` nor an app accessibility tap injects a real file provider. Computer-use interaction could drive a real source once an isolated source/destination exists; it does not create the missing isolation contract.++The Mac DEBUG UUID library path exists, but seeded `ContentView.swift:154` resets `UserDefaults.standard` keys. No disposable preference-domain selector, Mac UI-test host or prepared disposable macOS profile exists in this checkout. Launching the user's Mac app or changing its preference domain is not this acceptance preparation. An isolated Mac profile, or a narrow test-only host with temporary library and disposable preferences, is needed. For iPad, the existing isolated Asterism fixture is available, but there is no prepared Files image fixture and supported cross-app drag driver. Do not substitute a model call, add a product demo source, or claim compilation proves delivery.++## T-2436 actual incoming share++Target the installed Development extension in a supported isolated test host/library, using local deterministic pages with URL/title evidence:++- Ordinary new URL and saved URL: Save remains available without expanded chapter alternatives; Choose chapter exposes the optional routes.+- Clearly identified chapter 12: appropriate create/update, hidden Add another chapter, available correction; incorrect detection can be corrected without losing draft/content.+- Shared page with multiple saved chapter targets or incomparable evidence: required selection stays visible and prevents an accidental target choice.+- Multiple-chapters-per-page default: new chapter remains initially exposed; generic-note route and optional titles remain usable.+- Individual → whole-work → individual URL layouts: select/match the existing chapter, retain source links and avoid silent duplicate chapter identity; verify Save/Cancel and reopen.++Blocker: `ChapterCaptureChoicesView`, `CaptureView` and `ReShareCaptureView` render in extension targets, outside the app UI-test host. `ShareCaptureSession.swift:129` resolves the extension's declared App Group using `LibraryConfiguration.production`; it does not consume the app's UUID temporary test library environment. There is no existing external activity host plus supported isolated extension-library handoff. Safari/manual sharing alone would use the Development App Group rather than the asserted temporary fixture. No live or shared library mutation is authorized here.++Required infrastructure is a narrow external share host invoking the actual extension and a DEBUG/test-only, validated isolated-library handoff compatible with extension opening. The host must supply real URL/title providers and exercise both new and saved branches; embedding the common view in the app or reusing a capture model is not equivalent. Keep production configuration fail-closed and tests off CloudKit. This preparation designs no product behavior change and makes no infrastructure code changes.++## Decision / checkpoint++No remaining product decision blocks the settled feature. The final full phone and iPad gates ran once and both failed one unrelated method. The single phone role retry passed; the single iPad inspector retry reproduced its failure. No further reruns are planned. See [implementation evidence](implementation.md) for the exact original failure and eventual retry receipt. Actual drag and incoming share are blocked on supported isolated rendered hosts; these are genuine test-infrastructure prerequisites. Parent should choose a narrow harness follow-up or arrange a disposable owner-run test environment. Do not mark either rendered acceptance subpart complete until actual execution is recorded. No merge/install authority is implied.++## Updated checkpoint — 2026-10-13++Historical infrastructure/no-fix statements above retain their original context. A private iOS26.5 cross-app XCTest host now executes an actual native Safari image drag onto the production Cover field. The localized UIKit surface passes drop-to-crop/Cancel and the existing Menu journey (48 focused declarations/methods, 68 invocations, zero failures/skips). The List layout is unchanged. This closes that bounded Safari delivery/crop/Cancel subpart only.++Still open: actual Files drag; phone verification of the new source fix; external image crop-confirm/Save/reopen and existing-draft/invalid-source rendered journeys; actual incoming share-extension presentation. The installed phone logging-only package is fb959350-based and lacks the new fix. Its owner-reported Safari/Files failures remain recorded. Scoped two-minute app/category phone logging awaits a user-run administrator command; no collected archive means no phone provider/hit-test conclusion. No new phone build/install/launch, broad rerun or merge is part of this checkpoint.++The final bounded Files setup inventory completed one method, make exit0, at `/tmp/pr105-drop-diagnostic-native-cache/Logs/Test/Test-Asterism Development-2026.10.13_09-18-39-+1100.xcresult`. A label-based Save to Files cell was tapped, but inspected post-action screenshots still show the share sheet; no native save picker, actual Files file or Files drag was established. This is an inventory receipt, not Files acceptance. No further preparation loop follows.
diff --git a/specs/cover-image-drop/smolspec.md b/specs/cover-image-drop/smolspec.mdnew file mode 100644index 00000000..36e5643d--- /dev/null+++ b/specs/cover-image-drop/smolspec.md@@ -0,0 +1,41 @@+# Cover image drop — T-2433++## Overview+A reader can drop an image file onto the Cover field in a work editor, including when automatic cover scanning cannot find artwork. Dropping is another local image source for the existing crop, draft and Save flow. Existing cover menu actions remain available for keyboard and assistive-technology use.++## Requirements+- The system MUST accept a dropped local image file or image representation on the work editor's Cover field on supported macOS/iPad/iPhone drag-and-drop surfaces.+- Every accepted image MUST enter the existing crop step before replacing the cover draft. Only the existing work Save commits it; crop cancellation and work Cancel preserve saved content.+- A drop MUST NOT modify a read-only work, a work outside editing mode, or a work whose Save is submitting. Results arriving after Cancel, navigating away, leaving edit mode, Save or a newer pick/drop MUST be discarded.+- Invalid, unreadable or unsupported images MUST leave the current draft unchanged and show the existing file-source failure guidance when an image/file drop was accepted for loading.+- A local file URL MUST be read within its granted access/lifetime. A provider's temporary file MUST be consumed before its callback returns. Remote URL/text drops MUST NOT initiate network fetches.+- Supported formats MUST match the existing file picker: JPEG, PNG, HEIC, GIF and WebP. Try supported image representations before a provider's local-file representation; if one representation fails, try its remaining eligible representations before moving to the next provider.+- Reject unsupported/remote-only drops without changing crop, session or guidance. An accepted image/file drop supersedes the previous in-flight image session, but retains the current draft until a new crop is confirmed.+- One drop MUST select at most one image, using the first decodable supported image in provider order. Keep failures silent while trying later candidates; if all accepted candidates fail, show “That file could not be read as an image.” The existing 2,400-pixel working-image limit, portrait 2:3/square 1:1 crop shapes, encoding, stored bytes and draft retention on Save refusal MUST remain unchanged.+- The Cover field SHOULD indicate that it accepts image drops while a supported drag is over it; its existing label, menu and accessibility identity MUST remain usable.++## Implementation Approach+- Extend `Asterism/Asterism/Views/WorkDetailView.swift`'s existing `coverField` with a drop target scoped to that field. Register image and local-file representations; retain the menu and `WorkThumbnailPresentations` crop sheet.+- Retire the drop/pick session explicitly when the work page disappears: current `WorkThumbnailPresentations.onDisappear` cancels cover fetching only and does not invalidate the thumbnail token. Recheck editing/read-only/session state after every asynchronous load.+- Add a small internal adapter to `Asterism/Asterism/ViewModels/WorkDetailModel.swift` for `NSItemProvider` image/file input. Reuse `beginThumbnailPick`, `acceptPickedImage(... source: .file)`, `pendingCrop` and `acceptCroppedThumbnail` with session-token and editor/read-only/`isSubmitting` guards. The model owns these checks because its submission flag is private.+- Reuse `Asterism/Asterism/Support/PlatformModifiers.swift`'s security-scoped, off-main local-file read pattern. Materialise file-representation bytes inside the provider callback's lifetime; do not retain its temporary URL for later reads.+- Do not call `acceptPastedProviders` unchanged: its URL/text fallback fetches network content. Drops only read local images.+- Extend `Asterism/AsterismTests/WorkDetailThumbnailTests.swift` with valid image and local-file provider fixtures, multiple-provider ordering, nonimage/remote URL rejection, delayed-provider results after navigation and during Save, stale failure messages, an undecodable first representation/provider followed by a valid one, crop Cancel and Save/Cancel persistence boundaries. Use the established isolated library/model fixtures.+- Add one focused rendered drop-to-crop journey on a supported simulator/native test host if its existing drag API can supply a real image provider. Verify target/highlight and crop rendering without opening an existing Mac library. Model provider checks do not establish rendered drag coverage; record any actual harness limit explicitly.+- If an automated host cannot deliver an actual native file drag, leave that rendered subpart open for a manual drag check using an isolated Development library and disposable Mac preference domain; do not launch the reader's existing Mac library. Intended surfaces are Mac file drag and iPad Files drag; the shared iPhone input adapter remains compatible where the OS can originate a drag.+- Dependencies: existing thumbnail codec/source/crop/draft/repository pipeline, native Uniform Type Identifiers and item providers. No new package, stored schema, archive, site policy or network capability.+- Out of Scope: changing cover scanning, crop UI, artwork storage, other drop targets, dropping web links to fetch covers, camera import, deployment and merge.++## Risks and Assumptions+- Risk: Finder/Files exposes a file URL rather than image bytes. Mitigation: support local-file representations as well as image types; reject remote links without fetching.+- Risk: asynchronous loading races with editing cancellation or a newer cover. Mitigation: capture the existing pick token and recheck editor/read-only/session state before publishing crop or guidance.+- Risk: temporary/security-scoped file access expires. Mitigation: consume temporary files in their callback and balance scoped access around off-main reads.+- Risk: UI harness cannot initiate a real external image-file drag. Mitigation: exercise actual providers in native model tests and report rendered coverage limits rather than claiming an injection equals a drag.+- Assumption: a dropped image has the same crop and Save semantics as a chosen image, settled by `specs/work-thumbnails/requirements.md` sections 2, 3 and 5.++## Escalation Note+This change was scoped as a smolspec. If implementation reveals ambiguity only the user can resolve, an irreversible boundary (public API, persisted schema, auth path), or a contested architectural choice, stop and escalate to the full spec workflow rather than deciding it inline.++## Native iOS routing correction — 2026-10-13++Keep the existing List, Cover field, Menu, accessibility identity and crop UI. `CoverDropTarget` overlays a transparent UIKit `UIDropInteraction` surface over the existing field on iOS; macOS retains the original SwiftUI `onDrop`. The surface forwards ordinary public touch, keyboard and pointer event types to the Menu and permits UIKit interaction targeting through its public hit-test override. It checks the shared model admission predicate and editor state, then forwards providers to unchanged `beginCoverDrop`. No schema, decoder, crop/draft/Save/Cancel policy or network capability changes.
diff --git a/specs/cover-image-drop/tasks.md b/specs/cover-image-drop/tasks.mdnew file mode 100644index 00000000..69718766--- /dev/null+++ b/specs/cover-image-drop/tasks.md@@ -0,0 +1,16 @@+---+references:+ - specs/cover-image-drop/smolspec.md+ - specs/cover-image-drop/decision_log.md+metadata:+ status: authorised+---+# T-2433 cover image drop tasks++- [x] 1. Dropped image and local-file providers enter crop safely and preserve drafts on invalid/stale input.+ - Cover real image/local-file providers, ordering, undecodable-first then valid-second fallback, unreadable/nonimage/remote URL input, stale sessions after page disappearance, in-flight Save, read-only and editing guards with focused native tests.+ - References: [smolspec](smolspec.md)+- [x] 2. The editor Cover field accepts supported drops through the existing crop and Save/Cancel flow.+ - Retain menu accessibility; verify drop target wiring and crop/Save/Cancel persistence in the existing isolated harness, recording actual rendered drag limitations.+ - References: [smolspec](smolspec.md)+ - Actual external file-drag delivery on Mac/iPad remains a documented acceptance subpart; provider, compile/native and downstream crop UI checks passed. Evidence: [implementation.md](implementation.md).
diff --git a/specs/url-optional-chapter-notes/decision_log.md b/specs/url-optional-chapter-notes/decision_log.mdindex b3a34438..81277aca 100644--- a/specs/url-optional-chapter-notes/decision_log.md+++ b/specs/url-optional-chapter-notes/decision_log.md@@ -26,6 +26,7 @@ Status: approved for implementation at reviewed package `198b65ab`, with direct | Q18 | 2026-10-11 | Untitled spine rows start content at the normal first line | Owner reports residual reserved title space; date and rating remain visible | | Q19 | 2026-10-11 | Reliable title chapter numbers are presentation-only gutter hints | Reuse existing prefix parser/style; preserve authored titles and explicit choices without changing identity, sorting, citations or progress | | Q20 | 2026-10-11 | Group the work default and notes in one aligned editor card | Owner screenshot shows a separate clipped Form row; restore existing editor styling without changing capture behavior |+| Q21 | 2026-10-12 | Remove detected-chapter correction from the share sheet entirely | Owner rejects correction behind Chapter options; preserve required choices and post-save Entry Detail correction | ## Decision 1: Entry UUID identity separated from source pages @@ -218,3 +219,14 @@ Use the existing chapter-number gutter typography and `ChapterKeyDerivation` pre ## Work-editor layout feedback The owner reported that “Pages usually contain” was misaligned and in its own cut-off section, then explicitly requested deployment after fixing it. The supplied screenshot was materialised through the current Library workflow and its actual pixels inspected. The picker rendered as an unstyled standalone native Form row above the separately styled Notes field. Group both in the existing Notes VStack/card/list-row shape, retaining placement, menu binding, accessibility identifier and Save/Cancel semantics. This restores the approved editor alignment without a new product decision or change to the work default. Strengthen the existing exact work-default Save/Cancel/reset journey with full-window visibility and matching field-edge assertions; retain the genuine failed result and inspect the corrected phone capture.+++## Q21 — Remove detected-chapter correction from sharing entirely++**Date:** 2026-10-12. **Status:** Accepted; supersedes share correction placement in Q5 and the T-2436 report Q4.++**Context:** The owner tested standalone PR105 `beb8e6d6` and rejected the Chapter options menu because it still exposes Correct detected chapter. The requirement is absence from the share sheet, rather than collapsed presentation.++**Decision:** Remove that action and its sole-purpose wrapper and correction state from the common share chapter-choice view. Both share branches retain required conflicting/incomparable/new-chapter choices and content-resolution decisions. Correction remains in post-save Entry Detail editing; repository corrected intents remain available for that flow. No schema, migration, identity or matching change follows.++**Verification:** A focused whole-view source reach guard covers all conditional/expanded branches and both call sites; resolver regressions retain automatic capture and required-selection behavior. Source checks do not replace rendered incoming-share acceptance.
diff --git a/specs/url-optional-chapter-notes/design.md b/specs/url-optional-chapter-notes/design.mdindex ba3bad4a..956a3c69 100644--- a/specs/url-optional-chapter-notes/design.md+++ b/specs/url-optional-chapter-notes/design.md@@ -57,7 +57,7 @@ No mode change restricts capture. Strong evidence wins in either default. The ed 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.+The share sheet retains only separately required chapter selection without discarding note/rating; detected-chapter correction is absent from every share menu and expanded choice. After Save, EntryDetail offers 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. @@ -109,3 +109,8 @@ During development run affected Core suites using `make test-core CORE_TEST='… ## 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.+++## Share correction placement — owner correction, 2026-10-12++Both new and saved-page share branches retain `ChapterCaptureChoicesView` only for required ambiguous/new-chapter selection and optional unidentified-page alternatives. It never renders a detected-chapter correction action, menu, correction form or corrected intent, including after expanding choices. Correction belongs to the saved Entry Detail editor. Existing/new chapter and generic-note choices keep their existing selection, content-resolution and Save behavior; stored correction provenance and post-save correction transactions remain unchanged. This supersedes earlier pre-save share-correction placement.
diff --git a/specs/url-optional-chapter-notes/requirements.md b/specs/url-optional-chapter-notes/requirements.mdindex 7ad2d029..75dd6ea0 100644--- a/specs/url-optional-chapter-notes/requirements.md+++ b/specs/url-optional-chapter-notes/requirements.md@@ -42,7 +42,7 @@ Asterism should let the reader record a work and their reactions regardless of w **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. +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”. The share sheet SHALL NOT expose “Correct detected chapter”, directly or inside any menu or expanded choices; chapter correction SHALL remain available through post-save Entry Detail editing. 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. @@ -56,7 +56,7 @@ Asterism should let the reader record a work and their reactions regardless of w 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. +5. <a name="4.5"></a>WHEN the reader corrects a detected chapter in post-save Entry Detail editing, 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@@ -72,7 +72,7 @@ Asterism should let the reader record a work and their reactions regardless of w | 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 |+| Ordinary serial | Taught page identifies chapter 12; share it twice | Create then update chapter 12; “Add another chapter” hidden; correction available after Save in Entry Detail | | 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 |@@ -86,7 +86,7 @@ Asterism should let the reader record a work and their reactions regardless of w | Saved note metadata | Open a manual note for editing, rename/clear its title and add/change/clear its URL; try invalid URL and Cancel | Same note identity; accepted values survive Save/reopen; invalid input retains all drafts, Cancel leaves saved values untouched | | Manual source input | Save `example.com/story`, explicit HTTPS/HTTP, then clear; try malformed or unsupported input | Scheme-less input saves as `https://example.com/story`; explicit valid addresses preserve their scheme; blank clears; invalid input explains the accepted form, retains drafts and saved data | | 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 |+| Incorrect detection | Rule says 12; reader saves, then corrects to 13 in Entry Detail | Saved entry corrected 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 |
All expected phone identities are accounted across original32, timed-out186 and exact remaining9. The two failure retries are separate. The interrupted canceled case is an explicit non-executed placeholder in JUnit; header totals are run records, not unique tests. Two M4 skips remain. The bounded continuation has raw-log evidence because its xcresult Info.plist is absent. Final tail11 is Failed with one alias-chip failure; no green full-UI verdict.
No physical-device installation, Mac runtime rendering or live CloudKit delivery test. Existing backup/schema formats and PR105/106 remain unchanged.
All owned commands drained and both dedicated simulators are Shutdown; no queued tests. Initial pressure readings improved at release but remain high. No unrelated process or shared service was changed.
Fresh local-review found no blocker on45242dba. Four nonblocking observations are retained above; no source changed after review or passing checks.