asterism branch T-2366/to-read-capture-match commits 25 files 50 touched lines +6183 / -116

Pre-push review: T-2366/to-read-capture-match

To-read capture match: derive to-read/captured pairs in Today's publication, confirm through a .toReadMatch merge, or decline as synced distinct pairs.

At a glance

  • All 16 spec tasks implemented; decisions Q38–Q56 record every divergence from the design.
  • Core-only derivation (~18 ms on M4), invisible on Today publication (0.904 s vs 0.896 s).
  • The merge reuses the ordinary engine through a request flag and a post-fold overlay; no schema change.
  • This review round: shared refusal, quarantine and series helpers; isCandidate narrowed; Req 4.6 now invalidates at the first stale confirm; two new tests (Req 3.3 through the real merge, Req 4.2 field equality).
  • Open for the owner: the Elsewhere row wording is the same for every item (Q24).

Verdict

Ready to push

74 failing tests, all in the pending-capture suites, which fail identically on the base commit bbdcd8b6 (environmental EPERM).

The four reviewers found no major problems. Their minor findings are fixed in f2c7f587 and 1549f29a, including the Req 4.6 first-confirm invalidation. The Core run's only failures are the three pending-capture suites, which fail the same way on the base commit bbdcd8b6 (EPERM on spool files, environmental). make test-quick passed 1,859 tests and DuplicateResolutionUITests passed 11/11.

Review findings

16 raised · 13 fixed · 3 skipped

Jump to findings →

Tests

Pass rate: 98% (3096 of 3170)

New tests: 103

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

What changed

A story you add to To Read and later capture from a browser used to end up as two separate works. The app now notices when a new capture looks like one of your to-read works: Today's duplicate banner counts it, a row under Elsewhere says May belong to a story in To Read, and the work's row in Works gets a To Read? pill.

Tapping either opens a card that asks whether it is the same story. Picking one shows a merge preview, and confirming makes the two works one. None of these records that they differ, and the app never asks about that pair again.

Why it matters

The to-read list stops filling with stale entries. The merge keeps the to-read entry's identity and takes what the capture learned: the real title, and the fact that you are now reading it. A title you had typed yourself goes into the notes rather than being lost.

Key concepts

  • Match: a shared site, plus the same story address from the site's URL rule, or titles that agree once case, accents and punctuation are ignored.
  • Merge: every page moves into the folder you keep, and the empty one is thrown away.
  • Decline: a synced note saying these two are different.

Architecture

ToReadMatcher derives pairs inside every Today publication, from synced content only, and publishes them as toReadMatches on DuplicateWorkload. They are never stored, never scanned and never reconciled. A decline is an ordinary synced WorkDistinctPair, written N at a time by recordDistinctPairs.

Confirming reuses the ordinary merge with WorkMergeRequest.toReadMatch. A post-fold overlay in the planner decides:

  • title and provenance;
  • reading and work status;
  • verdict and release days.

The commit writes WorkMergeRawOverrides verbatim to every target row and re-checks isCandidate under the lock.

Patterns

  • Derived, not stored.
  • The to-read side is indexed first, with an early return.
  • Title candidates come from one first-word bucket (Q41).
  • Blocked choices are shown with their reason, not hidden.
  • The card and the commit share quarantinedHostnames and areInDifferentSeries, so they cannot disagree.

Trade-offs

  • Recompute every publication: about 18 ms, with no cache to keep in sync.
  • Re-check at commit: about 0.22 s under the exclusive lock, so a decline or edit that lands behind an open preview cannot be merged through.
  • Conservative prefix rule: a missed match is preferred to a wrong one.

Deep dive

Normalisation (Q27, amended by Q44):

  1. NFKD, then a locale-free full fold, then NFKD again.
  2. Drop Mn and Cf.
  3. Turn P and S into spaces.
  4. Collapse whitespace with M2Unicode.isWhitespace.

Words split on the U+0020 scalar, so a space followed by a combining or joiner scalar still separates words. A leading article is skipped only for the length floor.

Exclusion (Q38): a pair is excluded while either work is in any work set that publishes an item, that is members.count > 1 or a classification other than .silentlyResolvable. A converged single-work split never suppresses matching.

Commit order for .toReadMatch:

  1. A stale basis first re-checks isCandidate, then returns .invalidated or a .refreshed that still carries the request (Q53).
  2. The torn refusal.
  3. The quarantine refusal, through the shared helper.
  4. isCandidate.
  5. Write-before-delete.
  6. Value-guarded raw overrides.

Architecture impact

A second kind of item on the workload. reviewCount, isEmpty and allItems are unchanged. The merge contract carries its request end to end. No schema, marker or archive change.

Edge cases to watch

  • A whole-word prefix match on sites without a URL rule.
  • A survivor routed to the originating stack only (Q47).
  • The re-check's lock time at library sizes well beyond M4.
  • UI tests that duplicate the fixture's UUIDs (Q50).

Important changes — detailed

ToReadMatcher: normalisation, pairs, candidates, isCandidate

Packages/AsterismCore/Sources/AsterismCore/ToReadMatcher.swift

Why it matters. The whole matching rule lives here; it runs on every Today publication and again under the commit lock.

What to look at. ToReadMatcher.swift: normalise, titlesMatch, pairs, candidates, isCandidate

Takeaway. Split words on Unicode scalars, not Characters, whenever a separator may be followed by a combining or joiner scalar.
Rationale. Q27/Q44 fix the normalisation order; Q38 the exclusion; Q41 the single first-word bucket; Q54 the narrowed re-check.

Merge commit: request carried end to end, re-check before refresh

Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift

Why it matters. A refresh that dropped the request once turned a to-read confirm into a plain merge; the commit now re-checks the pair before offering a refreshed preview.

What to look at. LibraryRepository+WorkMerge.swift, the stale-basis branch and the isCandidate re-check

Takeaway. When a contract can be refreshed, carry every field that shapes the projection into the refreshed contract.
Rationale. Req 4.6 and Q53.

WorkMergePlanner: toReadMatchOverlay after the fold

Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift

Why it matters. Decides which side wins titles and statuses without touching WorkVariantUnion.fold, so ordinary merges are unchanged.

What to look at. WorkMergePlanner.project and toReadMatchOverlay

Takeaway. Layer a variant's rules after a shared fold instead of branching inside it.
Rationale. Q17 and Q42; the new planner test asserts every non-overlaid field equals the .merge outcome.

ToReadMatchSheet/Model: card and merge phases in one sheet

Asterism/Asterism/ViewModels/ToReadMatchModel.swift

Why it matters. The user-facing flow; cancel is disabled while submitting, and returning from an error refreshes before reloading the card.

What to look at. ToReadMatchModel.swift, ToReadMatchSheet.swift, WorkMergeView onCancel/dismissesOnCommit

Takeaway. Derive a view model's phase from its stored state instead of storing both.
Rationale. Q47, Q49 and Q55.

recordDistinctPairs: N declines in one commit

Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift

Why it matters. A decline must record every listed pair atomically, including blocked ones (Req 5.1).

What to look at. LibraryRepository+DuplicateResolution.swift, recordDistinctPairs

Takeaway. Build the single-item API on the batch one so both share one save boundary.
Rationale. Req 5.1 and Q25; a self-pair refuses the whole batch before anything is written.

Key decisions

Derived in Today's publication, never stored.

Pairs come from synced content on every publication, so devices agree without coordination and the scan and reconcile never see them (Req 1.1, 1.3).

Exclusion follows publishing work sets.

Q38: exclude a pair while either work is in a set that publishes an item; a converged one-member split does not suppress matching.

Format characters dropped, words split by scalar.

Q44 amends Q27, so titles with LRM, ZWSP, a soft hyphen or ZWJ emoji match.

Invalidate at the first stale confirm.

Q53: a stale .toReadMatch confirm re-checks the pair before refreshing, so the reader is told at once (Req 4.6).

Narrowed commit-time re-check.

Q54: workSets stay library-wide, but pairs receives only the pair's two works.

No derivation ceiling below the budget.

Q52: the fixture already runs the single-bucket worst case, so a sub-budget ceiling caught nothing it claimed to catch.

LibraryNotOpen kept as a known duplicate.

Q56: it duplicates LibraryRepositoryError.libraryUnavailable, but a test pins the type.

Review findings

SeverityAreaFindingResolution
minorRefusal wordingToReadMatchModel.blockedMessage copied WorkMergeModel's refusal strings.Shared WorkMergeModel.refusalMessage(for:).
minorQuarantine ruleMatcher and commit each computed the quarantined hostnames.Shared LibraryRepository.quarantinedHostnames(of:in:).
nitSeries conflictRule written three times.SeriesMembership.areInDifferentSeries used by all three.
minorisCandidate costBuilt every group and ran pairs over the whole library for one pair.Pairs narrowed to the two works; declined pair returns early (Q54).
minorisCandidate faultsCold context faults siteMemberships per work.Prefetching unmeasured; left for a measured change.
minorRedundant releaseDaysRawPassed a value the snapshot already holds.Argument dropped; the default supplies it.
minorToReadMatchModel.phaseStored phase duplicated mergeModel and item.Computed phase; dead .merging branch removed.
minorWorkMergeView dismissalonCancel also decided dismiss-on-commit.Separate dismissesOnCommit flag (Q55).
minorLibraryNotOpenDuplicates LibraryRepositoryError.libraryUnavailable.Kept; a test pins the type (Q56).
minorRequest without preset.toReadMatch without presetTargetID was representable.Precondition in WorkMergeModel.init.
minorReq 4.6 two-tapA stale confirm that also ended the pairing refreshed first and invalidated only on the second confirm.Re-check before refresh (Q53); the one test that accepted the two-step flow updated.
minorReq 3.3 testHand-seeded the survivor instead of running the merge.New test through projectMerge + commitMerge.
nitReq 4.2 testNo check that non-overlaid fields equal an ordinary merge.New reflective planner test.
minorDocsCHANGELOG claimed reading status survives; Req 4.1, design.md, testing.md counts stale.All corrected; CLAUDE.md gains the whole-target medians.
nitUI test tap loopHand-rolled scroll-and-tap instead of tapReviewControl.Test-only change without a bug; left.
nitSheet nitsIdentifier set twice, redundant parameter, no-op guard, public isPrefixMatch, fixture magic number.All tidied.

Tests

Source: local run at 2026-09-24T01:49:00+10:00 · snapshot 1549f29a74e2ac2a6ac410980f38d84bcabbc0ef

Baseline: none

Execution: failed · JUnit: 1 file · Coverage: none · Baseline: absent

Coverage scope: every test in the repository

Totals: 3096 passed · 74 failed · 53 skipped · 0 errored · 0 flaky

Failed tests

SuiteTestJob or artifactMessage
AsterismCoreTests.PendingCaptureSpoolTestsstagedFilesAreNeverEnumerated()—Expectation failed: waiting.count == 1 (error)
AsterismCoreTests.PendingCaptureSpoolTestspreservingIgnoresTheLibraryAndItsLock()—Expectation failed: counts.waiting == 1 (error)
AsterismCoreTests.PendingCaptureSpoolTestsscavengingSparesAConcurrentPublish()—Expectation failed: try await spool.pending().count == 1 (error): // And the published record is untouched by any of it.
AsterismCoreTests.PendingCaptureSpoolTestsaRecordWithoutTheHoldFieldStillDecodes()—Expectation failed: try contents(of: paths.pendingCapturesPendingURL).first (error)
AsterismCoreTests.PendingCaptureSpoolTestsreleasingTheHoldRestoresDrainability()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsoversizedFieldsAreTruncated()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTeststiesBreakOnRecordIdentity()—Expectation failed: waiting.count == 5 (error)
AsterismCoreTests.PendingCaptureSpoolTestsenumerationSortsOnDecodedValues()—Expectation failed: waiting.map(\.providerURL) == [ "https://example.com/0", "https://example.com/60", "https://example.com/120", "https://example.com/180", "https://example.com/240", ] (error)
AsterismCoreTests.PendingCaptureSpoolTestsrefusalsAreBoundedAndDoNotCountTowardsTheArea()—Expectation failed: refusals.count == PendingCaptureBounds.maxRefusalRecords (error)
AsterismCoreTests.PendingCaptureSpoolTestsanAttemptRewriteDoesNotResurrectADeletedRecord()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsonlyTerminationsAccumulate()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsaRecordNeverExceedsItsDeclaredMaximum()—Expectation failed: try contents(of: paths.pendingCapturesPendingURL).first (error)
AsterismCoreTests.PendingCaptureSpoolTestsdeleteRemovesOneRecord()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsaHeldRecordStillCountsAsWaiting()—Expectation failed: counts.waiting == 1 (error)
AsterismCoreTests.PendingCaptureSpoolTestssettingAsideADeletedRecordResurrectsNothing()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsonlyTheReaderDeletesASetAsideRecord()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestssettingAsideIsIdempotent()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsanObservedOutcomeReleasesItsAttempt()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestspreserveReportsWaitingAndSetAsideSeparately()—Expectation failed: counts.waiting == 2 (error): // Req 2.3's copy names the captures waiting to be added; a set-aside // record is not one of them, and only the reader can clear it.
AsterismCoreTests.PendingCaptureSpoolTestsaRefusalIsRecordedAndNothingIsDiscarded()—Expectation failed: try contents(of: paths.pendingCapturesPendingURL).first (error)
AsterismCoreTests.PendingCaptureSpoolTeststheBoundHoldsSequentially()—Caught error: Error Domain=NSCocoaErrorDomain Code=257 "The file “D81E2CC8-E864-429F-B36C-0D9F885E059A.json” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/pending-capture-spool-BA63729D-9612-4B25-804E-57986C64843D/PendingCaptures/quarantine/D81E2CC8-E864-429F-B36C-0D9F885E059A.json, NSURL=file:///private/var/folders/11/v0tnfm294kd9c6zll_ncmpkh0000gn/T/pending-capture-spool-BA63729D-9612-4B25-804E-5…
AsterismCoreTests.PendingCaptureSpoolTestsanObservedFailureDefersTheRecord()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsfilesInheritProtectionFromTheirDirectory()—Expectation failed: try contents(of: paths.pendingCapturesPendingURL).first (error)
AsterismCoreTests.PendingCaptureSpoolTeststheRetryIntervalDefersARecord()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsaNoFaultReleaseDefersNothing()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestssetAsideAndUnreadableAreDistinguishable()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsanUnreadableRecordCarriesNeitherCountNorURL()—Expectation failed: try contents(of: paths.pendingCapturesPendingURL).first (error)
AsterismCoreTests.PendingCaptureSpoolTestsrecordRoundTrips()—Expectation failed: waiting.count == 1 (error)
AsterismCoreTests.PendingCaptureSpoolTeststheSheetHoldDefersARecord()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestsunrecognisedFormatBecomesUnreadable()—Expectation failed: try contents(of: paths.pendingCapturesPendingURL).first (error)
AsterismCoreTests.PendingCaptureSpoolTestsanOversizedFileIsUnreadableWithoutBeingRead()—Expectation failed: waiting.map(\.providerURL) == ["https://example.com/healthy"] (error): // The healthy record is untouched; the oversized one is quarantined // under the identity its filename declared, so the reader can delete // it (Req 6.11).
AsterismCoreTests.PendingCaptureSpoolTeststheSpoolLivesBesideTheStore()—Expectation failed: try contents(of: paths.pendingCapturesPendingURL).count == 1 (error)
AsterismCoreTests.PendingCaptureSpoolTestsanAttemptClearsTheHold()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTeststheAttemptLimitIsReachedAndSetAside()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureSpoolTestssetAsideRecordsDoNotBlockAdmission()—Expectation failed: try await spool.pending().first (error)
AsterismCoreTests.PendingCaptureDrainTestsanOpenShareSheetDoesNotBecomeAnEntry()—Expectation failed: waiting.map(\.id) == [preservedID] (error)
AsterismCoreTests.PendingCaptureDrainTestsnoTitleAndNoNetworkWaits()—Expectation failed: try await fixture.spool.pending().first (error)
AsterismCoreTests.PendingCaptureDrainTeststheAttemptLimitSetsARecordAside()—Expectation failed: try await fixture.spool.pending().first (error)
AsterismCoreTests.PendingCaptureDrainTestsaBlankSafariTitleIsTerminal()—Expectation failed: report.setAside == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsaCommittedRecordAtTheLimitIsDeleted()—Expectation failed: try await fixture.spool.pending().first (error)
AsterismCoreTests.PendingCaptureDrainTestsaSheetCommitCarriesThePreservedID()—Expectation failed: try await fixture.spool.pending().first (error)
AsterismCoreTests.PendingCaptureDrainTestsaRecordDeletedMidPassIsNotResurrected()—Expectation failed: try await fixture.spool.pending().first { $0.providerURL == "https://ex.com/read/2" } (error)
AsterismCoreTests.PendingCaptureDrainTestsaSaveFailureDoesNotStopTheDrain()—Expectation failed: report.newEntries == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsaDrainedRowLeavesTheSetUnchanged()—Expectation failed: report.newEntries == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsrequestsDuringAPassCoalesce()—Caught error: .neverEntered (error)
AsterismCoreTests.PendingCaptureDrainTestsaDrainedCapturePromotesAToReadWork()—Expectation failed: report.newEntries == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsaRecentlyAttemptedRecordIsDeferred()—Expectation failed: try await fixture.spool.pending().first (error)
AsterismCoreTests.PendingCaptureDrainTestsaPersistedCommitIsNotRepeated()—Expectation failed: fixture.entries().count == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsanUnusableURLIsSetAsideImmediately()—Expectation failed: report.setAside == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsanUnavailableLibraryStopsThePass()—Expectation failed: waiting.count == 2 (error)
AsterismCoreTests.PendingCaptureDrainTestsoverlappingDrainsSerialise()—Caught error: .neverEntered (error)
AsterismCoreTests.PendingCaptureDrainTestsaFailingRecordDoesNotStarveTheTail()—Expectation failed: try await fixture.spool.pending().last (error)
AsterismCoreTests.PendingCaptureDrainTestsshareOrderDecidesWhichCreatesTheEntry()—Expectation failed: report.newEntries == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsaPassIsBoundedAtTwentyFiveRecords()—Expectation failed: first.newEntries == PendingCaptureBounds.recordsPerDrainPass (error)
AsterismCoreTests.PendingCaptureDrainTestsaMultiGroupMatchCreatesANewEntry()—Expectation failed: try await fixture.spool.pending().first?.id (error)
AsterismCoreTests.PendingCaptureDrainTestsunreadableAndRefusedRecordsAreReported()—Expectation failed: report.refused.map(\.providerURL) == ["https://ex.com/refused"] (error)
AsterismCoreTests.PendingCaptureDrainTestspreservedCaptureBecomesAnEntry()—Expectation failed: try await fixture.spool.pending().first?.id (error)
AsterismCoreTests.PendingCaptureDrainTestsaPassIsBoundedInTime()—Expectation failed: first.newEntries >= 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsaTornMatchCreatesANewEntry()—Expectation failed: try await fixture.spool.pending().first?.id (error)
AsterismCoreTests.PendingCaptureDrainTestsrulesInForceAtCommitTimeAreUsed()—Expectation failed: report.newEntries == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsaPreservedRecordSurvivesUntilALaterPass()—Expectation failed: report.newEntries == 1 (error)
AsterismCoreTests.PendingCaptureDrainTeststheCallerSuppliesTheBudget()—Expectation failed: drained.newEntries == 1 (error)
AsterismCoreTests.PendingCaptureDrainTestsaDrainedReShareDoesNotPromote()—Expectation failed: report.recordedAgainstExisting == 1 (error)
AsterismCoreTests.ShareCaptureFlowTestsdeleteIsRetriedOnceThenGivesUp()—Expectation failed: await spool.discardPreserved(id: Self.recordID) == false (error)
AsterismCoreTests.ShareCaptureFlowTestsconfirmationEscalates()—Expectation failed: message.contains("\(PendingCaptureBounds.escalationThreshold) captures are waiting") (error)
AsterismCoreTests.ShareCaptureFlowTeststerminationLeavesTheRecord()—Expectation failed: waiting.map(\.id) == [preservedID] (error)
AsterismCoreTests.ShareCaptureFlowTestsescalationCountsSetAsideButNamesWaiting()—Expectation failed: message.contains("5 captures are waiting") (error): // Waiting is 4 already held plus the one just preserved; the sum with // the 21 set aside is what escalates. Asking the reader to open the // app for 25 would be asking them to clear captures opening the app // cannot clear.
AsterismCoreTests.ShareCaptureFlowTeststheHoldLapses()—Expectation failed: try await reopened.pending().first (error)
AsterismCoreTests.ShareCaptureFlowTestseveryFailedOpenArmSavesForLater(failure:)—Expectation failed: waiting.map(\.id) == [preservedID] (error)
AsterismCoreTests.ShareCaptureFlowTestsaLiveSheetHoldsItsRecord()—Expectation failed: try await reopened.pending().first (error)
AsterismCoreTests.ShareCaptureFlowTeststheHoldIsStampedBeforeTheOpen()—Expectation failed: try await reopened.pending().first (error)
AsterismCoreTests.ShareCaptureFlowTestsrefusalAtTheBoundIsNotSaved()—Expectation failed: waiting.count == 1 (error)
AsterismCoreTests.ShareCaptureFlowTestspreservesBeforeOpening()—Expectation failed: waitingAtOpen == 1 (error)
AsterismCoreTests.ShareCaptureFlowTestsaFailedOpenLeavesItsRecordDrainable()—Expectation failed: try await reopened.pending().first (error)

New and removed tests

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

Blast radius

Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base bbdcd8b68a71e196a95f4bc3b71e18ac6612a041.

Dependents none found Changed Dependencies none found . Asterism/Asterism Asterism/Asterism/Layout Asterism/Asterism/ViewModels Asterism/Asterism/Views Asterism/AsterismTests Asterism/AsterismTests/Helpers Asterism/AsterismUITests …rismCore/Sources/AsterismCore …mCore/Tests/AsterismCoreTests MakefileMakefile Asterism/Asterism/ContentView.swift…sm/Asterism/ContentView.swift Asterism/Asterism/Layout/AppNavigation.swift…sm/Layout/AppNavigation.swift Asterism/Asterism/Layout/AppScreens.swift…erism/Layout/AppScreens.swift Asterism/Asterism/ViewModels/AppLibraryModel.swift…wModels/AppLibraryModel.swift Asterism/Asterism/ViewModels/ToReadMatchModel.swift…Models/ToReadMatchModel.swift Asterism/Asterism/ViewModels/WorkMergeModel.swift…ewModels/WorkMergeModel.swift Asterism/Asterism/Views/ToReadMatchSheet.swift…/Views/ToReadMatchSheet.swift Asterism/Asterism/Views/TodayView.swift…sterism/Views/TodayView.swift Asterism/Asterism/Views/WorkMergeView.swift…ism/Views/WorkMergeView.swift Asterism/Asterism/Views/WorksView.swift…sterism/Views/WorksView.swift Asterism/AsterismTests/DuplicateSurfaceTests.swift…s/DuplicateSurfaceTests.swift Asterism/AsterismTests/ToReadMatchModelTests.swift…s/ToReadMatchModelTests.swift Asterism/AsterismTests/WorkMergeModelTests.swift…sts/WorkMergeModelTests.swift Asterism/AsterismTests/Helpers/MockLibraryProvider.swift…ers/MockLibraryProvider.swift Asterism/AsterismUITests/AccessibilityJourneyUITests.swift…ssibilityJourneyUITests.swift Asterism/AsterismUITests/DuplicateResolutionUITests.swift…licateResolutionUITests.swift Asterism/AsterismUITests/UIJourneySupport.swift…ITests/UIJourneySupport.swift Asterism/AsterismUITests/WideLayoutUITests.swift…Tests/WideLayoutUITests.swift Packages/AsterismCore/Sources/AsterismCore/DuplicateWorkload.swift…mCore/DuplicateWorkload.swift Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift…smCore/LibraryProviding.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift…ory+DuplicateResolution.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift…itory+TodayPresentation.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift…aryRepository+WorkMerge.swift Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swift…re/M4PerformanceFixture.swift Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift…Core/ProjectionContract.swift Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift…erismCore/SeriesSupport.swift Packages/AsterismCore/Sources/AsterismCore/ToReadMatcher.swift…erismCore/ToReadMatcher.swift Packages/AsterismCore/Sources/AsterismCore/ToleratedStateFixture.swift…e/ToleratedStateFixture.swift Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift…smCore/WorkMergePlanner.swift Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift…sSiteDuplicateScanTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift…eDuplicateWorkloadTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift…plicatePublicationTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/M4ToReadMatchScalePerformanceTests.swift…chScalePerformanceTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift…/MultiSiteReadPathTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift…ests/ToReadMatcherTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift…s/WorkMergePlannerTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeSeriesLinkTests.swift…orkMergeSeriesLinkTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift…rkMergeToReadMatchTests.swift
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

50 files: 39 code · 11 docs. Click to expand.

Code (39)

Asterism/Asterism/ContentView.swift Modified +12 / -0
diff --git a/Asterism/Asterism/ContentView.swift b/Asterism/Asterism/ContentView.swiftindex 9fb49898..b3160439 100644--- a/Asterism/Asterism/ContentView.swift+++ b/Asterism/Asterism/ContentView.swift@@ -647,6 +647,18 @@ struct ContentView: View {                     DuplicateResolutionView(model: resolutionModel)                 }             }+            // `to-read-capture-match` Q23, Q30: the to-read card, beside the+            // resolution sheet so both trees share it. A committed merge closes+            // it and shows the survivor on the stack that opened it.+            .sheet(item: $navigation.presentingToReadMatch) { presented in+                if let matchModel = model.toReadMatchModel(for: presented.capturedWorkID) {+                    ToReadMatchSheet(+                        model: matchModel,+                        onCommitted: {+                            navigation.showToReadMatchSurvivor($0, from: presented)+                        })+                }+            }             // No resolve route inside this one. It is presented *from* this view,             // so a sheet it asked for could not present over it — and the Work it             // shows is by definition a Merge route's, which is not torn. The
Asterism/Asterism/Layout/AppNavigation.swift Modified +32 / -0
diff --git a/Asterism/Asterism/Layout/AppNavigation.swift b/Asterism/Asterism/Layout/AppNavigation.swiftindex 202f72a3..a43f52b2 100644--- a/Asterism/Asterism/Layout/AppNavigation.swift+++ b/Asterism/Asterism/Layout/AppNavigation.swift@@ -296,6 +296,10 @@ final class AppNavigation {     /// Works tab's own flow, entered at the set's first member.     var mergingWorkID: PresentedWork? +    /// The to-read card for one captured work (`to-read-capture-match` Q23),+    /// beside the resolution sheet so both trees share it.+    var presentingToReadMatch: PresentedToReadMatch?+     /// The entry a chapter row opened inside the Merge sheet's own stack. Its     /// own state, because that stack is not the Works tab's.     var mergeSheetEntryID: UUID?@@ -614,6 +618,26 @@ final class AppNavigation {         }     } +    /// Opens the to-read card for a captured work, remembering which stack+    /// asked so a committed merge shows its survivor there+    /// (`to-read-capture-match` Q30).+    func route(toReadMatch capturedWorkID: UUID, from stack: RouteStack) {+        presentingToReadMatch = PresentedToReadMatch(capturedWorkID: capturedWorkID, stack: stack)+    }++    /// A committed to-read merge: the card closes and the survivor is shown on+    /// the stack the card was opened from — Today's for the Elsewhere row, the+    /// Works tab's for the pill (Q47). `showWork` resets that whole stack to+    /// `[.work(survivor)]`, unlike `replaceWork` after the ordinary Merge,+    /// which swaps only the work on top; whatever that stack held, the+    /// captured work included, is gone. The *other* stack is not cleaned: a+    /// route there to the captured work is the same gap the ordinary Merge+    /// leaves.+    func showToReadMatchSurvivor(_ survivorID: UUID, from presented: PresentedToReadMatch) {+        presentingToReadMatch = nil+        showWork(survivorID, on: presented.stack)+    }+     /// Req 9.2 on a detail screen: the route out of a torn record, or nil where     /// it is in no set the reader can act on.     ///@@ -853,6 +877,14 @@ nonisolated struct PresentedWork: Identifiable, Equatable {     let id: UUID } +/// The to-read card's identity: the captured work it asks about, and the stack+/// that opened it, which is where a committed merge's survivor is shown.+nonisolated struct PresentedToReadMatch: Identifiable, Equatable {+    let capturedWorkID: UUID+    let stack: RouteStack+    var id: UUID { capturedWorkID }+}+ /// A re-teach route waiting for Settings to close, or presented directly. nonisolated struct PendingReteach: Identifiable, Equatable {     let hostname: String
Asterism/Asterism/Layout/AppScreens.swift Modified +7 / -1
diff --git a/Asterism/Asterism/Layout/AppScreens.swift b/Asterism/Asterism/Layout/AppScreens.swiftindex 20665096..02279d38 100644--- a/Asterism/Asterism/Layout/AppScreens.swift+++ b/Asterism/Asterism/Layout/AppScreens.swift@@ -97,6 +97,9 @@ struct AppScreens {             // toolbar opens, where the condition and its remedy are spelled out.             onShowSyncSettings: showSettings,             onResolveDuplicate: resolve,+            // `to-read-capture-match` Q24: the Elsewhere line's card. Opened+            // from Today, so a committed merge shows its survivor on Today.+            onResolveToReadMatch: { navigation.route(toReadMatch: $0, from: .today) },             // Reqs 4.1, 4.3: the day the strip taps and the week the chevrons             // page to, resolved against the day this cycle called current.             onSelectDay: { navigation.selectToday($0, currentDay: model.currentDay) },@@ -217,7 +220,10 @@ struct AppScreens {             // answered on.             onDismissDuplicate: { a, b in                 Task { await model.recordDistinctPair(a, b) }-            }+            },+            // `to-read-capture-match` Req 3.1: the row's pill opens the same+            // card Today's Elsewhere line does.+            onResolveToReadMatch: { navigation.route(toReadMatch: $0, from: .works) }         )     } 
Asterism/Asterism/ViewModels/AppLibraryModel.swift Modified +57 / -1
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex c1ddb7ae..fb3544e3 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -1575,6 +1575,56 @@ public final class AppLibraryModel {         scheduleDuplicateReconcile()     } +    /// The to-read match sheet for one captured work (`to-read-capture-match`+    /// Req 3.2).+    ///+    /// The workload is read live, at the moment the card appears, for the+    /// reason `libraryDiagnosticsModel` reads `pendingConflicts` live: the+    /// sheet outlives the publication it was opened from. A confirmed merge+    /// takes the ordinary merge's follow-through — publish, then schedule the+    /// pass that settles what the merge moved.+    public func toReadMatchModel(for capturedWorkID: UUID) -> ToReadMatchModel? {+        guard let repo = repository else { return nil }+        return ToReadMatchModel(+            capturedWorkID: capturedWorkID,+            library: repo,+            workload: { [weak self] in self?.todayPresentation.duplicateWorkload ?? .empty },+            onMutation: { [weak self] in+                await self?.clearConflicts(resolvedBy: capturedWorkID)+                await self?.refreshDiagnosesAndSnapshots()+                await self?.scheduleDuplicateReconcile()+            },+            decline: { [weak self] item in+                guard let self else { throw LibraryNotOpen() }+                try await self.declineToReadMatch(item)+            },+            refresh: { [weak self] in await self?.refreshDiagnosesAndSnapshots() })+    }++    /// A reader action that needs the library found none open. Thrown rather+    /// than swallowed where the surface would otherwise report success for a+    /// write that never happened — the to-read decline closes its sheet on a+    /// clean return (`to-read-capture-match` Req 5.1).+    nonisolated struct LibraryNotOpen: LocalizedError {+        var errorDescription: String? { "The library isn't open. Nothing was recorded." }+    }++    /// "None of these" (`to-read-capture-match` Req 5.1): every pair the item+    /// lists, blocked ones included, recorded as distinct in one commit.+    ///+    /// Unlike `recordDistinctPair`, a failure is thrown rather than logged: the+    /// sheet the reader answered on stays open and says why. A library that is+    /// not open is a failure too, not a quiet return. And it schedules+    /// no reconcile (Q25) — a distinct pair between two works that share a site+    /// changes no duplicate set, so the pass would be a no-op. The refresh is+    /// what takes the item off Today and the pill off the row.+    public func declineToReadMatch(_ item: ToReadMatchItem) async throws {+        guard let repo = repository else { throw LibraryNotOpen() }+        try await repo.recordDistinctPairs(+            item.choices.map { WorkPairKey(item.capturedWorkID, $0.toReadWorkID) })+        await refreshDiagnosesAndSnapshots()+    }+     /// Provides a model for creating a new work.     public func newWorkModel() -> NewWorkFormModel? {         guard let repo = repository else { return nil }@@ -1847,8 +1897,14 @@ public final class AppLibraryModel {     /// places — the sets by the Recent read, the conflicts by this model — and     /// overlaying them here is what keeps the banner from reporting one moment's     /// sets beside another moment's conflicts.+    ///+    /// `to-read-capture-match` Q29, Q35: plus one per to-read match, an item+    /// whose every choice is blocked included. Added here rather than folded+    /// into `reviewCount`, which Settings and Check Library also read and have+    /// no row for.     public var duplicateBannerCount: Int {-        todayPresentation.duplicateWorkload.reviewCount + pendingConflicts.count+        let workload = todayPresentation.duplicateWorkload+        return workload.reviewCount + workload.toReadMatches.count + pendingConflicts.count     }      /// Records a refused write so the banner and Check Library can carry it.
Asterism/Asterism/ViewModels/ToReadMatchModel.swift Added +177 / -0
diff --git a/Asterism/Asterism/ViewModels/ToReadMatchModel.swift b/Asterism/Asterism/ViewModels/ToReadMatchModel.swiftnew file mode 100644index 00000000..a2921e85--- /dev/null+++ b/Asterism/Asterism/ViewModels/ToReadMatchModel.swift@@ -0,0 +1,177 @@+import AsterismCore+import Foundation+import Observation+import OSLog++/// The to-read match sheet's model (`to-read-capture-match` Reqs 3.2, 4.1,+/// 5.1, Q23, Q30).+///+/// One sheet with two phases. The **card** asks whether a captured work is one+/// of the stories in To Read, with one choice per listed to-read work and "None+/// of these". Choosing a work replaces the card with the ordinary merge preview,+/// preset to that work as the survivor; cancelling the preview brings the card+/// back with nothing written.+///+/// Nothing here writes on its own: the merge commits through `WorkMergeModel`'s+/// confirmation, and the decline is one repository call behind the reader's tap+/// on "None of these".+@MainActor @Observable+public final class ToReadMatchModel {+    private static let logger = Logger(subsystem: "me.nore.ig.Asterism", category: "ToReadMatchModel")++    public enum Phase: Equatable, Sendable {+        case loading+        /// The question and its choices are on screen.+        case card+        /// The merge preview stands in for the card.+        case merging+        /// The item is no longer published: another device answered it, or the+        /// pair stopped matching.+        case resolvedElsewhere+        /// The reader declined and the decline landed; the host closes the sheet.+        case closed+    }++    /// The question the card asks (Req 3.2).+    public static let question = "Is this the same story?"++    public let capturedWorkID: UUID+    public private(set) var item: ToReadMatchItem?+    /// The preview for the chosen to-read work; the phase is `.merging` exactly+    /// while there is one.+    public private(set) var mergeModel: WorkMergeModel?+    /// Whether `load()` has looked the item up at least once.+    private var hasLoaded = false+    /// Whether a decline has landed and the host should close the sheet.+    private var isClosed = false++    /// Derived rather than stored, so it cannot disagree with `item` and+    /// `mergeModel`.+    public var phase: Phase {+        if isClosed { return .closed }+        if mergeModel != nil { return .merging }+        guard hasLoaded else { return .loading }+        return item == nil ? .resolvedElsewhere : .card+    }+    /// Why the last decline did not land. The sheet stays open with it.+    public private(set) var errorMessage: String?+    public private(set) var isDeclining = false++    private let library: any LibraryProviding+    private let workload: @MainActor () -> DuplicateWorkload+    private let onMutation: @Sendable () async -> Void+    private let declineItem: @MainActor (ToReadMatchItem) async throws -> Void+    private let refresh: @MainActor () async -> Void++    /// - Parameters:+    ///   - workload: the workload Today last published, read when the card+    ///     appears and again when the reader comes back to it.+    ///   - onMutation: what a committed merge runs, as every merge does.+    ///   - decline: records every listed pair as declined, in one commit.+    ///   - refresh: re-publishes the diagnoses and snapshots `workload` reads,+    ///     awaited before the card comes back from a failed or refused merge.+    public init(+        capturedWorkID: UUID,+        library: any LibraryProviding,+        workload: @escaping @MainActor () -> DuplicateWorkload,+        onMutation: @escaping @Sendable () async -> Void,+        decline: @escaping @MainActor (ToReadMatchItem) async throws -> Void,+        refresh: @escaping @MainActor () async -> Void+    ) {+        self.capturedWorkID = capturedWorkID+        self.library = library+        self.workload = workload+        self.onMutation = onMutation+        self.declineItem = decline+        self.refresh = refresh+    }++    /// Looks the item up in the published workload and shows the card, or+    /// says it is already resolved.+    public func load() {+        mergeModel = nil+        item = workload().toReadMatch(for: capturedWorkID)+        hasLoaded = true+    }++    /// "2 chapters" — the captured work's size, which is most of what tells the+    /// reader it is the story they started.+    public var chapterLine: String {+        Pluralisation.count(item?.entryCount ?? 0, "chapter", "chapters")+    }++    /// The line under a choice the merge would refuse (Req 3.4), worded as the+    /// merge picker words the same refusals.+    public static func blockedMessage(_ block: ToReadMatchBlock) -> String {+        let availability: WorkMergeModel.DestinationAvailability =+            switch block {+            case .quarantined(let hostname): .quarantined(hostname: hostname)+            case .seriesConflict: .differentSeries+            }+        // Never nil: both cases are refusals.+        return WorkMergeModel.refusalMessage(for: availability) ?? ""+    }++    /// Opens the merge preview with the chosen to-read work as the survivor+    /// (Req 4.1). The captured work is the source, so its UUID goes and the+    /// to-read work's stays. A blocked or unknown choice does nothing.+    public func choose(_ toReadWorkID: UUID) {+        guard phase == .card,+            let choice = item?.choices.first(where: { $0.toReadWorkID == toReadWorkID }),+            choice.blocked == nil+        else {+            Self.logger.debug("Ignored a to-read choice the card does not offer")+            return+        }+        errorMessage = nil+        mergeModel = WorkMergeModel(+            sourceWorkID: capturedWorkID, library: library, onMutation: onMutation,+            request: .toReadMatch, presetTargetID: choice.toReadWorkID)+    }++    /// Leaves the preview for the card, writing nothing (Req 4.1).+    ///+    /// Refused while the merge is submitting (Q49): the commit may be about to+    /// land, and dropping its model here would lose the survivor the host+    /// routes to. From an error — a refusal, an `.invalidated` commit, a+    /// failed read — the published workload is refreshed before the item is+    /// looked up again, because whatever refused the merge has probably moved+    /// the pair, and the last publication would still show the card as it was.+    /// A plain cancel from the preview changed nothing, so it reads the+    /// workload as it stands.+    public func returnToCard() async {+        guard phase == .merging, let mergeModel else { return }+        guard !mergeModel.isSubmitting else {+            Self.logger.debug("Ignored a return to the card while the merge is submitting")+            return+        }+        if case .error = mergeModel.state {+            await refresh()+        }+        load()+    }++    /// The survivor of a committed merge, for the host to show; nil until one+    /// has committed.+    public var committedTargetID: UUID? {+        mergeModel?.committedTargetID+    }++    /// "None of these" (Req 5.1): every listed pair, blocked ones included, is+    /// recorded as declined in one commit. A failure keeps the card up with the+    /// reason, since nothing was recorded.+    public func decline() async {+        guard phase == .card, !isDeclining, let item else { return }+        isDeclining = true+        defer { isDeclining = false }+        errorMessage = nil+        do {+            try await declineItem(item)+            isClosed = true+        } catch {+            errorMessage = error.localizedDescription+            Self.logger.error(+                "Declining a to-read match failed: \(String(describing: error), privacy: .public)")+        }+    }+}
Asterism/Asterism/ViewModels/WorkMergeModel.swift Modified +54 / -6
diff --git a/Asterism/Asterism/ViewModels/WorkMergeModel.swift b/Asterism/Asterism/ViewModels/WorkMergeModel.swiftindex fe3457ca..d1ba611d 100644--- a/Asterism/Asterism/ViewModels/WorkMergeModel.swift+++ b/Asterism/Asterism/ViewModels/WorkMergeModel.swift@@ -42,16 +42,55 @@ public final class WorkMergeModel {     private let library: any LibraryProviding     private let onMutation: @Sendable () async -> Void     private var contract: WorkMergeContract?-    private var isSubmitting = false+    /// Whether a confirmed merge is in flight: from the tap on Confirm until+    /// the commit has answered and, for a committed merge, the host's+    /// follow-through has run. The view disables its ways out while it is true,+    /// and the to-read card refuses to come back over it+    /// (`to-read-capture-match` Q49), so the reader cannot leave a merge that+    /// is about to land and lose the survivor it routes to.+    public private(set) var isSubmitting = false+    /// Which merge the preview projects: the ordinary Merge action, or a+    /// to-read match's confirm (`to-read-capture-match` Req 4.3).+    private let request: WorkMergeRequest+    /// A destination chosen before this flow opened — the to-read card's+    /// choice (Q30). With one, `start()` goes straight to its preview and the+    /// picker is never loaded.+    private let presetTargetID: UUID?      public init(         sourceWorkID: UUID,         library: any LibraryProviding,-        onMutation: @escaping @Sendable () async -> Void+        onMutation: @escaping @Sendable () async -> Void,+        request: WorkMergeRequest = .merge,+        presetTargetID: UUID? = nil     ) {+        // A to-read confirm answers one chosen pair; it has no picker to fall+        // back on (`to-read-capture-match` Q30).+        precondition(+            request == .merge || presetTargetID != nil,+            "A .toReadMatch merge needs its preset target")         self.sourceWorkID = sourceWorkID         self.library = library         self.onMutation = onMutation+        self.request = request+        self.presetTargetID = presetTargetID+    }++    /// What the view runs when it appears: the preset target's preview where+    /// there is one, the picker otherwise.+    public func start() async {+        if let presetTargetID {+            await selectTarget(presetTargetID)+        } else {+            await loadDestinations()+        }+    }++    /// The previewed target's own title, which a to-read match's preview lists+    /// as discarded with its value (Req 4.1): the outcome carries the title the+    /// survivor will have, not the one it loses.+    public var targetTitle: String? {+        contract?.basis.target.snapshot.displayTitle     }      // MARK: - The picker (Req 4.1)@@ -132,8 +171,7 @@ public final class WorkMergeModel {         // seriesID is Req 9.2's case and a one-sided membership is Req 9.1's,         // and neither refuses. Whether either series *resolves* on this device         // is not an input — Req 11.2 forbids that everywhere.-        if let source = sourceWork?.membership, let candidate = work.membership,-            source.seriesID != candidate.seriesID {+        if SeriesMembership.areInDifferentSeries(sourceWork?.membership, work.membership) {             return .differentSeries         }         return .available@@ -142,7 +180,16 @@ public final class WorkMergeModel {     /// The line under an unselectable row. Wording lives here, per the house     /// convention that models own text and views own layout.     public func unavailableMessage(for work: WorkSnapshot) -> String? {-        switch availability(of: work) {+        Self.refusalMessage(for: availability(of: work))+    }++    /// The wording of a destination refusal, shared with the to-read card's+    /// blocked choices (`to-read-capture-match` Req 3.4), so the two surfaces+    /// say the same thing about the same refusal. Nil for `.available`.+    public nonisolated static func refusalMessage(+        for availability: DestinationAvailability+    ) -> String? {+        switch availability {         case .available:             nil         case .quarantined(let hostname):@@ -229,7 +276,8 @@ public final class WorkMergeModel {         do {             let projected = try await library.projectMerge(                 sourceWorkID: sourceWorkID,-                targetWorkID: targetID+                targetWorkID: targetID,+                request: request             )             contract = projected             outcome = projected.outcome
Asterism/Asterism/Views/ToReadMatchSheet.swift Added +172 / -0
diff --git a/Asterism/Asterism/Views/ToReadMatchSheet.swift b/Asterism/Asterism/Views/ToReadMatchSheet.swiftnew file mode 100644index 00000000..ec63aea0--- /dev/null+++ b/Asterism/Asterism/Views/ToReadMatchSheet.swift@@ -0,0 +1,172 @@+import AsterismCore+import ConstellationKit+import SwiftUI++/// The to-read card and the merge preview it opens, in one sheet+/// (`to-read-capture-match` Q23, Q30).+///+/// The merge phase **replaces** the card rather than being pushed onto it:+/// `WorkMergeView` owns its own `NavigationStack`, and a push would nest two.+/// Its cancel comes back to the card with nothing written; a committed merge+/// hands the survivor to the host, which closes the sheet and shows it. The+/// merge view does not dismiss on its own commit here, because the host's+/// close would race it (Q49, Q55).+struct ToReadMatchSheet: View {+    @State private var model: ToReadMatchModel+    /// Shows the survivor of a committed merge.+    private let onCommitted: (UUID) -> Void+    @Environment(\.dismiss) private var dismiss+    @Environment(\.siteNames) private var siteNames++    init(model: ToReadMatchModel, onCommitted: @escaping (UUID) -> Void) {+        _model = State(initialValue: model)+        self.onCommitted = onCommitted+    }++    var body: some View {+        // A stack, not a `Group`: a `Group` hands its modifiers to whichever+        // child is showing, so the load and the observers below would run again+        // on every change of phase.+        ZStack {+            if let mergeModel = model.mergeModel {+                WorkMergeView(+                    model: mergeModel,+                    onCancel: { Task { await model.returnToCard() } },+                    dismissesOnCommit: false)+            } else {+                card+            }+        }+        .accessibilityIdentifier("to-read-match-sheet")+        .onAppear {+            if model.phase == .loading { model.load() }+        }+        .onChange(of: model.committedTargetID) { _, survivorID in+            if let survivorID { onCommitted(survivorID) }+        }+        .onChange(of: model.phase) { _, phase in+            if phase == .closed { dismiss() }+        }+    }++    // MARK: - The card (Req 3.2)++    private var card: some View {+        NavigationStack {+            Group {+                switch model.phase {+                case .resolvedElsewhere:+                    ContentUnavailableView(+                        "Already resolved",+                        systemImage: "checkmark.circle",+                        description: Text("This work is no longer waiting for an answer.")+                    )+                    .accessibilityIdentifier("to-read-match-resolved")+                case .card:+                    if let item = model.item {+                        question(item)+                    }+                default:+                    // Loading or closed. The card is never drawn while merging:+                    // the body shows the merge view whenever there is one.+                    ProgressView()+                }+            }+            .navigationTitle("To Read")+            .toolbar {+                // Q55's close, as every other sheet in the app draws it.+                ToolbarItem(placement: .cancellationAction) {+                    Button(role: .close) { dismiss() }+                        .frame(+                            minWidth: AsterismLayout.minHitTarget,+                            minHeight: AsterismLayout.minHitTarget)+                        .accessibilityIdentifier("to-read-match-close")+                        .accessibilityLabel("Close")+                }+            }+        }+    }++    private func question(_ item: ToReadMatchItem) -> some View {+        List {+            Section {+                VStack(alignment: .leading, spacing: 6) {+                    Text(ToReadMatchModel.question)+                        .font(.headline)+                    Text(item.capturedTitle)+                        .font(.body)+                        .foregroundStyle(AsterismColors.primaryText)+                        .fixedSize(horizontal: false, vertical: true)+                    Text(siteNames.label(for: item.hostname) + " · " + model.chapterLine)+                        .font(.subheadline)+                        .foregroundStyle(.secondary)+                        .fixedSize(horizontal: false, vertical: true)+                }+                .accessibilityElement(children: .combine)+                .accessibilityIdentifier("to-read-match-question")+            }++            Section {+                ForEach(item.choices, id: \.toReadWorkID) { choice in+                    choiceRow(choice)+                }+            } header: {+                ConstellationSectionHeader("In To Read", accent: .cyan)+            }++            Section {+                Button {+                    Task { await model.decline() }+                } label: {+                    Text("None of these")+                        .frame(maxWidth: .infinity, minHeight: AsterismLayout.minHitTarget)+                }+                .buttonStyle(.bordered)+                .disabled(model.isDeclining)+                .accessibilityIdentifier("to-read-match-\(item.capturedWorkID.uuidString)-none")+                .accessibilityLabel("None of these is the same story")++                if let error = model.errorMessage {+                    Text(error)+                        .font(.footnote)+                        .foregroundStyle(AsterismColors.amberText)+                        .fixedSize(horizontal: false, vertical: true)+                        .accessibilityIdentifier("to-read-match-error")+                }+            }+        }+    }++    /// One choice. A blocked one stays listed, disabled, with its reason under+    /// it (Req 3.4): a greyed-out row that says nothing is a dead end.+    @ViewBuilder+    private func choiceRow(_ choice: ToReadMatchItem.Choice) -> some View {+        let reason = choice.blocked.map(ToReadMatchModel.blockedMessage)+        VStack(alignment: .leading, spacing: 4) {+            Button {+                model.choose(choice.toReadWorkID)+            } label: {+                Text(choice.title)+                    .multilineTextAlignment(.leading)+                    .fixedSize(horizontal: false, vertical: true)+                    .frame(+                        maxWidth: .infinity, minHeight: AsterismLayout.minHitTarget,+                        alignment: .leading)+            }+            .buttonStyle(.bordered)+            .disabled(reason != nil || model.isDeclining)+            .accessibilityIdentifier(+                "to-read-match-\(model.capturedWorkID.uuidString)-confirm-\(choice.toReadWorkID.uuidString)")+            .accessibilityLabel(+                reason.map { "\(choice.title). \($0)" } ?? "Same story as \(choice.title)")++            if let reason {+                Text(reason)+                    .font(.caption)+                    .foregroundStyle(.secondary)+                    .fixedSize(horizontal: false, vertical: true)+                    .accessibilityHidden(true)+            }+        }+    }+}
Asterism/Asterism/Views/TodayView.swift Modified +20 / -0
diff --git a/Asterism/Asterism/Views/TodayView.swift b/Asterism/Asterism/Views/TodayView.swiftindex 4c81caac..0d85c5fa 100644--- a/Asterism/Asterism/Views/TodayView.swift+++ b/Asterism/Asterism/Views/TodayView.swift@@ -62,6 +62,9 @@ struct TodayView: View {     let onShowSyncSettings: (() -> Void)?     /// Req 9.2's inline route: the resolution surface for one duplicate set.     let onResolveDuplicate: ((DuplicateSetKey) -> Void)?+    /// `to-read-capture-match` Q24: an Elsewhere line's route to the to-read+    /// card, by captured work UUID.+    let onResolveToReadMatch: ((UUID) -> Void)?     /// Req 4.1: a strip cell's tap.     let onSelectDay: (CivilDay) -> Void     /// Req 4.3: the week controls, in weeks, either direction.@@ -144,6 +147,7 @@ struct TodayView: View {         onShowDiagnostics: (() -> Void)? = nil,         onShowSyncSettings: (() -> Void)? = nil,         onResolveDuplicate: ((DuplicateSetKey) -> Void)? = nil,+        onResolveToReadMatch: ((UUID) -> Void)? = nil,         onSelectDay: @escaping (CivilDay) -> Void = { _ in },         onPageWeek: @escaping (Int) -> Void = { _ in },         onSelectToday: @escaping () -> Void = {},@@ -170,6 +174,7 @@ struct TodayView: View {         self.onShowDiagnostics = onShowDiagnostics         self.onShowSyncSettings = onShowSyncSettings         self.onResolveDuplicate = onResolveDuplicate+        self.onResolveToReadMatch = onResolveToReadMatch         self.onSelectDay = onSelectDay         self.onPageWeek = onPageWeek         self.onSelectToday = onSelectToday@@ -861,6 +866,7 @@ struct TodayView: View {                         switch item.route {                         case .resolve(let key): onResolveDuplicate?(key)                         case .checkLibrary: onShowDiagnostics?()+                        case .toReadMatch(let capturedWorkID): onResolveToReadMatch?(capturedWorkID)                         }                     }                 }@@ -1229,6 +1235,9 @@ struct RecentDuplicatePlan: Equatable {             case resolve(DuplicateSetKey)             /// Check Library, which lists preserved edits beside the sets.             case checkLibrary+            /// The to-read card for one captured work (`to-read-capture-match`+            /// Q24), keyed by the captured work's UUID.+            case toReadMatch(UUID)         }          let id: String@@ -1257,6 +1266,17 @@ struct RecentDuplicatePlan: Equatable {                     itemCount: 1,                     route: .resolve(item.key)))         }+        // `to-read-capture-match` Q24: a to-read match has no Recent row either+        // — it is about a work, not an entry — so each one is a line here,+        // counted once as the banner counts it.+        for item in workload.toReadMatches {+            elsewhere.append(+                Elsewhere(+                    id: "to-read-\(item.capturedWorkID.uuidString)",+                    text: "May belong to a story in To Read",+                    itemCount: 1,+                    route: .toReadMatch(item.capturedWorkID)))+        }         if conflictCount > 0 {             elsewhere.append(                 Elsewhere(
Asterism/Asterism/Views/WorkMergeView.swift Modified +61 / -18
diff --git a/Asterism/Asterism/Views/WorkMergeView.swift b/Asterism/Asterism/Views/WorkMergeView.swiftindex dee1b1c6..f1b3a282 100644--- a/Asterism/Asterism/Views/WorkMergeView.swift+++ b/Asterism/Asterism/Views/WorkMergeView.swift@@ -12,9 +12,27 @@ struct WorkMergeView: View {     /// the same sites its `SiteLabel`s show. The preview's own site rows read     /// the lookup through `SiteLabel` and need nothing here.     @Environment(\.siteNames) private var siteNames--    init(model: WorkMergeModel) {+    /// What leaving the flow without merging does — the toolbar's X and the+    /// error view's Dismiss alike. Nil dismisses the sheet, which is every host+    /// but one: the to-read card shows this view in place of itself, and its+    /// cancel goes back to the card rather than closing the sheet+    /// (`to-read-capture-match` Q30, Q49).+    private let onCancel: (() -> Void)?+    /// Whether a committed merge dismisses the sheet from in here. The to-read+    /// host passes false: it closes the sheet itself when it routes to the+    /// survivor, and a second dismissal from in here would race it (Q49, Q55).+    private let dismissesOnCommit: Bool++    init(+        model: WorkMergeModel, onCancel: (() -> Void)? = nil, dismissesOnCommit: Bool = true+    ) {         _model = State(initialValue: model)+        self.onCancel = onCancel+        self.dismissesOnCommit = dismissesOnCommit+    }++    private func cancel() {+        if let onCancel { onCancel() } else { dismiss() }     }      var body: some View {@@ -43,14 +61,16 @@ struct WorkMergeView: View {             .toolbar {                 // Q55: the sheet's X, with the word kept for VoiceOver.                 ToolbarItem(placement: .cancellationAction) {-                    Button(role: .close) { dismiss() }+                    Button(role: .close) { cancel() }+                        // A merge that is landing cannot be left (Q49).+                        .disabled(model.isSubmitting)                         .accessibilityIdentifier("merge-cancel-button")                         .accessibilityLabel("Cancel")                 }             }-            .task { await model.loadDestinations() }+            .task { await model.start() }             .onChange(of: model.state) { _, newState in-                if case .committed = newState { dismiss() }+                if case .committed = newState, dismissesOnCommit { dismiss() }             }         }     }@@ -276,7 +296,8 @@ struct WorkMergeView: View {                             // membership is named with its **value**, because                             // "Series" alone does not tell the reader which                             // series and which place in it they are losing.-                            if let value = Self.discardedValue(field, outcome: outcome) {+                            if let value = Self.discardedValue(+                                field, outcome: outcome, targetTitle: model.targetTitle) {                                 Text(value)                                     .font(.caption)                                     .foregroundStyle(AsterismColors.primaryText)@@ -292,7 +313,8 @@ struct WorkMergeView: View {                         }                         .frame(minHeight: AsterismLayout.minHitTarget)                         .accessibilityLabel(-                            Self.discardedRowLabel(field, outcome: outcome))+                            Self.discardedRowLabel(+                                field, outcome: outcome, targetTitle: model.targetTitle))                         .accessibilityIdentifier("merge-discarded-\(field.rawValue)")                     } @@ -388,8 +410,9 @@ struct WorkMergeView: View {             Text(message)                 .multilineTextAlignment(.center)                 .accessibilityIdentifier("merge-error-message")-            Button("Dismiss") { dismiss() }+            Button("Dismiss") { cancel() }                 .frame(minHeight: AsterismLayout.minHitTarget)+                .disabled(model.isSubmitting)                 .accessibilityIdentifier("merge-dismiss-button")         }         .padding()@@ -403,6 +426,11 @@ struct WorkMergeView: View {         switch field {         case .targetDisplayTitle: "Target title"         case .sourceManualTitle: "Source manual title"+        // `to-read-capture-match` Q26: a to-read match's confirm. The plain+        // words the card uses, since the reader typed the one and captured+        // the other.+        case .targetManualTitle: "Your title"+        case .sourceDisplayTitle: "Title"         case .targetType: "Target type"         case .targetWorkURL: "Target Work URL"         case .sourceWorkURL: "Source Work URL"@@ -441,18 +469,30 @@ struct WorkMergeView: View {     /// The value a discarded field is named with, or nil where the label says     /// the whole of it.     ///-    /// Only the membership carries one (Req 9.5). A dropped title, URL or note-    /// is recorded in the merged notes and can be read there; a dropped-    /// membership is written down nowhere, so the preview is the only place the-    /// reader ever sees which series and which position went.+    /// Two fields carry one. A dropped membership (Req 9.5) is written down+    /// nowhere, so the preview is the only place the reader ever sees which+    /// series and which position went. The title a to-read match replaces+    /// (`to-read-capture-match` Req 4.1) is the one the reader typed, and "Your+    /// title" alone would not say which words go. Every other dropped title,+    /// URL or note is recorded in the merged notes and can be read there.+    ///+    /// `targetTitle` is the previewed target's own title+    /// (`WorkMergeModel.targetTitle`): the outcome carries the title the+    /// survivor will have, which for a to-read match is the other one.     static func discardedValue(-        _ field: WorkMergeField, outcome: WorkMergeOutcome, locale: Locale = .current+        _ field: WorkMergeField, outcome: WorkMergeOutcome, targetTitle: String? = nil,+        locale: Locale = .current     ) -> String? {-        guard field == .sourceSeries, let membership = outcome.discardedMembership else {+        switch field {+        case .targetManualTitle:+            return targetTitle+        case .sourceSeries:+            guard let membership = outcome.discardedMembership else { return nil }+            return (membership.name ?? SeriesDisplay.unresolvedLabel)+                + " · " + SeriesPosition.format(membership.position, locale: locale)+        default:             return nil         }-        return (membership.name ?? SeriesDisplay.unresolvedLabel)-            + " · " + SeriesPosition.format(membership.position, locale: locale)     }      /// "adaptation · The Other Work", or the placeholder for an end this device@@ -490,9 +530,12 @@ struct WorkMergeView: View {     /// call site so the two halves and the comma between them are one pinnable     /// thing (Req 7.3).     static func discardedRowLabel(-        _ field: WorkMergeField, outcome: WorkMergeOutcome? = nil, locale: Locale = .current+        _ field: WorkMergeField, outcome: WorkMergeOutcome? = nil, targetTitle: String? = nil,+        locale: Locale = .current     ) -> String {-        let value = outcome.flatMap { discardedValue(field, outcome: $0, locale: locale) }+        let value = outcome.flatMap {+            discardedValue(field, outcome: $0, targetTitle: targetTitle, locale: locale)+        }         return "Discarded: \(fieldLabel(field)), "             + (value.map { $0 + ", " } ?? "")             + discardedCaption(field).lowercased()
Asterism/Asterism/Views/WorksView.swift Modified +24 / -2
diff --git a/Asterism/Asterism/Views/WorksView.swift b/Asterism/Asterism/Views/WorksView.swiftindex 01fffceb..a6fd2036 100644--- a/Asterism/Asterism/Views/WorksView.swift+++ b/Asterism/Asterism/Views/WorksView.swift@@ -24,6 +24,9 @@ struct WorksView: View {     /// Works the reader says are not the same work. Nil where the host records     /// nothing, which hides the pill rather than drawing a dead one.     let onDismissDuplicate: ((UUID, UUID) -> Void)?+    /// `to-read-capture-match` Req 3.1: the route from a captured work's row to+    /// its to-read card, by the work's UUID. Nil hides the pill.+    let onResolveToReadMatch: ((UUID) -> Void)?     /// Every Work's title by id, from the **unfiltered** snapshot: a dismiss     /// pill names the other Work in the set, and a query that hides that Work     /// must not take its name off the pill on the row still showing.@@ -70,7 +73,8 @@ struct WorksView: View {         onShowSeriesList: @escaping () -> Void,         onShowCreatorList: @escaping () -> Void,         onResolveDuplicate: ((DuplicateSetKey) -> Void)? = nil,-        onDismissDuplicate: ((UUID, UUID) -> Void)? = nil+        onDismissDuplicate: ((UUID, UUID) -> Void)? = nil,+        onResolveToReadMatch: ((UUID) -> Void)? = nil     ) {         self.snapshot = snapshot         self.duplicateWorkload = duplicateWorkload@@ -88,6 +92,7 @@ struct WorksView: View {         self.onShowCreatorList = onShowCreatorList         self.onResolveDuplicate = onResolveDuplicate         self.onDismissDuplicate = onDismissDuplicate+        self.onResolveToReadMatch = onResolveToReadMatch     }      /// `site-display-names`: what the site filter's rows and its active pill@@ -691,6 +696,7 @@ struct WorksView: View {         _ work: WorkSnapshot, titles: [UUID: String], showsSeries: Bool     ) -> some View {         let item = duplicateWorkload.item(for: work.id, type: .work)+        let toReadMatch = duplicateWorkload.toReadMatch(for: work.id)         return HStack(alignment: .top, spacing: 8) {             Button {                 onSelectWork(work.id)@@ -719,6 +725,22 @@ struct WorksView: View {                 .accessibilityLabel("Resolve duplicate copies of \(work.displayTitle)")             } +            // `to-read-capture-match` Req 3.1: a captured work that probably+            // belongs to a story in To Read. The resolve pill's recipe, because+            // it is the same kind of question on the same row.+            if toReadMatch != nil, let onResolveToReadMatch {+                Button {+                    onResolveToReadMatch(work.id)+                } label: {+                    Text("To Read?")+                        .constellationPill(.attention)+                }+                .buttonStyle(.plain)+                .accessibilityIdentifier("work-to-read-match-pill")+                .accessibilityLabel(+                    "Check whether \(work.displayTitle) belongs to a story in To Read")+            }+             // Req 5.5's other answer. The set exists because two Works on             // *different* sites happen to share a parsed title, which is a guess             // the reader is entitled to reject outright — and a set of three@@ -766,7 +788,7 @@ struct WorksView: View {         // states is about where the reader *is*, and the Merge pill still says         // what the row needs.         .constellationCard(-            borderColor: item == nil ? nil : AsterismColors.attentionBorder,+            borderColor: item == nil && toReadMatch == nil ? nil : AsterismColors.attentionBorder,             isSelected: work.id == selectedWorkID)         .accessibilityAddTraits(work.id == selectedWorkID ? [.isSelected] : [])     }
Asterism/AsterismTests/DuplicateSurfaceTests.swift Modified +60 / -0
diff --git a/Asterism/AsterismTests/DuplicateSurfaceTests.swift b/Asterism/AsterismTests/DuplicateSurfaceTests.swiftindex c8928957..02fc3c95 100644--- a/Asterism/AsterismTests/DuplicateSurfaceTests.swift+++ b/Asterism/AsterismTests/DuplicateSurfaceTests.swift@@ -546,6 +546,66 @@ struct DuplicateSurfaceTests {         #expect(plan.accountedCount == 1)     } +    // MARK: - To-read matches (`to-read-capture-match` Req 3.1, Q24, Q29, Q35)++    private static func toReadItem(blocked: ToReadMatchBlock? = nil) -> ToReadMatchItem {+        ToReadMatchItem(+            capturedWorkID: UUID(), capturedTitle: "Captured", hostname: "toread.test",+            entryCount: 1,+            choices: [.init(toReadWorkID: UUID(), title: "Typed", blocked: blocked)])+    }++    /// Q29: the workload's own `reviewCount` describes duplicate sets, so the+    /// banner adds the to-read items itself — and Q35: an item whose every+    /// choice is blocked still counts, because "None of these" is still an+    /// action the reader can take.+    @Test("The banner counts each to-read item once, an all-blocked one included")+    @MainActor func theBannerCountsToReadItems() async {+        let workSet = DuplicateSetKey(recordType: .work, memberIDs: [UUID(), UUID()])+        let workload = DuplicateWorkload(+            reviewItems: [+                DuplicateReviewItem(+                    key: workSet, route: .merge, memberIDs: workSet.memberIDs,+                    variantCount: 2, isTorn: false)+            ],+            deferredItems: [],+            toReadMatches: [Self.toReadItem(), Self.toReadItem(blocked: .seriesConflict)])+        let library = MockLibraryProvider()+        library.todayPresentationResult = .success(+            TodayPresentation(groups: [], actionableCount: 0, duplicateWorkload: workload))+        let app = AppLibraryModel(readyRepository: library)+        await app.handleActivation()+        app.recordConflict(+            .survivorDiverged(recordID: UUID(), survivorID: UUID()), recordType: .entry)++        #expect(workload.reviewCount == 1)+        #expect(app.duplicateBannerCount == 1 + 2 + 1)+    }++    /// Q24: a to-read item has no Recent row, so the duplicates-only filter+    /// names it as an Elsewhere line routed at its own sheet — one line per+    /// item, so the banner's count and the filter still agree.+    @Test("Each to-read item is one Elsewhere row routed at its sheet")+    @MainActor func eachToReadItemIsAnElsewhereRow() {+        let first = Self.toReadItem()+        let second = Self.toReadItem(blocked: .quarantined(hostname: "toread.test"))+        let workload = DuplicateWorkload(+            reviewItems: [], deferredItems: [], toReadMatches: [first, second])++        let plan = RecentDuplicatePlan(workload: workload, conflictCount: 1)++        let toRead = plan.elsewhere.filter {+            if case .toReadMatch = $0.route { true } else { false }+        }+        #expect(toRead.map(\.route) == [+            .toReadMatch(first.capturedWorkID), .toReadMatch(second.capturedWorkID),+        ])+        #expect(toRead.allSatisfy { $0.text == "May belong to a story in To Read" })+        #expect(toRead.allSatisfy { $0.itemCount == 1 })+        #expect(Set(plan.elsewhere.map(\.id)).count == plan.elsewhere.count)+        #expect(plan.accountedCount == 2 + 1)+    }+     // MARK: - WorkDetailModel (Req 2.8 on the Work half)      /// Req 2.8 mirrored: a torn Work says why its fields are off and how to turn
Asterism/AsterismTests/Helpers/MockLibraryProvider.swift Modified +29 / -1
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex ac462c39..e9bc433a 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -836,6 +836,16 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable {         recordedDistinctPairs.append((a, b))     } +    /// Each call's pairs as one batch, so a test can tell one decline from+    /// several (`to-read-capture-match` Req 5.1). Refused by the same result as+    /// the singular call.+    var recordedDistinctPairBatches: [[WorkPairKey]] = []++    func recordDistinctPairs(_ pairs: [WorkPairKey]) async throws {+        try recordDistinctPairResult.get()+        recordedDistinctPairBatches.append(pairs)+    }+     func projectWorkURL(         workID: UUID, hostname: String, request: WorkURLRequest     ) async throws -> WorkURLContract {@@ -898,13 +908,31 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable {         return try commitDuplicateResolutionResult.get()     } -    func projectMerge(sourceWorkID: UUID, targetWorkID: UUID) async throws -> WorkMergeContract {+    /// The request the last projection asked for (`to-read-capture-match`+    /// Req 4.1): a to-read confirm must not preview as an ordinary merge.+    var lastProjectMergeRequest: WorkMergeRequest?+    /// The pair the last projection was asked about: a to-read confirm merges+    /// the captured work into the to-read one, never the other way round.+    var lastProjectMergeSourceID: UUID?+    var lastProjectMergeTargetID: UUID?++    func projectMerge(+        sourceWorkID: UUID, targetWorkID: UUID, request: WorkMergeRequest+    ) async throws -> WorkMergeContract {         projectMergeCallCount += 1+        lastProjectMergeRequest = request+        lastProjectMergeSourceID = sourceWorkID+        lastProjectMergeTargetID = targetWorkID         return try projectMergeResult.get()     } +    /// Holds a merge commit open after it is recorded, so a test can act while+    /// the merge is submitting (`to-read-capture-match` Q49).+    var commitMergeHold: (@Sendable () async -> Void)?+     func commitMerge(_ contract: WorkMergeContract) async throws -> WorkMergeCommitOutcome {         commitMergeCallCount += 1+        if let hold = commitMergeHold { await hold() }         return try commitMergeResult.get()     } 
Asterism/AsterismTests/ToReadMatchModelTests.swift Added +303 / -0
diff --git a/Asterism/AsterismTests/ToReadMatchModelTests.swift b/Asterism/AsterismTests/ToReadMatchModelTests.swiftnew file mode 100644index 00000000..4c522f7c--- /dev/null+++ b/Asterism/AsterismTests/ToReadMatchModelTests.swift@@ -0,0 +1,303 @@+import AsterismCore+import Foundation+import Testing++@testable import Asterism++/// The to-read match sheet's model (`to-read-capture-match` Reqs 3.2, 4.1,+/// 5.1, Q30).+///+/// Built through `AppLibraryModel.toReadMatchModel(for:)`, the only way the app+/// builds one, so the workload it reads is the one Today published and the+/// decline is the app model's.+@Suite("To-read match sheet")+@MainActor+struct ToReadMatchModelTests {++    private static let capturedID = UUID()+    private static let toReadID = UUID()+    private static let blockedID = UUID()++    private static let item = ToReadMatchItem(+        capturedWorkID: capturedID, capturedTitle: "The Wandering Inn (Volume 1)",+        hostname: "toread.test", entryCount: 2,+        choices: [+            .init(toReadWorkID: toReadID, title: "The Wandering Inn", blocked: nil),+            .init(toReadWorkID: blockedID, title: "the wandering inn", blocked: .seriesConflict),+        ])++    /// An app model that has published a Today presentation carrying `items`.+    private func makeApp(+        items: [ToReadMatchItem] = [Self.item]+    ) async -> (AppLibraryModel, MockLibraryProvider) {+        let mock = MockLibraryProvider()+        mock.todayPresentationResult = .success(+            TodayPresentation(+                groups: [], actionableCount: 0,+                duplicateWorkload: DuplicateWorkload(+                    reviewItems: [], deferredItems: [], toReadMatches: items)))+        let app = AppLibraryModel(readyRepository: mock)+        await app.handleActivation()+        return (app, mock)+    }++    // MARK: - The card (Req 3.2)++    @Test("Loading finds the item in the published workload and shows the card")+    func loadShowsTheCard() async throws {+        let (app, _) = await makeApp()+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))++        model.load()++        #expect(model.phase == .card)+        #expect(model.item == Self.item)+        #expect(model.chapterLine == "2 chapters")+        #expect(ToReadMatchModel.question == "Is this the same story?")+    }++    /// Another device answered it, or a capture moved it out of match: the+    /// sheet says so rather than offering choices that no longer exist.+    @Test("An item gone from the workload reads as already resolved")+    func aGoneItemReadsAsResolved() async throws {+        let (app, _) = await makeApp(items: [])+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))++        model.load()++        #expect(model.phase == .resolvedElsewhere)+        #expect(model.item == nil)+    }++    @Test("A blocked choice names its reason in the merge picker's words")+    func blockedChoicesNameTheirReason() {+        #expect(ToReadMatchModel.blockedMessage(.seriesConflict) == "In a different series")+        #expect(+            ToReadMatchModel.blockedMessage(.quarantined(hostname: "toread.test"))+                == "toread.test needs attention in Check Library before this Work can be merged into.")+    }++    // MARK: - Choosing (Req 4.1, Q30)++    @Test("Choosing builds the preset merge model: captured into to-read, as a to-read match")+    func chooseBuildsThePresetMergeModel() async throws {+        let (app, mock) = await makeApp()+        mock.projectMergeResult = .success(Self.contract())+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))+        model.load()++        model.choose(Self.toReadID)++        #expect(model.phase == .merging)+        let merge = try #require(model.mergeModel)+        await merge.start()+        #expect(merge.state == .confirming)+        #expect(mock.lastProjectMergeRequest == .toReadMatch)+        #expect(mock.lastProjectMergeSourceID == Self.capturedID)+        #expect(mock.lastProjectMergeTargetID == Self.toReadID)+        #expect(mock.mergeDestinationsCallCount == 0)+    }++    /// Req 3.4: a choice the merge is certain to refuse is not offered.+    @Test("Choosing a blocked choice does nothing")+    func aBlockedChoiceIsNotOffered() async throws {+        let (app, _) = await makeApp()+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))+        model.load()++        model.choose(Self.blockedID)++        #expect(model.phase == .card)+        #expect(model.mergeModel == nil)+    }++    /// Req 4.1: cancelling the preview leaves both works and the item as they+    /// were, so the reader is back on the card with nothing written.+    @Test("Cancelling the preview returns to the card and writes nothing")+    func cancellingReturnsToTheCard() async throws {+        let (app, mock) = await makeApp()+        mock.projectMergeResult = .success(Self.contract())+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))+        model.load()+        model.choose(Self.toReadID)+        await model.mergeModel?.start()++        let publishedBefore = mock.todayPresentationCallCount++        await model.returnToCard()++        #expect(model.phase == .card)+        #expect(model.mergeModel == nil)+        #expect(mock.commitMergeCallCount == 0)+        #expect(mock.recordedDistinctPairBatches.isEmpty)+        // A plain cancel changed nothing, so it re-publishes nothing.+        #expect(mock.todayPresentationCallCount == publishedBefore)+    }++    /// Q49: a merge that is landing cannot be left. Dropping the merge model+    /// mid-commit would lose the survivor the host routes to.+    @Test("Cancelling while the merge is submitting keeps the merge and still routes the survivor")+    func cancellingDuringSubmissionKeepsTheMerge() async throws {+        let (app, mock) = await makeApp()+        mock.projectMergeResult = .success(Self.contract())+        mock.commitMergeResult = .success(.committed(targetID: Self.toReadID))+        let gate = SubmissionGate()+        mock.commitMergeHold = { await gate.wait() }+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))+        model.load()+        model.choose(Self.toReadID)+        let merge = try #require(model.mergeModel)+        await merge.start()++        async let confirmed: () = merge.confirmMerge()+        await yieldUntil { mock.commitMergeCallCount == 1 }+        try #require(mock.commitMergeCallCount == 1)+        #expect(merge.isSubmitting)++        await model.returnToCard()++        #expect(model.phase == .merging, "The card does not come back over a landing merge")+        #expect(model.mergeModel === merge)+        gate.open()+        _ = await confirmed++        #expect(model.committedTargetID == Self.toReadID)+        #expect(!merge.isSubmitting)+    }++    /// m2 of the design-critic review: an `.invalidated` commit means the pair+    /// has probably moved, so the card is rebuilt from a fresh publication+    /// rather than the one the sheet opened on.+    @Test("Returning from a refused merge refreshes the workload before the card reloads")+    func returningFromARefusalRefreshesFirst() async throws {+        let (app, mock) = await makeApp()+        mock.projectMergeResult = .success(Self.contract())+        mock.commitMergeResult = .success(.invalidated(reason: "The works changed."))+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))+        model.load()+        model.choose(Self.toReadID)+        let merge = try #require(model.mergeModel)+        await merge.start()+        await merge.confirmMerge()+        #expect(merge.state == .error(message: "The works changed."))++        // Another device answered the question meanwhile: the next+        // publication no longer carries the item.+        mock.todayPresentationResult = .success(+            TodayPresentation(+                groups: [], actionableCount: 0,+                duplicateWorkload: DuplicateWorkload(+                    reviewItems: [], deferredItems: [], toReadMatches: [])))+        let publishedBefore = mock.todayPresentationCallCount++        await model.returnToCard()++        #expect(mock.todayPresentationCallCount > publishedBefore)+        #expect(model.phase == .resolvedElsewhere)+        #expect(model.mergeModel == nil)+    }++    @Test("A committed merge reports the survivor for the host to show")+    func aCommittedMergeReportsTheSurvivor() async throws {+        let (app, mock) = await makeApp()+        mock.projectMergeResult = .success(Self.contract())+        mock.commitMergeResult = .success(.committed(targetID: Self.toReadID))+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))+        model.load()+        model.choose(Self.toReadID)+        #expect(model.committedTargetID == nil)++        await model.mergeModel?.start()+        await model.mergeModel?.confirmMerge()++        #expect(model.committedTargetID == Self.toReadID)+    }++    // MARK: - Declining (Req 5.1)++    /// Every listed pair, blocked ones included, in one call: one commit, so a+    /// decline cannot land half-way.+    @Test("Declining records every listed pair in one call and closes the sheet")+    func declineRecordsEveryPair() async throws {+        let (app, mock) = await makeApp()+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))+        model.load()+        // Settle the activation's own passes, so the count below is the+        // decline's alone.+        await app.waitForLaunchTail()+        await app.waitForDuplicateFollowUp()+        let publishedBefore = mock.todayPresentationCallCount+        let reconcilesBefore = mock.reconcileAfterSyncTiers++        await model.decline()+        await app.waitForDuplicateFollowUp()++        #expect(+            mock.recordedDistinctPairBatches == [[+                WorkPairKey(Self.capturedID, Self.toReadID),+                WorkPairKey(Self.capturedID, Self.blockedID),+            ]])+        #expect(model.phase == .closed)+        #expect(model.errorMessage == nil)+        // Q25: refreshed, so the item leaves Today at once, and no reconcile+        // is scheduled, because a distinct pair within one site changes no set.+        #expect(mock.todayPresentationCallCount > publishedBefore)+        #expect(mock.reconcileAfterSyncTiers == reconcilesBefore)+    }++    /// m6 of the design-critic review: with no library open, the decline must+    /// not report success, or the sheet closes having recorded nothing.+    @Test("Declining with no library open throws rather than closing quietly")+    func declineWithoutALibraryThrows() async {+        let root = FileManager.default.temporaryDirectory+            .appendingPathComponent(UUID().uuidString, isDirectory: true)+        let app = AppLibraryModel(configuration: LibraryConfiguration(rootDirectory: root))++        await #expect(throws: AppLibraryModel.LibraryNotOpen.self) {+            try await app.declineToReadMatch(Self.item)+        }+    }++    @Test("A failed decline keeps the sheet open with the error")+    func aFailedDeclineKeepsTheSheet() async throws {+        let (app, mock) = await makeApp()+        mock.recordDistinctPairResult = .failure(+            MockLibraryProvider.MockError.simulatedFailure("disk full"))+        let model = try #require(app.toReadMatchModel(for: Self.capturedID))+        model.load()++        await model.decline()++        #expect(model.phase == .card)+        #expect(model.errorMessage == "disk full")+        #expect(mock.recordedDistinctPairBatches.isEmpty)+    }++    // MARK: - Fixtures++    private static func contract() -> WorkMergeContract {+        let source = TestFixtures.makeWork(id: capturedID, displayTitle: "The Wandering Inn (Volume 1)")+        let target = TestFixtures.makeWork(id: toReadID, displayTitle: "The Wandering Inn")+        let basis = try! WorkMergeBasis(+            source: WorkMergeWorkBasis(snapshot: source, identity: .none),+            target: WorkMergeWorkBasis(snapshot: target, identity: .none),+            currentRule: nil)+        let outcome = WorkMergeOutcome(+            sourceID: capturedID, targetID: toReadID,+            displayTitle: "The Wandering Inn (Volume 1)", lastParsedTitle: nil,+            titleProvenance: .parsed, typeDisplay: .untyped,+            sites: [+                WorkMergeSiteOutcome(+                    hostname: "toread.test", workURL: nil,+                    identityEvidence: .noEntries(previousIdentity: .none),+                    identityDisposition: .retain(.none), isShared: true)+            ],+            genericNotes: "", genreTags: [], auditBlock: nil, movedEntryIDs: [],+            resultingEntryCount: 2,+            sourceIdentityEvidence: .noEntries(previousIdentity: .none),+            targetIdentityEvidence: .noEntries(previousIdentity: .none),+            issues: [], retainedFields: [.sourceDisplayTitle],+            discardedFields: [.targetManualTitle], sourceDeleted: true)+        return WorkMergeContract(basis: basis, request: .toReadMatch, outcome: outcome)+    }+}
Asterism/AsterismTests/WorkMergeModelTests.swift Modified +79 / -0
diff --git a/Asterism/AsterismTests/WorkMergeModelTests.swift b/Asterism/AsterismTests/WorkMergeModelTests.swiftindex dc042c21..a20a185a 100644--- a/Asterism/AsterismTests/WorkMergeModelTests.swift+++ b/Asterism/AsterismTests/WorkMergeModelTests.swift@@ -272,6 +272,85 @@ struct WorkMergeModelTests {         #expect(committed.committedTargetID == survivor)     } +    // MARK: - A preset target (`to-read-capture-match` Q30)++    /// The to-read card has already chosen the destination, so the merge view+    /// opens on its preview. The picker is never loaded: loading it is the one+    /// path to `.pickingDestination`, so a call count of zero is the proof that+    /// the sheet never showed it.+    @Test("With a preset target, start projects that target and never loads the picker")+    @MainActor func startWithAPresetTargetProjectsIt() async {+        let sourceID = UUID()+        let targetID = UUID()+        let mock = MockLibraryProvider()+        mock.projectMergeResult = .success(+            makeMergeContract(sourceID: sourceID, targetID: targetID))+        let model = WorkMergeModel(+            sourceWorkID: sourceID, library: mock, onMutation: {},+            request: .toReadMatch, presetTargetID: targetID)++        await model.start()++        #expect(model.state == .confirming)+        #expect(model.selectedTargetID == targetID)+        #expect(mock.mergeDestinationsCallCount == 0)+        #expect(mock.lastProjectMergeRequest == .toReadMatch)+        #expect(mock.lastProjectMergeSourceID == sourceID)+        #expect(mock.lastProjectMergeTargetID == targetID)+    }++    @Test("Without a preset target, start loads the picker and a choice projects a plain merge")+    @MainActor func startWithoutAPresetTargetIsUnchanged() async {+        let targetID = UUID()+        let (model, mock) = makeSUT()+        mock.mergeDestinationsResult = .success([TestFixtures.makeWork(id: targetID)])+        mock.projectMergeResult = .success(makeMergeContract(targetID: targetID))++        await model.start()++        #expect(model.state == .pickingDestination)+        #expect(mock.mergeDestinationsCallCount == 1)+        #expect(mock.projectMergeCallCount == 0)++        await model.selectTarget(targetID)++        #expect(mock.lastProjectMergeRequest == .merge)+    }++    /// Req 4.1: the preview names the title the reader typed, because the+    /// merged notes are the only other place it survives.+    @Test("The discarded typed title is shown with its value")+    func theDiscardedTypedTitleShowsItsValue() {+        let outcome = makeMergeContract(targetID: UUID()).outcome++        #expect(WorkMergeView.fieldLabel(.targetManualTitle) == "Your title")+        #expect(WorkMergeView.fieldLabel(.sourceDisplayTitle) == "Title")+        #expect(+            WorkMergeView.discardedValue(+                .targetManualTitle, outcome: outcome, targetTitle: "Wandering Inn")+                == "Wandering Inn")+        #expect(+            WorkMergeView.discardedRowLabel(+                .targetManualTitle, outcome: outcome, targetTitle: "Wandering Inn")+                == "Discarded: Your title, Wandering Inn, recorded in merged notes")+        // Every other field is still named by its label alone.+        #expect(+            WorkMergeView.discardedValue(+                .sourceVerdict, outcome: outcome, targetTitle: "Wandering Inn") == nil)+    }++    @Test("The model exposes the target's title from the previewed contract")+    @MainActor func theModelExposesTheTargetTitle() async {+        let targetID = UUID()+        let (model, mock) = makeSUT()+        mock.projectMergeResult = .success(makeMergeContract(targetID: targetID))+        #expect(model.targetTitle == nil)++        await model.selectTarget(targetID)++        #expect(model.targetTitle == "Target")+    }+     // MARK: - Helpers      @MainActor
Asterism/AsterismUITests/AccessibilityJourneyUITests.swift Modified +56 / -0
diff --git a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swiftindex a0236e08..95e419b5 100644--- a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift+++ b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift@@ -1384,6 +1384,62 @@ final class AccessibilityJourneyUITests: XCTestCase {             "Req 10.4: and the tap clears the day, as it does at the default size")     } +    /// `to-read-capture-match` Req 3.6 on the phone: at the largest text size+    /// every choice on the to-read card is reachable by its identifier,+    /// labelled, and a full target — the offered one and "None of these"+    /// operable, the blocked one present and disabled — and the offered one+    /// still reaches the merge preview and back.+    @MainActor+    func testTheToReadMatchCardIsOperableAtLargestDynamicType() {+        launchSeeded(+            scenario: ToReadMatchScenario.scenario,+            extraArguments: [+                "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"+            ]+        )+        let works = app.tabControl(.works)+        XCTAssertTrue(works.waitForExistence(timeout: 60), "The Works tab is reachable")+        works.tap()++        scrollUntilTappableAndTap(+            app.buttons["work-to-read-match-pill"], in: app,+            "The captured work's pill is reachable at the largest size")+        XCTAssertTrue(+            app.anyElement("to-read-match-sheet").waitForExistence(timeout: 15),+            "The pill opens the card")++        let confirm = app.buttons[ToReadMatchScenario.confirm]+        XCTAssertTrue(confirm.waitForExistence(timeout: 10))+        scrollToElement(confirm, attempts: 8)+        assertContentControl(confirm, named: "The offered to-read work")++        let blocked = app.buttons[ToReadMatchScenario.confirmBlocked]+        scrollToElement(blocked, attempts: 8)+        XCTAssertTrue(blocked.exists, "The blocked to-read work is listed")+        XCTAssertFalse(blocked.isEnabled, "…and not offered")+        XCTAssertFalse(+            blocked.label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,+            "The blocked choice still says what it is")++        let none = app.buttons[ToReadMatchScenario.none]+        scrollToElement(none, attempts: 8)+        assertContentControl(none, named: "None of these")++        for _ in 0..<6 where !confirm.isHittable { app.swipeDown() }+        confirm.tap()+        // The preview's toolbar rather than its Confirm button: at this size+        // Confirm is at the foot of a lazy list and not yet in the tree.+        let cancel = app.buttons["merge-cancel-button"]+        XCTAssertTrue(cancel.waitForExistence(timeout: 15), "The choice opens the merge preview")+        XCTAssertTrue(+            ToReadMatchScenario.mergePreview(in: app).waitForExistence(timeout: 15),+            "The merge view shows the preview, not the destination picker")+        assertSystemControl(cancel, named: "Cancel the preview")+        cancel.tap()+        XCTAssertTrue(+            confirm.waitForExistence(timeout: 10), "Cancelling the preview returns to the card")+    }+     /// Taps a review-list control, walking back to the top of the list first.     ///     /// `scrollUntilTappableAndTap` only ever goes one way, and a decision taken
Asterism/AsterismUITests/DuplicateResolutionUITests.swift Modified +149 / -1
diff --git a/Asterism/AsterismUITests/DuplicateResolutionUITests.swift b/Asterism/AsterismUITests/DuplicateResolutionUITests.swiftindex 3d8513a3..f839150a 100644--- a/Asterism/AsterismUITests/DuplicateResolutionUITests.swift+++ b/Asterism/AsterismUITests/DuplicateResolutionUITests.swift@@ -86,7 +86,9 @@ final class DuplicateResolutionUITests: XCTestCase {     /// seeder is otherwise invisible until some other assertion times out with     /// no explanation.     func testSeededDuplicateShapesReachRecent() {-        for shape in ["divergentEntrySet", "tornEntryGroup", "divergentWorkSet"] {+        for shape in [+            "divergentEntrySet", "tornEntryGroup", "divergentWorkSet", ToReadMatchScenario.shape,+        ] {             launch(shape)             require(                 app.collectionViews["recent-list"], "\(shape) opens and publishes Recent",@@ -291,6 +293,152 @@ final class DuplicateResolutionUITests: XCTestCase {             "Q30: a divergent Work set with no torn member is a Merge, not the sheet")     } +    // MARK: - To-read matches (`to-read-capture-match` Reqs 3.1, 3.2, 4.1, 5.1)++    /// Today banner → Elsewhere row → card → choice → preview → merge. The sheet+    /// closes on the commit and the survivor's page is what the reader sees,+    /// carrying the captured title (Req 4.3).+    func testConfirmingAToReadMatchMergesAndShowsTheSurvivor() {+        launch(ToReadMatchScenario.shape)+        require(app.collectionViews["recent-list"], "The library opens", timeout: 60)++        require(app.buttons["duplicate-banner"], "The to-read item counts in the banner").tap()+        let row = require(+            app.buttons.matching(+                NSPredicate(format: "label == %@", "May belong to a story in To Read")+            ).firstMatch,+            "The duplicates filter names the to-read item as an Elsewhere row")+        row.tap()++        require(any("to-read-match-sheet"), "The row opens the to-read card")+        let question = require(any("to-read-match-question"), "The card asks its question")+        XCTAssertTrue(+            question.label.contains("Is this the same story?"),+            "The card asks whether the works are one story: \(question.label)")+        XCTAssertTrue(+            question.label.contains("The Wandering Inn (Volume 1)"),+            "The card names the captured work: \(question.label)")+        let confirm = require(+            app.buttons[ToReadMatchScenario.confirm], "The matching to-read work is offered")+        XCTAssertTrue(confirm.isEnabled)+        let blocked = require(+            app.buttons[ToReadMatchScenario.confirmBlocked],+            "The to-read work in another series is listed")+        XCTAssertFalse(blocked.isEnabled, "A choice the merge would refuse is not offered (Req 3.4)")+        require(app.buttons[ToReadMatchScenario.none], "None of these is offered")++        confirm.tap()+        require(+            ToReadMatchScenario.mergePreview(in: app),+            "The choice opens the merge preview (Req 4.1)")+        // Confirm sits at the foot of the preview's lazy list, below the fold.+        scrollUntilTappableAndTap(+            app.buttons["merge-confirm-button"], in: app, "The preview can be confirmed")++        waitForDisappearance(any("to-read-match-sheet"), "The sheet closes on the commit")+        require(any("work-detail-pulse"), "The survivor's page is shown", timeout: 20)+        require(+            app.staticTexts["The Wandering Inn (Volume 1)"],+            "The survivor carries the captured title")++        // Req 4.2: the to-read work survived under its own UUID and the+        // captured one is gone — not the other way round, which would show the+        // same title on the survivor's page.+        selectTab(.works, in: app)+        require(+            app.buttons["work-row-\(ToReadMatchScenario.toReadID)"],+            "The to-read work is the survivor")+        waitForDisappearance(+            app.buttons["work-row-\(ToReadMatchScenario.capturedID)"],+            "The captured work was merged away")+    }++    /// Q30, Q47: confirmed from the Works pill, the survivor opens on the+    /// Works stack, as its only route: one Back returns to the list, where the+    /// to-read work stands and the captured one is gone.+    func testConfirmingFromTheWorksPillShowsTheSurvivorOnTheWorksStack() {+        launch(ToReadMatchScenario.shape)+        require(app.collectionViews["recent-list"], "The library opens", timeout: 60)++        selectTab(.works, in: app)+        require(+            app.buttons["work-to-read-match-pill"], "The captured work's row carries the pill"+        ).tap()+        require(app.buttons[ToReadMatchScenario.confirm], "The card offers the choice").tap()+        require(ToReadMatchScenario.mergePreview(in: app), "The preview is on screen")+        scrollUntilTappableAndTap(+            app.buttons["merge-confirm-button"], in: app, "The preview can be confirmed")++        waitForDisappearance(any("to-read-match-sheet"), "The sheet closes on the commit")+        require(any("work-detail-pulse"), "The survivor's page is shown", timeout: 20)+        require(+            app.staticTexts["The Wandering Inn (Volume 1)"],+            "The survivor carries the captured title")++        app.goBack()+        require(+            app.buttons["work-row-\(ToReadMatchScenario.toReadID)"],+            "Back from the survivor is the Works list, with the to-read work in it")+        waitForDisappearance(+            app.buttons["work-row-\(ToReadMatchScenario.capturedID)"],+            "The captured work was merged away")+        // No assertion on the pill: the survivor is no longer to-read and+        // carries the captured title, so it can pair afresh with the fixture's+        // other to-read work, and a pill on its row is then correct.+    }++    /// Req 4.1: cancelling the preview writes nothing and returns to the card,+    /// and both works are still in the library afterwards.+    func testCancellingTheToReadPreviewReturnsToTheCard() {+        launch(ToReadMatchScenario.shape)+        require(app.collectionViews["recent-list"], "The library opens", timeout: 60)++        selectTab(.works, in: app)+        require(+            app.buttons["work-to-read-match-pill"], "The captured work's row carries the pill"+        ).tap()+        require(app.buttons[ToReadMatchScenario.confirm], "The card offers the choice").tap()+        require(ToReadMatchScenario.mergePreview(in: app), "The preview is on screen")++        require(app.buttons["merge-cancel-button"], "The preview can be cancelled").tap()+        require(+            app.buttons[ToReadMatchScenario.confirm],+            "Cancelling returns to the card rather than closing the sheet")+        require(app.buttons["to-read-match-close"], "The card can be closed").tap()+        waitForDisappearance(any("to-read-match-sheet"), "The card closes")++        require(+            app.buttons["work-row-\(ToReadMatchScenario.capturedID)"],+            "The captured work is still in the library")+        require(+            app.buttons["work-row-\(ToReadMatchScenario.toReadID)"],+            "The to-read work is still in the library")+        require(+            app.buttons["work-to-read-match-pill"],+            "Nothing was answered, so the question is still asked")+    }++    /// Req 5.1: "None of these" declines every listed pair, and the pill goes+    /// with the question at the next publication.+    func testNoneOfTheseFromTheWorksPillRemovesThePill() {+        launch(ToReadMatchScenario.shape)+        require(app.collectionViews["recent-list"], "The library opens", timeout: 60)++        selectTab(.works, in: app)+        let pill = require(+            app.buttons["work-to-read-match-pill"], "The captured work's row carries the pill")+        XCTAssertEqual(+            pill.label,+            "Check whether The Wandering Inn (Volume 1) belongs to a story in To Read")+        pill.tap()++        require(app.buttons[ToReadMatchScenario.none], "The card offers None of these").tap()++        waitForDisappearance(any("to-read-match-sheet"), "A decline closes the sheet")+        waitForDisappearance(+            app.buttons["work-to-read-match-pill"], "The declined question is not asked again")+    }+     // MARK: - The blocked backup names its count and its route (Req 8.4)      /// Task 21's reader-facing half, driven the way the reader meets it: the
Asterism/AsterismUITests/UIJourneySupport.swift Modified +31 / -0
diff --git a/Asterism/AsterismUITests/UIJourneySupport.swift b/Asterism/AsterismUITests/UIJourneySupport.swiftindex 78c9d81a..55bb6fa0 100644--- a/Asterism/AsterismUITests/UIJourneySupport.swift+++ b/Asterism/AsterismUITests/UIJourneySupport.swift@@ -634,3 +634,34 @@ extension XCTestCase {         return resolved     } }++/// The `seeded-tolerated-to-read-match` scenario's fixed identities+/// (`to-read-capture-match` Req 3.6).+///+/// The same three UUIDs `ToReadMatchFixture` seeds in `AsterismCore`, spelled+/// here because the UI-test bundle does not link the package. Three suites walk+/// this card — the phone journey, the phone's largest text size and the iPad's+/// wide layout — so the identifiers are built once.+enum ToReadMatchScenario {+    /// The suffix `DuplicateResolutionUITests.launch(_:)` prefixes.+    static let shape = "to-read-match"+    static let scenario = "seeded-tolerated-\(shape)"++    static let capturedID = "7E4D0000-0000-4000-8000-000000000001"+    /// The to-read work the captured one can be merged into.+    static let toReadID = "7E4D0000-0000-4000-8000-000000000002"+    /// The to-read work in a conflicting series: listed, not offered.+    static let blockedToReadID = "7E4D0000-0000-4000-8000-000000000003"++    static let confirm = "to-read-match-\(capturedID)-confirm-\(toReadID)"+    static let confirmBlocked = "to-read-match-\(capturedID)-confirm-\(blockedToReadID)"+    static let none = "to-read-match-\(capturedID)-none"++    /// The merge preview's summary row, which is at the top of the preview and+    /// so is in the tree at every text size. Its Confirm button is at the foot+    /// of a lazy list and is not, until it has been scrolled to.+    static func mergePreview(in app: XCUIApplication) -> XCUIElement {+        app.descendants(matching: .any)+            .matching(NSPredicate(format: "label BEGINSWITH %@", "Merge result:")).firstMatch+    }+}
Asterism/AsterismUITests/WideLayoutUITests.swift Modified +37 / -0
diff --git a/Asterism/AsterismUITests/WideLayoutUITests.swift b/Asterism/AsterismUITests/WideLayoutUITests.swiftindex 6c4fad8d..11edbfd1 100644--- a/Asterism/AsterismUITests/WideLayoutUITests.swift+++ b/Asterism/AsterismUITests/WideLayoutUITests.swift@@ -1252,4 +1252,41 @@ final class WideLayoutUITests: XCTestCase {                 + "list column, so the Mac's 360 pt column holds them too — span was \(span)",             file: file, line: line)     }++    // MARK: - `to-read-capture-match` Req 3.6 — the to-read card in the wide layout++    /// Every choice on the card is reached by its identifier in the wide+    /// layout: the offered one opens the merge preview and its cancel returns to+    /// the card inside the same sheet (Q30), the blocked one is listed and+    /// disabled, and "None of these" answers the question so the pill goes.+    func testTheToReadMatchCardIsOperableInTheWideLayout() {+        launch(ToReadMatchScenario.scenario, orientation: .landscapeLeft)+        waitForLibrary()++        selectTab(.works, in: app)+        waitFor(+            app.buttons["work-to-read-match-pill"], "The captured work's row carries the pill"+        ).tap()+        waitFor(app.anyElement("to-read-match-sheet"), "The pill opens the card")++        let confirm = waitFor(+            app.buttons[ToReadMatchScenario.confirm], "The offered to-read work is reachable")+        XCTAssertTrue(confirm.isHittable && confirm.isEnabled)+        let blocked = waitFor(+            app.buttons[ToReadMatchScenario.confirmBlocked], "The blocked to-read work is listed")+        XCTAssertFalse(blocked.isEnabled, "A choice the merge would refuse is not offered")+        let none = waitFor(app.buttons[ToReadMatchScenario.none], "None of these is reachable")+        XCTAssertTrue(none.isHittable)++        confirm.tap()+        waitFor(ToReadMatchScenario.mergePreview(in: app), "The choice opens the merge preview")+        waitFor(app.buttons["merge-cancel-button"], "The preview can be cancelled").tap()+        waitFor(+            app.buttons[ToReadMatchScenario.none], "Cancelling returns to the card"+        ).tap()++        waitUntilGone(app.anyElement("to-read-match-sheet"), "A decline closes the sheet")+        waitUntilGone(+            app.buttons["work-to-read-match-pill"], "The declined question is not asked again")+    } }
Makefile Modified +1 / -1
diff --git a/Makefile b/Makefileindex 389fee08..46c452a3 100644--- a/Makefile+++ b/Makefile@@ -406,7 +406,7 @@ test-performance-m4: 			--no-parallel \ 			-c release \ 			-Xswiftc -DASTERISM_PERFORMANCE_TESTING \-			--filter 'M4(ScalePerformance|ToleratedScalePerformance|ToleratedFixture|DuplicateScalePerformance|MembershipScalePerformance|SeriesScalePerformance|CreatorScalePerformance|EmptyLibraryPerformance)Tests' \+			--filter 'M4(ScalePerformance|ToleratedScalePerformance|ToleratedFixture|DuplicateScalePerformance|MembershipScalePerformance|SeriesScalePerformance|CreatorScalePerformance|EmptyLibraryPerformance|ToReadMatchScalePerformance)Tests' \ 			|| exit $$?; \ 	done 
Packages/AsterismCore/Sources/AsterismCore/DuplicateWorkload.swift Modified +79 / -3
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateWorkload.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateWorkload.swiftindex e75330f5..b310dc81 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateWorkload.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateWorkload.swift@@ -89,6 +89,61 @@ public struct DuplicateReviewItem: Sendable, Equatable, Identifiable {     } } +/// Why a to-read choice cannot be merged, shown beside it instead of offering+/// it (`to-read-capture-match` Req 3.4).+public enum ToReadMatchBlock: Sendable, Equatable {+    /// A membership hostname of either work is quarantined, which the merge+    /// commit refuses.+    case quarantined(hostname: String)+    /// Both works are in a series and the series differ, which the merge+    /// planner refuses.+    case seriesConflict+}++/// One captured work that probably belongs to a story in To Read+/// (`to-read-capture-match` Req 3.1, 3.2).+///+/// A sibling of `DuplicateReviewItem`, not a kind of it (Decision 1): it is+/// keyed by the captured work rather than by a `DuplicateSetKey`, and it is not+/// a duplicate set, so it counts in none of `reviewCount`, `isEmpty` or+/// `allItems` (Q29).+public struct ToReadMatchItem: Sendable, Equatable, Identifiable {+    public let capturedWorkID: UUID+    public let capturedTitle: String+    /// The lowest shared hostname on which a choice matched.+    public let hostname: String+    /// The captured work's logical entries.+    public let entryCount: Int+    /// Every to-read work it pairs with, by to-read UUID, blocked ones included+    /// so the reason shows (Q35).+    public let choices: [Choice]++    public struct Choice: Sendable, Equatable {+        public let toReadWorkID: UUID+        public let title: String+        public let blocked: ToReadMatchBlock?++        public init(toReadWorkID: UUID, title: String, blocked: ToReadMatchBlock?) {+            self.toReadWorkID = toReadWorkID+            self.title = title+            self.blocked = blocked+        }+    }++    public init(+        capturedWorkID: UUID, capturedTitle: String, hostname: String, entryCount: Int,+        choices: [Choice]+    ) {+        self.capturedWorkID = capturedWorkID+        self.capturedTitle = capturedTitle+        self.hostname = hostname+        self.entryCount = entryCount+        self.choices = choices+    }++    public var id: UUID { capturedWorkID }+}+ /// Every duplicate set that is waiting for somebody, and nothing else. /// /// A silently resolvable set contributes nothing (Req 9.5): the app resolves it@@ -102,10 +157,25 @@ public struct DuplicateWorkload: Sendable, Equatable {     /// **excluded from `reviewCount`**: while deferred a set does not surface,     /// count, or list as awaiting action on its own account (Req 1.6, Q32).     public let deferredItems: [DuplicateReviewItem]+    /// Captured works that probably belong to a story in To Read+    /// (`to-read-capture-match` Req 3.1), one per captured work, by captured+    /// UUID. Not a duplicate set, so **excluded from `reviewCount`, `isEmpty`+    /// and `allItems`**: Settings and Check Library read those and have no row+    /// for a candidate; the Today banner adds this count itself (Q29).+    public let toReadMatches: [ToReadMatchItem] -    public init(reviewItems: [DuplicateReviewItem], deferredItems: [DuplicateReviewItem]) {+    public init(+        reviewItems: [DuplicateReviewItem], deferredItems: [DuplicateReviewItem],+        toReadMatches: [ToReadMatchItem] = []+    ) {         self.reviewItems = reviewItems         self.deferredItems = deferredItems+        self.toReadMatches = toReadMatches+    }++    /// The to-read item for one captured work, or nil where it pairs with none.+    public func toReadMatch(for capturedWorkID: UUID) -> ToReadMatchItem? {+        toReadMatches.first { $0.capturedWorkID == capturedWorkID }     }      public static let empty = DuplicateWorkload(reviewItems: [], deferredItems: [])@@ -185,11 +255,16 @@ public struct DuplicateWorkload: Sendable, Equatable {     /// workload therefore has no reason to walk the two rule tables, and the     /// Recent publication — which runs on a 2 s budget — used to walk them     /// twice per publication for nothing.+    ///+    /// `toReadMatches` are carried, not derived: Today's publication derives+    /// them from the same rows beside the sets (`to-read-capture-match`+    /// Decision 1), and the scan never sees them (Req 1.3).     public init(         entrySets: [EntryDuplicateSet],         workSets: [WorkDuplicateSet],         characterSets: [RecordDuplicateSet] = [],-        placeSets: [RecordDuplicateSet] = []+        placeSets: [RecordDuplicateSet] = [],+        toReadMatches: [ToReadMatchItem] = []     ) {         var review: [DuplicateReviewItem] = []         var deferred: [DuplicateReviewItem] = []@@ -247,7 +322,8 @@ public struct DuplicateWorkload: Sendable, Equatable {          self.init(             reviewItems: review.sorted { $0.key < $1.key },-            deferredItems: deferred.sorted { $0.key < $1.key })+            deferredItems: deferred.sorted { $0.key < $1.key },+            toReadMatches: toReadMatches)     }      private static func item<Content: AuthoredContent>(
Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift Modified +18 / -2
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex dd7b2c11..ba9e8625 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift@@ -362,6 +362,10 @@ public protocol LibraryProviding: Sendable {     /// recorded as distinct and stops linking those two Works by title.     func recordDistinctPair(_ a: UUID, _ b: UUID) async throws +    /// Every pair recorded as distinct in one commit (`to-read-capture-match`+    /// Req 5.1): "None of these" declines each to-read work its item listed.+    func recordDistinctPairs(_ pairs: [WorkPairKey]) async throws+     /// What the resolution sheet shows: every authored variant in the set, the     /// fields they differ in, and the leading variant preselected.     func projectDuplicateResolution(@@ -514,8 +518,12 @@ public protocol LibraryProviding: Sendable {     /// Merge destinations for a given source Work (same-Site other Works).     func mergeDestinations(for sourceWorkID: UUID) async throws -> [WorkSnapshot] -    /// Project a Merge preview. Pure read, no write.-    func projectMerge(sourceWorkID: UUID, targetWorkID: UUID) async throws -> WorkMergeContract+    /// Project a Merge preview. Pure read, no write. `.toReadMatch` is a to-read+    /// match's confirm (`to-read-capture-match` Req 4.1); the overload below+    /// without `request` is the ordinary Merge action.+    func projectMerge(+        sourceWorkID: UUID, targetWorkID: UUID, request: WorkMergeRequest+    ) async throws -> WorkMergeContract      /// Commit an approved Merge contract.     func commitMerge(_ contract: WorkMergeContract) async throws -> WorkMergeCommitOutcome@@ -705,4 +713,12 @@ extension LibraryProviding {     public func reconcileAfterSync() async throws -> ReconciliationOutcome {         try await reconcileAfterSync(tier: .full)     }++    /// The ordinary Merge action's preview. Here rather than as a default+    /// argument, which a protocol requirement cannot carry.+    public func projectMerge(+        sourceWorkID: UUID, targetWorkID: UUID+    ) async throws -> WorkMergeContract {+        try await projectMerge(sourceWorkID: sourceWorkID, targetWorkID: targetWorkID, request: .merge)+    } }
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift Modified +31 / -14
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swiftindex de886d4f..41b18493 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift@@ -27,27 +27,44 @@ extension LibraryRepository {     /// would then have to dedupe (Req 5.8). A pair naming one Work twice is     /// refused — a Work is not distinct from itself.     public func recordDistinctPair(_ a: UUID, _ b: UUID) async throws {-        guard a != b else {+        try await recordDistinctPairs([WorkPairKey(a, b)])+    }++    /// Records every pair as distinct in **one** commit+    /// (`to-read-capture-match` Req 5.1): "None of these" declines every to-read+    /// work its item listed, and a failure part-way must not leave some of them+    /// declined and the rest still asked about.+    ///+    /// Each pair takes `recordDistinctPair`'s idempotent body, so a pair named+    /// twice in one call, or already recorded, re-stamps the row rather than+    /// adding one. A pair naming one Work twice refuses the whole call before+    /// anything is written.+    public func recordDistinctPairs(_ pairs: [WorkPairKey]) async throws {+        guard !pairs.contains(where: { $0.lower == $0.higher }) else {             throw LibraryRepositoryError.invalidInput(-                operation: "recordDistinctPair",+                operation: "recordDistinctPairs",                 reason: "A Work cannot be recorded as distinct from itself.")         }+        guard !pairs.isEmpty else { return }         try await withLockedContext(             mode: .exclusive, operation: "recording a distinct Work pair"         ) { context in-            let sorted = WorkDistinctPair.sortedIDs(a, b)             let timestamp = MillisecondInstant.quantize(self.clock.now())-            let existing = try context.fetch(FetchDescriptor<WorkDistinctPair>())-                .filter { $0.lowerWorkID == sorted.lower && $0.higherWorkID == sorted.higher }-            if existing.isEmpty {-                context.insert(-                    WorkDistinctPair(-                        lowerWorkID: sorted.lower, higherWorkID: sorted.higher,-                        recordedAt: timestamp))-            } else {-                // Latest wins on convergence (Q23), so re-recording moves the-                // stamp rather than adding a row for the reconciler to remove.-                for row in existing { row.recordedAt = timestamp }+            var existing: [WorkPairKey: [WorkDistinctPair]] = [:]+            for row in try context.fetch(FetchDescriptor<WorkDistinctPair>()) {+                existing[WorkPairKey(row.lowerWorkID, row.higherWorkID), default: []].append(row)+            }+            for pair in pairs {+                if let rows = existing[pair] {+                    // Latest wins on convergence (Q23), so re-recording moves the+                    // stamp rather than adding a row for the reconciler to remove.+                    for row in rows { row.recordedAt = timestamp }+                } else {+                    let row = WorkDistinctPair(+                        lowerWorkID: pair.lower, higherWorkID: pair.higher, recordedAt: timestamp)+                    context.insert(row)+                    existing[pair] = [row]+                }             }             do { try self.saveStrategy.save(context) } catch {                 throw LibraryRepositoryError.libraryUnavailable(
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift Modified +16 / -5
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swiftindex 6827fb69..2a863ea2 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift@@ -52,11 +52,6 @@ extension LibraryRepository {             let distinctPairs = try DuplicateScan.distinctPairKeys(context: context)             let workSets = DuplicateScan.workSets(                 of: works, types: types, distinctPairs: distinctPairs)-            let workload = DuplicateWorkload(-                entrySets: DuplicateScan.entrySets(of: entryRows, workSets: workSets),-                workSets: workSets)-            // Built once: asked per row, the item scan is O(rows × sets).-            let duplicateRoutes = workload.routes(for: .entry)             // Definitions: assignments referring to members of one Work             // duplicate set are equal, so a group split across two members of an             // unresolved Work set is not torn. One spelling, shared with the@@ -78,6 +73,22 @@ extension LibraryRepository {             // Computed once and shared by the title fold, the unfiltered title             // map and the schedule (`launch-to-today` Decision 2).             let workGroups = Self.workGroups(works, types: types)+            // `to-read-capture-match` Decision 1: the to-read candidates come+            // from the rows, groups and sets this publication already holds,+            // beside the duplicate sets and never inside the scan (Req 1.3).+            // The quarantine is the repository's own latch, read here inside+            // the lock: the one `quarantineReason(hostname:)` answers from when+            // the merge commit refuses, so a choice shows as blocked exactly+            // when the commit would refuse it (Req 3.4, Q45).+            let toReadMatches = ToReadMatcher.candidates(+                works: works, sites: sites, entries: entryRows, groups: workGroups,+                distinctPairs: distinctPairs, workSets: workSets,+                quarantine: self.quarantined)+            let workload = DuplicateWorkload(+                entrySets: DuplicateScan.entrySets(of: entryRows, workSets: workSets),+                workSets: workSets, toReadMatches: toReadMatches)+            // Built once: asked per row, the item scan is O(rows × sets).+            let duplicateRoutes = workload.routes(for: .entry)             let workTitles = Self.recentWorkTitles(workGroups)             // `sitesByHostname` resolves the row whose *current* teaching drives             // the row's mode and presentation — a genuine winner-selection
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift Modified +102 / -9
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swiftindex 9514a96f..bf4d1f25 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift@@ -308,9 +308,13 @@ extension LibraryRepository {         }     } +    /// - Parameter request: `.toReadMatch` for a to-read match's confirm+    ///   (`to-read-capture-match` Req 4.1), which the contract carries so the+    ///   commit re-projects the same request.     public func projectMerge(         sourceWorkID: UUID,-        targetWorkID: UUID+        targetWorkID: UUID,+        request: WorkMergeRequest     ) async throws -> WorkMergeContract {         try await withLockedContext(mode: .shared, operation: "projecting Merge") { context in             let basis = try Self.buildMergeBasis(@@ -319,7 +323,7 @@ extension LibraryRepository {                 context: context             ).basis             let outcome: WorkMergeOutcome-            do { outcome = try WorkMergePlanner.project(basis) }+            do { outcome = try WorkMergePlanner.project(basis, request: request) }             catch let error as WorkMergePlanningError {                 // `projectWorkURL`'s shape, and Q41's reason: `withLockedContext`                 // re-wraps anything that is not a `LibraryRepositoryError` as@@ -332,7 +336,7 @@ extension LibraryRepository {             workMergeLogger.debug(                 "Projected Merge from \(sourceWorkID.uuidString) into \(targetWorkID.uuidString)"             )-            return WorkMergeContract(basis: basis, request: .merge, outcome: outcome)+            return WorkMergeContract(basis: basis, request: request, outcome: outcome)         }     } @@ -365,19 +369,33 @@ extension LibraryRepository {             // 2. Rebuild outcome from current basis             let currentOutcome: WorkMergeOutcome             do {-                currentOutcome = try WorkMergePlanner.project(currentBasis)+                currentOutcome = try WorkMergePlanner.project(+                    currentBasis, request: contract.request)             } catch {                 return .invalidated(reason: String(describing: error))             }              // 3. Compare basis AND outcome — stale detection             guard currentBasis == contract.basis, currentOutcome == contract.outcome else {+                // `to-read-capture-match` Req 4.6 at the **first** stale+                // confirm (Q53): a to-read pair that stopped matching is+                // invalidated here, rather than refreshed into a second preview+                // the next confirm would then refuse.+                if contract.request == .toReadMatch,+                    try !ToReadMatcher.isCandidate(+                        capturedID: contract.basis.source.snapshot.id,+                        toReadID: contract.basis.target.snapshot.id, context: context) {+                    return .invalidated(reason: Self.toReadMatchInvalidatedReason)+                }                 workMergeLogger.debug(                     "Merge commit detected stale state; returning refreshed projection"                 )+                // The contract's own request (`to-read-capture-match`): a+                // refreshed `.toReadMatch` preview must still be one, or the+                // reader's next confirm would commit a plain merge.                 return .refreshed(WorkMergeContract(                     basis: currentBasis,-                    request: .merge,+                    request: contract.request,                     outcome: currentOutcome                 ))             }@@ -433,15 +451,27 @@ extension LibraryRepository {             let mergeHostnames = Set(                 (sourceGroup.rows + targetGroup.rows)                     .flatMap { $0.membershipValues.map(\.hostname) })-            let quarantined = mergeHostnames-                .filter { self.quarantineReason(hostname: $0) != nil }-                .sorted()+            let quarantined = Self.quarantinedHostnames(+                of: [sourceGroup, targetGroup], in: self.quarantined)             if !quarantined.isEmpty {                 return .invalidated(                     reason: "Merge is unavailable while \(quarantined.joined(separator: ", ")) "                         + "\(quarantined.count == 1 ? "has" : "have") an unresolved problem.")             } +            // `to-read-capture-match` Req 4.6: a confirm is only as good as the+            // candidate rule it answered, so the rule is evaluated again here,+            // under the lock, over what the library holds now. A decline or a+            // duplicate set that arrived behind the preview changes neither+            // basis, which is why the comparison above cannot catch it. After+            // the quarantine refusal, which already speaks for a blocked pair,+            // and before any mutation.+            if contract.request == .toReadMatch,+                try !ToReadMatcher.isCandidate(+                    capturedID: sourceID, toReadID: targetID, context: context) {+                return .invalidated(reason: Self.toReadMatchInvalidatedReason)+            }+             // Move all source Entries to target, updating modifiedAt.             //             // `movedEntryIDs` comes from the source *group's* snapshot, so it@@ -520,6 +550,12 @@ extension LibraryRepository {                 // are: one row taking it is what re-tears the group.                 row.seriesID = outcome.membership?.seriesID                 row.seriesPosition = outcome.membership?.position+                // `to-read-capture-match` Req 4.3: the projected raw values,+                // never re-read from a source row, so the survivor carries+                // exactly what the preview showed (Q34).+                if let overrides = outcome.rawOverrides {+                    Self.applyToReadMatchOverrides(overrides, to: row)+                }                 row.modifiedAt = timestamp             } @@ -640,6 +676,36 @@ extension LibraryRepository {         }     } +    /// Writes a `.toReadMatch` survivor's raw values to one target row, each+    /// only where the row differs. Raw columns are copied as the planner took+    /// them, never re-encoded through a tolerated enum, so an unknown value a+    /// newer build stored survives the merge (Q31, Q34).+    private static func applyToReadMatchOverrides(+        _ overrides: WorkMergeRawOverrides, to row: Work+    ) {+        if row.displayTitle != overrides.displayTitle {+            row.displayTitle = overrides.displayTitle+        }+        if row.lastParsedTitle != overrides.lastParsedTitle {+            row.lastParsedTitle = overrides.lastParsedTitle+        }+        if row.titleProvenanceRaw != overrides.titleProvenanceRaw {+            row.titleProvenanceRaw = overrides.titleProvenanceRaw+        }+        if row.readingStatusRaw != overrides.readingStatusRaw {+            row.readingStatusRaw = overrides.readingStatusRaw+        }+        if row.workStatusRaw != overrides.workStatusRaw {+            row.workStatusRaw = overrides.workStatusRaw+        }+        if row.verdict != overrides.verdict {+            row.verdict = overrides.verdict+        }+        if row.releaseDaysRaw != overrides.releaseDaysRaw {+            row.releaseDaysRaw = overrides.releaseDaysRaw+        }+    }+     /// Q73's route, spelled for a surface that returns an outcome rather than     /// throwing: a torn group is workload, not damage, and the refusal names     /// where the reader goes.@@ -650,6 +716,24 @@ extension LibraryRepository {         """     } +    /// Req 4.6's refusal for a to-read pair that no longer matches.+    private static let toReadMatchInvalidatedReason =+        "These works no longer look like the same story."++    /// Every hostname any row of `groups` has a membership on that `map`+    /// quarantines, sorted (Req 4.5). The merge commit refuses on these, and+    /// the to-read card blocks a choice on the first of them+    /// (`to-read-capture-match` Req 3.4), so the two cannot disagree.+    internal static func quarantinedHostnames(+        of groups: [WorkGroup], in map: [String: LibraryValidationError]+    ) -> [String] {+        guard !map.isEmpty else { return [] }+        let hostnames = Set(groups.flatMap(\.rows).flatMap {+            ($0.siteMemberships ?? []).map(\.hostname)+        })+        return hostnames.filter { map[$0] != nil }.sorted()+    }+     // MARK: - Merge basis builder      /// - Returns: the basis, plus the two folds the commit reuses — both sides'@@ -844,10 +928,19 @@ extension LibraryRepository {             WorkMergeEntryBasis(snapshot: entrySnap)         } +        // `to-read-capture-match` Q34: the raw columns of the row the snapshot+        // presents its titles and statuses from, so a `.toReadMatch` merge can+        // decide "pristine" and copy values without a tolerated enum between.+        // `releaseDaysRaw` is left to the init's default: the group snapshot+        // already carries the carrier's raw array.+        let carrier = group.carrier         return WorkMergeWorkBasis(             snapshot: workSnapshot,             identitiesByHostname: identitiesByHostname,-            entries: entries+            entries: entries,+            workStatusRaw: carrier.workStatusRaw,+            readingStatusRaw: carrier.readingStatusRaw,+            titleProvenanceRaw: carrier.titleProvenanceRaw         )     } 
Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swift Modified +134 / -0
diff --git a/Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swiftindex d0123951..252c47ed 100644--- a/Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/M4PerformanceFixture.swift@@ -683,6 +683,82 @@ extension LibraryRepository {         }     } +    /// Layers `to-read-capture-match` Req 6.1's shape over an already-seeded M4+    /// performance fixture: 50 to-read works on `m4FixtureHostname` — 20 whose+    /// titles equal a base work's after normalising, 10 whole-word prefix+    /// matches and 20 near misses — plus the 10 captured works the prefix+    /// matches pair with.+    ///+    /// **The 10 captured works are the one addition beyond the design's+    /// sentence** (Q46). Every base work is titled `Story <n>`, which is two+    /// words and at most nine scalars, so it can never be the shorter side of a+    /// prefix match (Req 2.4's floor), and a to-read work shorter than it has+    /// nothing left to match with. A prefix pair needs a captured title long+    /// enough to be the longer side, so the layer brings its own.+    ///+    /// Every title here starts with `story`, the first word all 1,000 base+    /// works share, so each to-read work scans the whole captured bucket: the+    /// single first-word bucket of Q41 at its worst case on this fixture.+    ///+    /// **The base graph is left exactly as it was**, and the rows sit beside it+    /// in their own UUID namespaces. The to-read works carry no parsed title,+    /// as a to-read work never has one, so none of them lands in a Work+    /// duplicate set with the base work it matches; a pair inside an open set+    /// is withheld (Req 3.5), and the arm would be measuring nothing.+    ///+    /// Straight through `saveStrategy.save`, as the other layers are.+    public func seedM4ToReadMatchLayer() async throws {+        let operation = "seeding the M4 to-read match layer"+        let hostname = Self.m4FixtureHostname+        let toReadRaw = ReadingStatus.toRead.rawValue+        try await withLockedContext(mode: .exclusive, operation: operation) { context in+            let existing = try context.fetchCount(+                FetchDescriptor<Work>(+                    predicate: #Predicate { $0.readingStatusRaw == toReadRaw }))+            guard existing == 0 else {+                throw LibraryRepositoryError.invalidInput(+                    operation: operation,+                    reason: "the library already holds \(existing) to-read works")+            }+            guard let site = try context.fetch(+                FetchDescriptor<Site>(predicate: #Predicate { $0.hostname == hostname })+            ).first else {+                throw LibraryRepositoryError.invalidInput(+                    operation: operation,+                    reason: "the fixture's Site row is missing")+            }+            // Past the composed fixture's own 0..<5,000 second offsets and the+            // duplicate sets' band after them.+            let base = Date(timeIntervalSince1970: TimeInterval(Self.m4FixtureEntryCount * 4))++            for index in 0..<Self.m4ToReadMatchPrefixCount {+                let title = Self.m4ToReadMatchCapturedTitle(index)+                let work = Work.create(+                    in: context,+                    id: Self.m4FixtureUUID(namespace: 32, index: index),+                    membershipID: Self.m4FixtureUUID(namespace: 34, index: index),+                    title: title, hostname: hostname, site: site,+                    timestamp: base.addingTimeInterval(TimeInterval(index)))+                work.lastParsedTitle = title+                work.titleProvenance = .parsed+            }++            for index in 0..<Self.m4ToReadMatchWorkCount {+                let work = Work.create(+                    in: context,+                    id: Self.m4FixtureUUID(namespace: 31, index: index),+                    membershipID: Self.m4FixtureUUID(namespace: 33, index: index),+                    title: Self.m4ToReadMatchTitle(index), hostname: hostname, site: site,+                    timestamp: base.addingTimeInterval(+                        TimeInterval(Self.m4ToReadMatchPrefixCount + index)))+                work.readingStatus = .toRead+                work.titleProvenance = .manual+            }++            try self.saveStrategy.save(context)+        }+    }+     /// Req 10.1's shape, written underneath the validating commit path exactly     /// as the other tolerated states are.     ///@@ -1101,6 +1177,64 @@ extension LibraryRepository {         return [first, (first + 2) % m4CreatorFixtureRoleCount]     } +    // MARK: The to-read match layer — `to-read-capture-match` Req 6.1's shape++    /// To-read works whose title equals a base work's after normalising.+    public static let m4ToReadMatchEqualCount = 20+    /// To-read works that are a whole-word prefix of a layer-seeded captured+    /// work, and the captured works they pair with, one each.+    public static let m4ToReadMatchPrefixCount = 10+    /// To-read works that share a first word with every captured work and+    /// match none of them.+    public static let m4ToReadMatchNearMissCount = 20+    /// 50 to-read works in all.+    public static let m4ToReadMatchWorkCount =+        m4ToReadMatchEqualCount + m4ToReadMatchPrefixCount + m4ToReadMatchNearMissCount+    /// One pair per equal or prefix to-read work, each with its own captured+    /// work, so one review item per pair.+    public static let m4ToReadMatchPairCount = m4ToReadMatchEqualCount + m4ToReadMatchPrefixCount++    /// The to-read work's title, by index: the equal arm first, then the prefix+    /// arm, then the near misses.+    ///+    /// - **Equal:** base work `Story <50i>` spelled four ways — case,+    ///   punctuation, extra whitespace — that all normalise to `story <50i>`.+    /// - **Prefix:** the first five words of a captured title from+    ///   `m4ToReadMatchCapturedTitle`, well over the floor.+    /// - **Near miss:** half are `Story <n> Part Two`, whose shorter side+    ///   `story <n>` is under Req 2.4's floor; half are `Story <n>a`, which+    ///   shares the first word and no other.+    static func m4ToReadMatchTitle(_ index: Int) -> String {+        if index < m4ToReadMatchEqualCount {+            let title = m4FixtureWorkTitle(workIndex: index * m4ToReadMatchWorkStride)+            return [+                title.uppercased(),+                title.lowercased().replacingOccurrences(of: " ", with: "-") + "!",+                "  " + title.replacingOccurrences(of: " ", with: "   ") + " ",+                title + ".",+            ][index % 4]+        }+        let prefixIndex = index - m4ToReadMatchEqualCount+        if prefixIndex < m4ToReadMatchPrefixCount {+            return "Story \(1_000 + prefixIndex) The Long Road"+        }+        let missIndex = prefixIndex - m4ToReadMatchPrefixCount+        return missIndex % 2 == 0+            ? "Story \(missIndex * m4ToReadMatchWorkStride + 25) Part Two"+            : "Story \(missIndex * m4ToReadMatchWorkStride + 10)a"+    }++    /// The gap between the base works the equal arm and the near misses name:+    /// 50, spreading the 20 equal to-read works evenly over the 1,000 base+    /// works.+    static let m4ToReadMatchWorkStride = m4FixtureWorkCount / m4ToReadMatchEqualCount++    /// The captured side of a prefix pair: numbered past the base works, so it+    /// shares nothing but its first word with any of them.+    static func m4ToReadMatchCapturedTitle(_ index: Int) -> String {+        "Story \(1_000 + index): The Long Road Home"+    }+     // MARK: `.duplicateSets` — Req 10.1's shape      /// Entry sets of two rows each: 500 extra Entry rows, 250 collapses.
Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift Modified +91 / -6
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift b/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swiftindex fdebc3bf..249d201e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ProjectionContract.swift@@ -542,32 +542,61 @@ public struct WorkMergeWorkBasis: Equatable, Sendable {     public let identitiesByHostname: [String: WorkIdentitySnapshot]     public let entries: [WorkMergeEntryBasis] +    /// The carrier row's raw columns (`to-read-capture-match` Q31, Q34), beside+    /// the tolerated values the snapshot holds. A `.toReadMatch` merge decides+    /// "pristine" on the target's and copies the source's verbatim, and neither+    /// can be done through a tolerated enum: an unknown raw status reads as the+    /// default. Part of the basis, so a raw-only change behind the preview+    /// refreshes it.+    public let workStatusRaw: String+    public let readingStatusRaw: String+    public let titleProvenanceRaw: String+    /// The stored token array, undecoded: unknown tokens included, in stored+    /// order.+    public let releaseDaysRaw: [String]+     /// The primary site's identity, for the single-site reads that predate V8.     public var identity: WorkIdentitySnapshot {         snapshot.memberships.first.map { identitiesByHostname[$0.hostname] ?? .none } ?? .none     } +    /// A raw column left nil is the snapshot's typed value's own spelling,+    /// which is what a basis built by hand — the planner tests do — means.     public init(         snapshot: WorkSnapshot,         identitiesByHostname: [String: WorkIdentitySnapshot],-        entries: [WorkMergeEntryBasis]? = nil+        entries: [WorkMergeEntryBasis]? = nil,+        workStatusRaw: String? = nil,+        readingStatusRaw: String? = nil,+        titleProvenanceRaw: String? = nil,+        releaseDaysRaw: [String]? = nil     ) {         self.snapshot = snapshot         self.identitiesByHostname = identitiesByHostname         self.entries = entries ?? snapshot.entries.map { WorkMergeEntryBasis(snapshot: $0) }+        self.workStatusRaw = workStatusRaw ?? snapshot.workStatus.rawValue+        self.readingStatusRaw = readingStatusRaw ?? snapshot.readingStatus.rawValue+        self.titleProvenanceRaw = titleProvenanceRaw ?? snapshot.titleProvenance.rawValue+        self.releaseDaysRaw = releaseDaysRaw ?? snapshot.releaseDaysRaw     }      /// The single-site shape: the identity belongs to the Work's primary site.     public init(         snapshot: WorkSnapshot,         identity: WorkIdentitySnapshot,-        entries: [WorkMergeEntryBasis]? = nil+        entries: [WorkMergeEntryBasis]? = nil,+        workStatusRaw: String? = nil,+        readingStatusRaw: String? = nil,+        titleProvenanceRaw: String? = nil,+        releaseDaysRaw: [String]? = nil     ) {         self.init(             snapshot: snapshot,             identitiesByHostname: snapshot.memberships.first                 .map { [$0.hostname: identity] } ?? [:],-            entries: entries)+            entries: entries,+            workStatusRaw: workStatusRaw, readingStatusRaw: readingStatusRaw,+            titleProvenanceRaw: titleProvenanceRaw, releaseDaysRaw: releaseDaysRaw)     } } @@ -702,11 +731,57 @@ public struct WorkMergeBasis: Equatable, Sendable {  public enum WorkMergeRequest: Equatable, Sendable {     case merge+    /// `to-read-capture-match` Req 4.3, 4.4: the source is a captured work and+    /// the target a to-read work the reader confirmed it belongs to. The+    /// ordinary merge outcome, with the target taking the source's titles and+    /// reading status, and its status, verdict and release days wherever the+    /// target still holds what the New Work form gave it.+    case toReadMatch+}++/// The raw values a `.toReadMatch` survivor carries (`to-read-capture-match`+/// Q34), taken from the basis as the snapshot presents each field: titles and+/// statuses from the carrier, the parsed title from the representative.+///+/// Raw, never re-encoded from a tolerated enum, so the commit writes an unknown+/// value a newer build stored exactly as it found it.+public struct WorkMergeRawOverrides: Equatable, Sendable {+    public let displayTitle: String+    public let lastParsedTitle: String?+    public let titleProvenanceRaw: String+    public let readingStatusRaw: String+    public let workStatusRaw: String+    public let verdict: String+    public let releaseDaysRaw: [String]++    public init(+        displayTitle: String,+        lastParsedTitle: String?,+        titleProvenanceRaw: String,+        readingStatusRaw: String,+        workStatusRaw: String,+        verdict: String,+        releaseDaysRaw: [String]+    ) {+        self.displayTitle = displayTitle+        self.lastParsedTitle = lastParsedTitle+        self.titleProvenanceRaw = titleProvenanceRaw+        self.readingStatusRaw = readingStatusRaw+        self.workStatusRaw = workStatusRaw+        self.verdict = verdict+        self.releaseDaysRaw = releaseDaysRaw+    } }  public enum WorkMergeField: String, Equatable, Hashable, Sendable, CaseIterable {     case targetDisplayTitle     case sourceManualTitle+    // `to-read-capture-match` (Req 4.1, Q26): a `.toReadMatch` merge takes the+    // source's display title, and the title the reader typed on the to-read+    // work is discarded — recorded in the audit block's `Title before merge`+    // line.+    case targetManualTitle+    case sourceDisplayTitle     case targetType     case targetWorkURL     case sourceWorkURL@@ -751,7 +826,8 @@ public enum WorkMergeField: String, Equatable, Hashable, Sendable, CaseIterable     /// promise on the screen a merge is approved from.     public var recordedInNotes: Bool {         switch self {-        case .sourceManualTitle, .sourceWorkURL, .sourceNotes, .sourceVerdict: true+        case .sourceManualTitle, .sourceWorkURL, .sourceNotes, .sourceVerdict,+             .targetManualTitle: true         // The tags are unioned rather than recorded, and nothing on the target's         // side is discarded at all.         // A dropped membership is not written down anywhere either: the preview@@ -761,7 +837,7 @@ public enum WorkMergeField: String, Equatable, Hashable, Sendable, CaseIterable         // text, and a picture is not text — so the preview saying so is the         // whole of what the reader gets (Req 1.5).         case .sourceGenreTags, .sourceWorkStatus, .sourceReadingStatus,-             .targetDisplayTitle, .targetType, .targetWorkURL, .targetNotes,+             .targetDisplayTitle, .sourceDisplayTitle, .targetType, .targetWorkURL, .targetNotes,              .targetGenreTags, .targetWorkStatus, .targetReadingStatus, .targetVerdict,              .targetSeries, .sourceSeries,              .targetThumbnail, .sourceThumbnail,@@ -913,6 +989,11 @@ public struct WorkMergeOutcome: Equatable, Sendable {     /// the merged Work will carry and the commit's target loop writes none of     /// them.     public let releaseDays: [ReleaseDay]+    /// `to-read-capture-match` Q34: the raw values a `.toReadMatch` survivor+    /// takes, written to every target row by the commit; nil for `.merge`,+    /// whose target loop writes none of these fields. The typed fields above+    /// agree with it, as the tolerated reads of the same values.+    public let rawOverrides: WorkMergeRawOverrides?      public init(         sourceID: UUID,@@ -957,9 +1038,13 @@ public struct WorkMergeOutcome: Equatable, Sendable {         // Defaulted for the reason above: an outcome built by hand is describing         // a preview, and a caller that omits it is describing a merge of two         // works neither of which has a schedule.-        releaseDays: [ReleaseDay] = []+        releaseDays: [ReleaseDay] = [],+        // Defaulted for the reason above: an outcome built by hand is+        // describing an ordinary merge unless it says otherwise.+        rawOverrides: WorkMergeRawOverrides? = nil     ) {         self.releaseDays = ReleaseDay.canonical(releaseDays)+        self.rawOverrides = rawOverrides         self.thumbnail = thumbnail         self.gainedCredits = gainedCredits         self.membership = membership
Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift Modified +11 / -0
diff --git a/Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift b/Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swiftindex 8e772d42..45dd84e1 100644--- a/Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift@@ -30,6 +30,17 @@ public struct SeriesMembership: Equatable, Hashable, Sendable {         self.seriesID = seriesID         self.position = position     }++    /// `series-and-related-works` Req 9.3's refusal: both works are in a+    /// series and not the same one. The same seriesID is Req 9.2's case and a+    /// one-sided membership is Req 9.1's, and neither refuses. The one test+    /// the merge planner, the merge picker and the to-read card all apply.+    public static func areInDifferentSeries(+        _ left: SeriesMembership?, _ right: SeriesMembership?+    ) -> Bool {+        guard let left, let right else { return false }+        return left.seriesID != right.seriesID+    } }  /// One member as the series editor's draft holds it, for the one commit that
Packages/AsterismCore/Sources/AsterismCore/ToReadMatcher.swift Added +405 / -0
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ToReadMatcher.swift b/Packages/AsterismCore/Sources/AsterismCore/ToReadMatcher.swiftnew file mode 100644index 00000000..d2df61f7--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/ToReadMatcher.swift@@ -0,0 +1,405 @@+import Foundation+import SwiftData++/// A title as the to-read match rule compares it (`to-read-capture-match`+/// Definitions).+///+/// `text` and `words` keep a leading article, because every comparison reads+/// it (Req 2.4: "Wandering Inn" is not a prefix of "The Wandering Inn 2").+/// `countedWords` and `countedLength` leave it out, because the prefix floor+/// is about how much of the title says something.+struct NormalisedTitle: Hashable {+    let text: String+    let words: [Substring]+    /// Words, a leading `the`, `a` or `an` not counted.+    let countedWords: Int+    /// Unicode scalars in `text`, spaces included, a leading article and the+    /// space after it not counted.+    let countedLength: Int+}++/// One candidate pair: a captured work and a to-read work that match on at+/// least one shared site. `hostname` is the lowest shared hostname on which+/// they matched, so a pair matching on two sites is still one pair.+struct MatchedPair: Hashable {+    let capturedID: UUID+    let toReadID: UUID+    let hostname: String+}++/// Finds the pairs of a to-read work and a captured work that look like one+/// story (`to-read-capture-match` Req 2).+///+/// Pure over its inputs: no clock, no `PersistentIdentifier`, no device state,+/// so two devices holding the same synced content derive the same pairs+/// (Req 1.1). Nothing here feeds the duplicate scan, the reconcile pass or its+/// counters (Req 1.3): the callers are Today's publication and the merge+/// commit's re-check.+enum ToReadMatcher {++    private static let articles: Set<Substring> = ["the", "a", "an"]++    // MARK: - Pairs++    /// One work on one hostname, as the match rule reads it.+    private struct Side {+        let id: UUID+        let title: NormalisedTitle+        let membership: WorkSiteMembership+    }++    /// Every candidate pair (Req 2.1–2.5, 3.5), sorted by captured UUID and+    /// then to-read UUID.+    ///+    /// A work's values are its group carrier's, as its snapshot presents them:+    /// title, reading status. Its memberships are the union over the group's+    /// rows, one per hostname, the survivor `Work.membership(in:for:)` picks.+    static func pairs(+        works: [Work], sites: [Site], groups: [UUID: WorkGroup],+        distinctPairs: Set<WorkPairKey>, workSets: [WorkDuplicateSet]+    ) -> [MatchedPair] {+        // Req 3.5: nothing is offered while either work is in an open set or+        // its group is torn. Dropping the work drops every pair it is in.+        //+        // An open set is one the reader is being asked about, as+        // `DuplicateWorkload` publishes it (anything not silently resolvable),+        // or one of **two or more** works, which a collapse is still to fold.+        // A lone split group that is silently resolvable is a set of one too,+        // and one that has converged stays one for good, because its rows are+        // never deleted (duplicate-reconciliation Decision 4), so it holds+        // nothing back: merging it is not order-dependent and the merge carries+        // every row of a split group (Q38 as amended).+        var excluded: Set<UUID> = []+        for set in workSets+        where set.members.count > 1 || set.classification != .silentlyResolvable {+            for member in set.members { excluded.insert(member.id) }+        }+        func isOffered(_ id: UUID, _ group: WorkGroup) -> Bool {+            !group.isTorn && !excluded.contains(id)+        }++        // The to-read side first: without one there is nothing to index, which+        // is the common case on Today's path.+        var toReadByHostname: [String: [Side]] = [:]+        for (id, group) in groups+        where group.carrier.readingStatus == .toRead && isOffered(id, group) {+            let memberships = membershipsByHostname(group.rows)+            guard !memberships.isEmpty else { continue }+            let title = normalise(group.carrier.displayTitle)+            for (hostname, membership) in memberships {+                toReadByHostname[hostname, default: []].append(+                    Side(id: id, title: title, membership: membership))+            }+        }+        guard !toReadByHostname.isEmpty else { return [] }++        // Only a captured work on a site holding a to-read work is indexed and+        // normalised.+        var capturedRows: [UUID: [WorkSiteMembership]] = [:]+        for work in works {+            for membership in work.siteMemberships ?? []+            where toReadByHostname[membership.hostname] != nil {+                capturedRows[work.id, default: []].append(membership)+            }+        }+        var capturedByHostname: [String: [Side]] = [:]+        for (id, rows) in capturedRows {+            guard let group = groups[id], group.carrier.readingStatus != .toRead,+                isOffered(id, group)+            else { continue }+            let title = normalise(group.carrier.displayTitle)+            for (hostname, membership) in membershipsByHostname(rows) {+                capturedByHostname[hostname, default: []].append(+                    Side(id: id, title: title, membership: membership))+            }+        }++        let sitesByHostname = SiteResolutionOrder.winnersByHostname(sites)+        var lowestHostname: [PairIDs: String] = [:]+        for (hostname, capturedSides) in capturedByHostname {+            let identityRule = identityRule(of: sitesByHostname[hostname])+            // Indexed once per hostname: the prefix scan only compares titles+            // sharing a first word, and a whole-word prefix always does.+            var byFirstWord: [Substring: [Side]] = [:]+            var byIdentity: [ExactScalarString: [UUID]] = [:]+            for side in capturedSides {+                if let first = side.title.words.first {+                    byFirstWord[first, default: []].append(side)+                }+                // Q28: a legacy identity is still the value capture reuses on.+                let state = side.membership.urlIdentityState+                if state == .rule || state == .legacyUnverified,+                    let identity = side.membership.urlIdentity {+                    byIdentity[ExactScalarString(identity), default: []].append(side.id)+                }+            }++            for toRead in toReadByHostname[hostname] ?? [] {+                var matched: Set<UUID> = []+                if let first = toRead.title.words.first {+                    for side in byFirstWord[first] ?? [] where titlesMatch(toRead.title, side.title) {+                        matched.insert(side.id)+                    }+                }+                if let identity = workURLIdentity(of: toRead.membership, rule: identityRule) {+                    matched.formUnion(byIdentity[identity] ?? [])+                }+                for capturedID in matched+                where !distinctPairs.contains(WorkPairKey(capturedID, toRead.id)) {+                    let key = PairIDs(captured: capturedID, toRead: toRead.id)+                    if let existing = lowestHostname[key], existing <= hostname { continue }+                    lowestHostname[key] = hostname+                }+            }+        }++        return lowestHostname+            .map { MatchedPair(capturedID: $0.key.captured, toReadID: $0.key.toRead, hostname: $0.value) }+            .sorted {+                $0.capturedID == $1.capturedID+                    ? $0.toReadID.uuidString < $1.toReadID.uuidString+                    : $0.capturedID.uuidString < $1.capturedID.uuidString+            }+    }++    /// Whether the pair is still a candidate over what the library holds now+    /// (Req 4.6), for the merge commit's re-check under the exclusive lock.+    ///+    /// The same `pairs` the publication calls, over the same inputs built the+    /// same way, so the two cannot disagree. No `Entry` rows: they only feed+    /// the displayed count, and they are the dominant cost of Today's reads+    /// (Q32). No blocked check either: the commit's quarantine refusal runs+    /// before this and the planner throws on a series conflict.+    ///+    /// A declined pair is answered before anything else is fetched. The Work+    /// sets are built over every row, because Req 3.5 asks whether either work+    /// is in any open set; `pairs` then sees only the two works' rows, since+    /// no other work changes whether this pair matches (Q54).+    static func isCandidate(+        capturedID: UUID, toReadID: UUID, context: ModelContext+    ) throws -> Bool {+        let distinctPairs = try DuplicateScan.distinctPairKeys(context: context)+        if distinctPairs.contains(WorkPairKey(capturedID, toReadID)) { return false }+        let works = try context.fetch(FetchDescriptor<Work>())+        let sites = try context.fetch(FetchDescriptor<Site>())+        let types = try LibraryRepository.workTypeDirectory(context: context)+        let workSets = DuplicateScan.workSets(+            of: works, types: types, distinctPairs: distinctPairs)+        let pairRows = works.filter { $0.id == capturedID || $0.id == toReadID }+        return pairs(+            works: pairRows, sites: sites,+            groups: LibraryRepository.workGroups(pairRows, types: types),+            distinctPairs: distinctPairs, workSets: workSets+        ).contains { $0.capturedID == capturedID && $0.toReadID == toReadID }+    }++    // MARK: - Review items++    /// One review item per captured work with at least one pair (Req 3.1–3.4),+    /// sorted by captured UUID, its choices by to-read UUID.+    ///+    /// A blocked choice stays in its item so the reason shows, and an item+    /// whose choices are all blocked is still returned, because "None of these"+    /// is still an answer (Q35).+    static func candidates(+        works: [Work], sites: [Site], entries: [Entry],+        groups: [UUID: WorkGroup], distinctPairs: Set<WorkPairKey>,+        workSets: [WorkDuplicateSet],+        quarantine: [String: LibraryValidationError]+    ) -> [ToReadMatchItem] {+        let pairs = pairs(+            works: works, sites: sites, groups: groups, distinctPairs: distinctPairs,+            workSets: workSets)+        guard !pairs.isEmpty else { return [] }++        // Logical entries, counted off the to-one the publication has already+        // faulted — never through `work.entries`.+        let capturedIDs = Set(pairs.map(\.capturedID))+        var entryIDsByWork: [UUID: Set<UUID>] = [:]+        for entry in entries {+            guard let workID = entry.work?.id, capturedIDs.contains(workID) else { continue }+            entryIDsByWork[workID, default: []].insert(entry.id)+        }++        var items: [ToReadMatchItem] = []+        var index = pairs.startIndex+        while index < pairs.endIndex {+            let capturedID = pairs[index].capturedID+            let end = pairs[index...].firstIndex { $0.capturedID != capturedID } ?? pairs.endIndex+            let itemPairs = pairs[index..<end]+            index = end+            guard let capturedGroup = groups[capturedID] else { continue }+            let choices = itemPairs.compactMap { pair -> ToReadMatchItem.Choice? in+                guard let toReadGroup = groups[pair.toReadID] else { return nil }+                return ToReadMatchItem.Choice(+                    toReadWorkID: pair.toReadID, title: toReadGroup.carrier.displayTitle,+                    blocked: block(capturedGroup, toReadGroup, quarantine: quarantine))+            }+            items.append(ToReadMatchItem(+                capturedWorkID: capturedID,+                capturedTitle: capturedGroup.carrier.displayTitle,+                hostname: itemPairs.map(\.hostname).min() ?? "",+                entryCount: entryIDsByWork[capturedID]?.count ?? 0,+                choices: choices))+        }+        return items+    }++    /// Why merging the pair would be refused (Req 3.4), or nil. Quarantine+    /// first, because the commit refuses on it before the planner runs.+    private static func block(+        _ captured: WorkGroup, _ toRead: WorkGroup,+        quarantine: [String: LibraryValidationError]+    ) -> ToReadMatchBlock? {+        // The commit's own refusal, so a choice shows as blocked exactly when+        // the commit would refuse it; it names the lowest hostname.+        if let hostname = LibraryRepository.quarantinedHostnames(+            of: [captured, toRead], in: quarantine+        ).first {+            return .quarantined(hostname: hostname)+        }+        // The planner's test (`WorkMergePlanner.project`).+        if SeriesMembership.areInDifferentSeries(+            GroupOrdering.membership(of: captured.carrier),+            GroupOrdering.membership(of: toRead.carrier)) {+            return .seriesConflict+        }+        return nil+    }++    // MARK: - Helpers++    /// The pair without its hostname: the key under which `pairs` keeps the+    /// lowest matching hostname, which `MatchedPair` carries as a field.+    private struct PairIDs: Hashable {+        let captured: UUID+        let toRead: UUID+    }++    /// One work's memberships by hostname, from the rows of its group, one+    /// survivor kept per hostname. A blank hostname is on no site.+    ///+    /// Reads the inverse array, which the membership lint pins: every caller+    /// has built the Work sets over the same rows first, and that has already+    /// faulted it per Work (`DuplicateScan.WorkKeyRow`, Q39).+    private static func membershipsByHostname(+        _ rows: [Work]+    ) -> [String: WorkSiteMembership] {+        membershipsByHostname(rows.flatMap { $0.siteMemberships ?? [] })+    }++    private static func membershipsByHostname(+        _ rows: [WorkSiteMembership]+    ) -> [String: WorkSiteMembership] {+        var result: [String: WorkSiteMembership] = [:]+        for hostname in Set(rows.map(\.hostname)) where !M2Unicode.isBlank(hostname) {+            result[hostname] = Work.membership(in: rows, for: hostname)+        }+        return result+    }++    /// The site's current URL rule when it can supply a work identity, or nil+    /// (Req 2.3). An unreadable rule is no rule: no log, no diagnosis.+    private static func identityRule(of site: Site?) -> URLRuleDefinition? {+        guard let definition = try? site?.currentURLRule?.definition,+            definition.suppliesIdentity+        else { return nil }+        return definition+    }++    /// The work identity the rule reads from a to-read work's Work URL, exactly+    /// as it reads a captured URL, or nil where there is no rule, no Work URL,+    /// or the rule does not apply (Req 2.3, Q16).+    private static func workURLIdentity(+        of membership: WorkSiteMembership, rule: URLRuleDefinition?+    ) -> ExactScalarString? {+        guard let rule, let workURL = membership.workURLString,+            let extraction = try? URLRuleApplicator.apply(rule, to: ExactScalarString(workURL))+        else { return nil }+        return extraction.workIdentity+    }++    // MARK: - Titles++    /// The Definitions' normalised title, in Q27's order as Q44 amends it:+    /// NFKD, a locale-free full case fold, NFKD again, nonspacing marks and+    /// format characters dropped, punctuation and symbols to spaces, whitespace+    /// collapsed with the M2 set, trimmed.+    ///+    /// The fold comes before the marks are dropped because folding `İ` yields+    /// `i` plus U+0307: dropping first would leave a mark a second pass removes,+    /// and normalising would not be idempotent. The second NFKD is there for+    /// whatever the fold composes.+    ///+    /// Format characters (Cf: zero-width space and joiner, direction marks,+    /// soft hyphen, byte order mark) are removed rather than turned into+    /// spaces, because they sit inside words (Q44).+    static func normalise(_ title: String) -> NormalisedTitle {+        let folded = title.decomposedStringWithCompatibilityMapping+            .folding(options: .caseInsensitive, locale: nil)+            .decomposedStringWithCompatibilityMapping++        var text = String.UnicodeScalarView()+        var pendingSpace = false+        for scalar in folded.unicodeScalars {+            let category = scalar.properties.generalCategory+            if category == .nonspacingMark || category == .format { continue }+            if isPunctuationOrSymbol(category) || M2Unicode.isWhitespace(scalar) {+                // Collapsed and trimmed in one: a run becomes one space, and+                // only once a word follows it.+                pendingSpace = !text.isEmpty+                continue+            }+            if pendingSpace {+                text.append(" ")+                pendingSpace = false+            }+            text.append(scalar)+        }++        let string = String(text)+        // Split on the space scalar, not on `Character`: a space followed by+        // a spacing mark is one grapheme, and a `Character` split would not+        // separate the words there (Q44).+        let words = string.unicodeScalars.split(separator: " ").map(Substring.init)+        let length = string.unicodeScalars.count+        guard let first = words.first, articles.contains(first) else {+            return NormalisedTitle(+                text: string, words: words, countedWords: words.count, countedLength: length)+        }+        // The article, and the space after it where a word follows.+        let articleLength = first.unicodeScalars.count + (words.count > 1 ? 1 : 0)+        return NormalisedTitle(+            text: string, words: words, countedWords: words.count - 1,+            countedLength: length - articleLength)+    }++    /// Req 2.2's two title arms: equal and non-empty, or Req 2.4's whole-word+    /// prefix whose shorter side has at least three words or twelve scalars.+    static func titlesMatch(_ a: NormalisedTitle, _ b: NormalisedTitle) -> Bool {+        guard !a.text.isEmpty, !b.text.isEmpty else { return false }+        if a.words == b.words { return true }+        let (shorter, longer) = a.words.count <= b.words.count ? (a, b) : (b, a)+        return isPrefixMatch(shorter, of: longer)+    }++    /// Req 2.4 alone, for a caller that already knows the two are unequal and+    /// which is shorter.+    private static func isPrefixMatch(_ shorter: NormalisedTitle, of longer: NormalisedTitle) -> Bool {+        guard !shorter.words.isEmpty, shorter.words.count < longer.words.count,+            shorter.countedWords >= 3 || shorter.countedLength >= 12+        else { return false }+        return longer.words.starts(with: shorter.words)+    }++    private static func isPunctuationOrSymbol(_ category: Unicode.GeneralCategory) -> Bool {+        switch category {+        case .connectorPunctuation, .dashPunctuation, .openPunctuation, .closePunctuation,+            .initialPunctuation, .finalPunctuation, .otherPunctuation,+            .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol:+            true+        default:+            false+        }+    }+}
Packages/AsterismCore/Sources/AsterismCore/ToleratedStateFixture.swift Modified +72 / -1
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ToleratedStateFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/ToleratedStateFixture.swiftindex fe6a13ab..50703734 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ToleratedStateFixture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ToleratedStateFixture.swift@@ -35,12 +35,32 @@ public enum ToleratedStateFixtureKind: String, Sendable, CaseIterable {     /// Two Works sharing a URL identity, each holding notes: a divergent Work     /// set with no torn member, which routes to Merge (Req 5.3, Q30).     case divergentWorkSet+    /// One captured work paired with two to-read works on one site, one of+    /// them in a series that conflicts with the captured work's+    /// (`to-read-capture-match` Req 3.2, 3.4). Legal on every count: a to-read+    /// match is a question for the reader, not damage. The raw value is the+    /// scenario's own spelling, `seeded-tolerated-to-read-match`.+    case toReadMatch = "to-read-match" }  // The seeding itself is compiled only for Development or explicit Release // performance-test builds; the shape names above are not, because the UI-test // launch parser names them unconditionally. #if DEBUG || ASTERISM_PERFORMANCE_TESTING+/// The `.toReadMatch` shape's fixed identities, so a UI test can address the+/// card's choices by identifier (`to-read-match-<captured>-confirm-<to-read>`).+/// The UI-test bundle cannot import the package, so it spells the same three+/// strings itself.+public enum ToReadMatchFixture {+    public static let capturedWorkID = UUID(uuidString: "7E4D0000-0000-4000-8000-000000000001")!+    /// The to-read work the captured one can be merged into.+    public static let toReadWorkID = UUID(uuidString: "7E4D0000-0000-4000-8000-000000000002")!+    /// The to-read work in a conflicting series, listed but not offered.+    public static let conflictingToReadWorkID = UUID(+        uuidString: "7E4D0000-0000-4000-8000-000000000003")!+    public static let hostname = "toread.test"+}+ extension LibraryRepository {      /// A hostname that resolves normally in every fixture, so a test can tell@@ -49,7 +69,7 @@ extension LibraryRepository {      /// How far before the seeding instant the fixture's earliest row sits. Every     /// row is placed at `seededAt - toleratedFixtureLead + index`, and the-    /// largest index any shape uses is 61, so the whole fixture lands inside the+    /// largest index any shape uses is 73, so the whole fixture lands inside the     /// two minutes before the seed — one civil day, and the day the app opens on.     private static let toleratedFixtureLead: TimeInterval = 120 @@ -195,6 +215,57 @@ extension LibraryRepository {                     entry.work = work                     entry.editCitations { $0.workAssignment = .manual }                 }++            case .toReadMatch:+                let hostname = ToReadMatchFixture.hostname+                context.insert(Self.untaughtSite(hostname))+                let captureSeries = Series(name: "The Innverse")+                let otherSeries = Series(name: "Another Story")+                context.insert(captureSeries)+                context.insert(otherSeries)++                // The captured work: a parsed title that is the to-read one+                // plus a volume, two chapters, and a place in a series.+                let captured = Work.create(+                    in: context, id: ToReadMatchFixture.capturedWorkID,+                    title: "The Wandering Inn (Volume 1)", hostname: hostname,+                    timestamp: Self.toleratedInstant(70, from: seededAt))+                captured.lastParsedTitle = "The Wandering Inn (Volume 1)"+                captured.titleProvenance = .parsed+                captured.seriesID = captureSeries.id+                captured.seriesPosition = 1+                for index in 0..<2 {+                    let entry = Self.toleratedEntry(+                        captureTitle: "The Wandering Inn (Volume 1) - Chapter \(index + 1)",+                        hostname: hostname, path: "inn-\(index + 1)", index: 70 + index,+                        seededAt: seededAt)+                    context.insert(entry)+                    entry.work = captured+                    entry.editCitations { $0.workAssignment = .manual }+                }++                // Two to-read works as the New Work form leaves them: a typed+                // title, no parsed title (so no duplicate bucket), no entries.+                // The first matches by whole-word prefix; the second is equal+                // after normalising but sits in a different series, so its+                // choice is shown blocked (Req 3.4).+                let toReadWorks: [(id: UUID, title: String, seriesID: UUID?, offset: Int)] = [+                    (ToReadMatchFixture.toReadWorkID, "The Wandering Inn", nil, 72),+                    (+                        ToReadMatchFixture.conflictingToReadWorkID, "The Wandering Inn: Volume 1",+                        otherSeries.id, 73+                    ),+                ]+                for (id, title, seriesID, offset) in toReadWorks {+                    let work = Work.create(+                        in: context, id: id, title: title, hostname: hostname,+                        timestamp: Self.toleratedInstant(offset, from: seededAt))+                    work.readingStatus = .toRead+                    if let seriesID {+                        work.seriesID = seriesID+                        work.seriesPosition = 1+                    }+                }             }              // Plain `context.save()` (Boundaries.swift). The validating commit
Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift Modified +144 / -13
diff --git a/Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift b/Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swiftindex 23f7adc1..e54908fa 100644--- a/Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/WorkMergePlanner.swift@@ -15,13 +15,22 @@ public enum WorkMergeAuditFormatter {     ///   multi-line reader text (Req 2.3), so an unescaped one holding a blank     ///   line would end the structured region early and one holding     ///   `--- Merged from:` would forge a block boundary.+    /// - Parameter titleBeforeMerge: the title the reader typed on a to-read+    ///   work a `.toReadMatch` merge replaces (`to-read-capture-match` Req 4.4,+    ///   Q26). Its own labelled line directly under the header, because the+    ///   header names the captured work the notes below it came from. Escaped+    ///   like the header.     public static func block(         sourceTitle: String,         discardedWorkURLs: [(hostname: String, url: String)] = [],         sourceVerdict: String = "",-        sourceNotes: String+        sourceNotes: String,+        titleBeforeMerge: String? = nil     ) -> String {         var value = "--- Merged from: \(escapedField(sourceTitle)) ---"+        if let titleBeforeMerge {+            value += "\nTitle before merge: \(escapedField(titleBeforeMerge))"+        }         for discarded in discardedWorkURLs {             value += "\nWork URL (\(discarded.hostname)): \(discarded.url)"         }@@ -104,7 +113,9 @@ public enum WorkMergePlanner {             .map(\.snapshot)     } -    public static func project(_ basis: WorkMergeBasis) throws -> WorkMergeOutcome {+    public static func project(+        _ basis: WorkMergeBasis, request: WorkMergeRequest+    ) throws -> WorkMergeOutcome {         let source = basis.source.snapshot         let target = basis.target.snapshot @@ -114,8 +125,7 @@ public enum WorkMergePlanner {         // pick one. Refused by name, with each label the directory could resolve         // — the snapshots carry the displays the read already fetched, so the         // planner stays free of a directory of its own.-        if let targetMembership = target.membership, let sourceMembership = source.membership,-            targetMembership.seriesID != sourceMembership.seriesID {+        if SeriesMembership.areInDifferentSeries(target.membership, source.membership) {             throw WorkMergePlanningError.seriesConflict(                 targetSeries: resolvedName(target.series),                 sourceSeries: resolvedName(source.series))@@ -155,10 +165,24 @@ public enum WorkMergePlanner {         case (.none, .none):             thumbnail = .none         }-        let auditBlock = union.auditBlock-        let genericNotes = union.genericNotes+        var auditBlock = union.auditBlock+        var genericNotes = union.genericNotes         let genreTags = union.genreTags +        // `to-read-capture-match` Req 4.3, 4.4, **outside** the fold for the+        // cover's reason (Q17): the fold is shared with reader resolution, and+        // the overrides are this request's alone.+        var overlay: ToReadMatchOverlay?+        if request == .toReadMatch {+            let applied = toReadMatchOverlay(+                basis, union: union, retained: retained, discarded: discarded)+            retained = applied.retained+            discarded = applied.discarded+            auditBlock = applied.auditBlock+            genericNotes = applied.genericNotes+            overlay = applied+        }+         let targetEntries = basis.target.entries.filter { !$0.snapshot.intentionallyUnattached }         let sourceEntries = basis.source.entries.filter { !$0.snapshot.intentionallyUnattached } @@ -250,9 +274,9 @@ public enum WorkMergePlanner {         return WorkMergeOutcome(             sourceID: source.id,             targetID: target.id,-            displayTitle: target.displayTitle,-            lastParsedTitle: target.lastParsedTitle,-            titleProvenance: target.titleProvenance,+            displayTitle: overlay?.overrides.displayTitle ?? target.displayTitle,+            lastParsedTitle: overlay.map(\.overrides.lastParsedTitle) ?? target.lastParsedTitle,+            titleProvenance: overlay?.titleProvenance ?? target.titleProvenance,             typeDisplay: target.typeDisplay,             sites: sites,             genericNotes: genericNotes,@@ -270,9 +294,10 @@ public enum WorkMergePlanner {             movedPlaceCount: basis.movedPlaceCount,             // Req 7.3: the target's, as its type and its title are. The commit's             // target loop writes none of them, so the preview and the row agree.-            workStatus: target.workStatus,-            readingStatus: target.readingStatus,-            verdict: target.verdict,+            // A `.toReadMatch` overlay replaces them, and its commit writes them.+            workStatus: overlay?.workStatus ?? target.workStatus,+            readingStatus: overlay?.readingStatus ?? target.readingStatus,+            verdict: overlay?.overrides.verdict ?? target.verdict,             // V11: the fold decided the pair; the label is this planner's,             // because only it holds both sides' resolved displays. Both sides             // are in the same series wherever there is anything to discard —@@ -290,10 +315,116 @@ public enum WorkMergePlanner {             // V15 (Req 7.3): the target's, as its statuses and its type are. The             // commit's target loop writes none of them, so the preview and the             // row agree.-            releaseDays: target.releaseDays+            releaseDays: overlay?.releaseDays ?? target.releaseDays,+            rawOverrides: overlay?.overrides         )     } +    /// What a `.toReadMatch` merge changes about the ordinary outcome+    /// (`to-read-capture-match` Req 4.3, 4.4).+    private struct ToReadMatchOverlay {+        let overrides: WorkMergeRawOverrides+        let titleProvenance: TitleProvenance+        let readingStatus: ReadingStatus+        let workStatus: WorkStatus+        let releaseDays: [ReleaseDay]+        let retained: [WorkMergeField]+        let discarded: [WorkMergeField]+        let auditBlock: String+        let genericNotes: String+    }++    /// The fields the overlay decides for itself, removed from the fold's+    /// lists before it adds its own.+    private static let toReadMatchFields: Set<WorkMergeField> = [+        .targetDisplayTitle, .sourceManualTitle,+        .targetReadingStatus, .sourceReadingStatus,+        .targetWorkStatus, .sourceWorkStatus,+        .targetVerdict, .sourceVerdict,+        .targetReleaseDays, .sourceReleaseDays,+    ]++    /// Req 4.3 on top of the fold: the source's titles and reading status, and+    /// its work status, verdict and release days wherever the target still+    /// holds the New Work form's value for it.+    ///+    /// "Pristine" is decided on the target's **raw** columns (Q31): an unknown+    /// work status reads as `.ongoing` and an unknown day as no day, and either+    /// would pass for the form's default through the tolerated values. The+    /// winning side's raw value is what the survivor gets, so an unknown value+    /// is carried rather than rewritten (Q34).+    private static func toReadMatchOverlay(+        _ basis: WorkMergeBasis, union: WorkVariantUnionOutcome,+        retained: [WorkMergeField], discarded: [WorkMergeField]+    ) -> ToReadMatchOverlay {+        let source = basis.source+        let target = basis.target+        let sourceWork = source.snapshot+        let targetWork = target.snapshot++        let takesWorkStatus = target.workStatusRaw == WorkStatus.ongoing.rawValue+        let takesVerdict = M2Unicode.isBlank(targetWork.verdict)+        let takesReleaseDays = target.releaseDaysRaw.isEmpty++        var kept = retained.filter { !toReadMatchFields.contains($0) }+        var dropped = discarded.filter { !toReadMatchFields.contains($0) }+        // The typed title and the to-read status always go; neither is recorded+        // anywhere but the block's `Title before merge` line (Req 4.1).+        kept += [.sourceDisplayTitle, .sourceReadingStatus]+        dropped += [.targetManualTitle, .targetReadingStatus]++        // Each of the three: the winner is kept. A pristine target losing is not+        // a loss worth listing (Req 4.1); a source losing is, where it held+        // something the target does not — the fold's own terms, under which the+        // default work status, an empty verdict or an empty schedule+        // contributes nothing (Q42).+        kept.append(takesWorkStatus ? .sourceWorkStatus : .targetWorkStatus)+        if !takesWorkStatus, source.workStatusRaw != WorkStatus.ongoing.rawValue,+            source.workStatusRaw != target.workStatusRaw {+            dropped.append(.sourceWorkStatus)+        }+        let verdictLost = !takesVerdict && !M2Unicode.isBlank(sourceWork.verdict)+            && ExactScalarString(sourceWork.verdict) != ExactScalarString(targetWork.verdict)+        kept.append(takesVerdict ? .sourceVerdict : .targetVerdict)+        if verdictLost { dropped.append(.sourceVerdict) }+        kept.append(takesReleaseDays ? .sourceReleaseDays : .targetReleaseDays)+        if !takesReleaseDays, !source.releaseDaysRaw.isEmpty,+            Set(source.releaseDaysRaw) != Set(target.releaseDaysRaw) {+            dropped.append(.sourceReleaseDays)+        }++        // Req 4.4: always written, whatever the fold's own condition for a+        // block. The header still names the source, which is where the notes+        // under it came from; the typed title is its own line (Q18).+        let block = WorkMergeAuditFormatter.block(+            sourceTitle: sourceWork.displayTitle,+            discardedWorkURLs: union.discardedWorkURLsByHostname+                .sorted { $0.key < $1.key }+                .map { (hostname: $0.key, url: $0.value) },+            sourceVerdict: verdictLost ? sourceWork.verdict : "",+            sourceNotes: sourceWork.genericNotes,+            titleBeforeMerge: targetWork.displayTitle)++        return ToReadMatchOverlay(+            overrides: WorkMergeRawOverrides(+                displayTitle: sourceWork.displayTitle,+                lastParsedTitle: sourceWork.lastParsedTitle,+                titleProvenanceRaw: source.titleProvenanceRaw,+                readingStatusRaw: source.readingStatusRaw,+                workStatusRaw: takesWorkStatus ? source.workStatusRaw : target.workStatusRaw,+                verdict: takesVerdict ? sourceWork.verdict : targetWork.verdict,+                releaseDaysRaw: takesReleaseDays ? source.releaseDaysRaw : target.releaseDaysRaw),+            titleProvenance: sourceWork.titleProvenance,+            readingStatus: sourceWork.readingStatus,+            workStatus: takesWorkStatus ? sourceWork.workStatus : targetWork.workStatus,+            releaseDays: takesReleaseDays ? sourceWork.releaseDays : targetWork.releaseDays,+            retained: kept,+            discarded: dropped,+            auditBlock: block,+            genericNotes: WorkMergeAuditFormatter.append(+                block: block, to: targetWork.genericNotes))+    }+     /// `work-creators` Req 6.1/6.2 at projection: what the merged work gains     /// from the source, in the order the preview lists it.     ///
Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift Modified +42 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swiftindex a6dd067d..37d1bbfb 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift@@ -121,6 +121,48 @@ struct CrossSiteDuplicateScanTests {         #expect(Set(throughC.components[0].ids) == [Self.id(1), Self.id(2), Self.id(3)])     } +    // MARK: - A declined to-read match (`to-read-capture-match` Req 5.3)++    /// A decline is recorded while the two works share a site, where no+    /// cross-site title edge can exist (Q19). When one of them later leaves that+    /// site, their site sets become disjoint with equal parsed titles — the+    /// shape of a cross-site title edge — and the decline suppresses it, as a+    /// dismissal does. Without the decline the same library forms the set,+    /// which is what makes the first half not vacuous.+    @Test("A declined pair suppresses a later cross-site title edge", arguments: [true, false])+    func aDeclinedPairSuppressesALaterCrossSiteEdge(declined: Bool) async throws {+        let toRead = Self.id(1)+        let captured = Self.id(2)+        let fixture = try await M5Fixture()+        try await fixture.repository.seedM5Rows(+            sites: [M5SeedSite(hostname: "shared.example"), M5SeedSite(hostname: "own.example")],+            works: [+                // Distinct identities on the shared site, so it gives no key edge+                // either: the only edge this pair can ever have is the title.+                M5SeedWork(+                    id: toRead, displayTitle: "A Serial", hostname: "shared.example",+                    titleProvenance: .parsed, lastParsedTitle: "A Serial", urlIdentity: "1"),+                M5SeedWork(+                    id: captured, displayTitle: "A Serial", hostname: "shared.example",+                    titleProvenance: .parsed, lastParsedTitle: "A Serial", urlIdentity: "2"),+            ])+        try await fixture.repository.seedMembership(workID: toRead, hostname: "own.example")+        #expect(try await fixture.repository.m5Scan().workSets.isEmpty)++        if declined {+            try await fixture.repository.recordDistinctPairs([WorkPairKey(captured, toRead)])+        }+        try await fixture.repository.removeSiteMemberships(+            workID: toRead, hostnames: ["shared.example"])++        let sets = try await fixture.repository.m5Scan().workSets+        if declined {+            #expect(sets.isEmpty)+        } else {+            #expect(sets.map { Set($0.key.memberIDs) } == [[toRead, captured]])+        }+    }+     // MARK: - Property-style coverage (Req 5.1, 5.2, 5.3)      /// Over generated membership graphs: set membership is symmetric and
Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift Modified +128 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swiftindex 2cea9550..925c310c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateWorkloadTests.swift@@ -86,6 +86,134 @@ struct CrossSiteDuplicateWorkloadTests {         }     } +    // MARK: - Recording several pairs at once (`to-read-capture-match` Req 5.1, 5.2)++    /// Three Works on one site with unrelated titles: the captured work, the+    /// to-read work it was declined against, and one it is later folded into.+    private func declineFixture(+        saveStrategy: any RepositorySaveStrategy = ModelContextSaveStrategy()+    ) async throws -> M5Fixture {+        let fixture = try await M5Fixture(saveStrategy: saveStrategy)+        try await fixture.repository.seedM5Rows(+            sites: [M5SeedSite(hostname: "one.example")],+            works: [+                M5SeedWork(id: Self.first, displayTitle: "Mother of Learning", hostname: "one.example"),+                M5SeedWork(+                    id: Self.second, displayTitle: "mother of learning!", hostname: "one.example",+                    titleProvenance: .parsed, lastParsedTitle: "mother of learning!"),+                M5SeedWork(id: Self.third, displayTitle: "Zorian's Loop", hostname: "one.example"),+            ])+        return fixture+    }++    @Test("Every declined pair is recorded in one commit")+    func declinedPairsShareOneCommit() async throws {+        let saves = InstrumentedSaveStrategy()+        let fixture = try await declineFixture(saveStrategy: saves)+        saves.resetCounts()++        try await fixture.repository.recordDistinctPairs([+            WorkPairKey(Self.second, Self.first), WorkPairKey(Self.second, Self.third),+        ])++        #expect(saves.attemptCount == 1)+        #expect(+            Set(try await fixture.repository.m5DistinctPairRows().map {+                WorkPairKey($0.lowerWorkID, $0.higherWorkID)+            }) == [WorkPairKey(Self.first, Self.second), WorkPairKey(Self.second, Self.third)])+    }++    /// Req 5.8's idempotence, over a batch: recording the same pairs again, in+    /// either order and twice in one call, re-stamps rather than adds.+    @Test("Recording declined pairs again adds no row")+    func recordingDeclinedPairsIsIdempotent() async throws {+        let fixture = try await declineFixture()+        let pairs = [WorkPairKey(Self.second, Self.first), WorkPairKey(Self.second, Self.third)]+        try await fixture.repository.recordDistinctPairs(pairs)+        try await fixture.repository.recordDistinctPairs(+            pairs + [WorkPairKey(Self.first, Self.second)])++        #expect(try await fixture.repository.distinctPairCount() == 2)+    }++    @Test("A batch whose save fails records none of its pairs")+    func aFailedBatchRecordsNothing() async throws {+        let saves = InstrumentedSaveStrategy()+        let fixture = try await declineFixture(saveStrategy: saves)++        saves.shouldFail = true+        await #expect(throws: LibraryRepositoryError.self) {+            try await fixture.repository.recordDistinctPairs([+                WorkPairKey(Self.second, Self.first), WorkPairKey(Self.second, Self.third),+            ])+        }+        saves.shouldFail = false++        #expect(try await fixture.repository.distinctPairCount() == 0)+    }++    @Test("A batch naming a Work twice is refused whole")+    func aSelfPairRefusesTheBatch() async throws {+        let fixture = try await declineFixture()+        await #expect(throws: LibraryRepositoryError.self) {+            try await fixture.repository.recordDistinctPairs([+                WorkPairKey(Self.second, Self.first), WorkPairKey(Self.third, Self.third),+            ])+        }+        #expect(try await fixture.repository.distinctPairCount() == 0)+    }++    /// Req 5.2: a decline is an ordinary distinct pair, so it is in the archive+    /// and a restore brings it back.+    @Test("A declined pair survives a backup export and import")+    func aDeclinedPairSurvivesTheRoundTrip() async throws {+        let fixture = try await declineFixture()+        try await fixture.repository.recordDistinctPairs([WorkPairKey(Self.second, Self.first)])+        let archive = try BackupV15Codec.encode(+            payload: try await fixture.repository.backupV15Snapshot(),+            metadata: BackupV15Metadata(appBuild: "test", exportedAt: M5Fixture.epoch))++        let restored = try await M5Fixture()+        try await restored.repository.confirmImport(plan: try BackupImporter.plan(from: archive))++        #expect(+            try await restored.repository.m5DistinctPairRows()+                == (try await fixture.repository.m5DistinctPairRows()))+        #expect(try await restored.repository.distinctPairCount() == 1)+    }++    /// Req 5.2 and Q36: merging the captured work into another says the other+    /// is the same story, so the decline follows it.+    @Test("A declined pair is re-pointed through a later merge")+    func aDeclinedPairFollowsAMerge() async throws {+        let fixture = try await declineFixture()+        try await fixture.repository.recordDistinctPairs([WorkPairKey(Self.second, Self.first)])++        let contract = try await fixture.repository.projectMerge(+            sourceWorkID: Self.second, targetWorkID: Self.third)+        #expect(+            try await fixture.repository.commitMerge(contract) == .committed(targetID: Self.third))++        #expect(+            try await fixture.repository.m5DistinctPairRows().map {+                WorkPairKey($0.lowerWorkID, $0.higherWorkID)+            } == [WorkPairKey(Self.first, Self.third)])+    }++    @Test("A declined pair is re-pointed through a later duplicate collapse")+    func aDeclinedPairFollowsACollapse() async throws {+        let fixture = try await declineFixture()+        try await fixture.repository.recordDistinctPairs([WorkPairKey(Self.second, Self.first)])++        try await fixture.repository.collapseWorkMemberships(+            loser: Self.second, survivor: Self.third)++        #expect(+            try await fixture.repository.m5DistinctPairRows().map {+                WorkPairKey($0.lowerWorkID, $0.higherWorkID)+            } == [WorkPairKey(Self.first, Self.third)])+    }+     /// Task 8 review: a collapse must not delete a loser's membership for a     /// hostname the survivor is not on — that row is the only record that the     /// Work is on that site at all, and the reader-confirmed path can now
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift Modified +298 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swiftindex c16c0a2d..91c6689b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicatePublicationTests.swift@@ -430,6 +430,241 @@ struct DuplicatePublicationTests {         #expect(counts.works == 1)     } +    // MARK: - To-read matches (`to-read-capture-match` Req 1.2, 1.3, 3.1, 3.3)++    @Test("A to-read pair is published beside the duplicate sets and counts in none of them")+    func toReadMatchIsPublished() async throws {+        let library = try PublicationFixture()+        let captured = UUID()+        let toRead = UUID()+        try library.seed { store in+            store.insertSite(hostname: "dup.example")+            let work = store.insertWork(+                id: captured, hostname: "dup.example", title: "Mother of Learning", offset: 0)+            store.insertEntry(hostname: "dup.example", key: "one", title: "One", offset: 0, work: work)+            store.insertToReadWork(id: toRead, hostname: "dup.example", title: "Mother of Learning")+        }+        let repository = try await library.openForApp()++        let workload = try await repository.todayPresentation(calendar: .current).duplicateWorkload++        #expect(workload.toReadMatches.map(\.capturedWorkID) == [captured])+        let item = try #require(workload.toReadMatch(for: captured))+        #expect(item.entryCount == 1)+        #expect(item.hostname == "dup.example")+        #expect(item.choices.map(\.toReadWorkID) == [toRead])+        #expect(workload.toReadMatch(for: toRead) == nil)+        // Q29: the duplicate-set views describe duplicate sets only.+        #expect(workload.reviewCount == 0)+        #expect(workload.isEmpty)+        #expect(workload.allItems.isEmpty)+    }++    /// The UI scenario's seeder guard (`docs/agent-notes/testing.md`): the+    /// shape the to-read UI journeys walk publishes exactly the item they+    /// expect, so a seeder that drifts fails here rather than as a UI timeout.+    @Test("The seeded to-read scenario publishes one item with one offered and one blocked choice")+    func seededToReadScenarioPublishesItsItem() async throws {+        let directory = FileManager.default.temporaryDirectory+            .appending(path: "AsterismToReadScenario-\(UUID())", directoryHint: .isDirectory)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        defer { try? FileManager.default.removeItem(at: directory) }+        let (_, repository) = try await LibraryRepository.openForApp(+            LibraryConfiguration(rootDirectory: directory), capabilities: .multiSite)+        try await repository.seedToleratedStateFixture(.toReadMatch)++        let workload = try await repository.todayPresentation(calendar: .current).duplicateWorkload++        #expect(workload.isEmpty)+        let item = try #require(workload.toReadMatch(for: ToReadMatchFixture.capturedWorkID))+        #expect(workload.toReadMatches.count == 1)+        #expect(item.capturedTitle == "The Wandering Inn (Volume 1)")+        #expect(item.hostname == ToReadMatchFixture.hostname)+        #expect(item.entryCount == 2)+        #expect(+            item.choices.map(\.toReadWorkID)+                == [ToReadMatchFixture.toReadWorkID, ToReadMatchFixture.conflictingToReadWorkID])+        #expect(item.choices.map(\.blocked) == [nil, .seriesConflict])+    }++    /// Req 1.2: the capture path, which never waits on a publication, still+    /// produces a pair the next publication shows.+    @Test("A pair a capture creates appears at the next publication")+    func captureCreatesAPair() async throws {+        let fixture = try await ToReadCaptureFixture()+        try await fixture.teach()+        let toRead = try await fixture.repository.createWork(+            NewWorkDraft(+                displayTitle: "Mother of Learning", hostname: "example.com",+                readingStatus: .toRead))+        #expect(+            try await fixture.repository.todayPresentation(calendar: .current)+                .duplicateWorkload.toReadMatches.isEmpty)++        // Not the exact title, so capture matching mints a second work.+        let entry = try await fixture.capture(+            title: "Mother of Learning (Book 1) - Chapter 1",+            rawURL: "https://example.com/read?id=mol&chapter=1")+        let captured = try #require(entry.workID)+        #expect(captured != toRead.id)++        let matches = try await fixture.repository.todayPresentation(calendar: .current)+            .duplicateWorkload.toReadMatches+        #expect(matches.map(\.capturedWorkID) == [captured])+        #expect(matches.first?.choices.map(\.toReadWorkID) == [toRead.id])+    }++    @Test("A pair a sync-shaped insert creates appears at the next publication")+    func syncInsertCreatesAPair() async throws {+        let library = try PublicationFixture()+        let captured = UUID()+        try library.seed { store in+            store.insertSite(hostname: "dup.example")+            store.insertWork(+                id: captured, hostname: "dup.example", title: "The Wandering Inn (Volume 1)",+                offset: 0)+        }+        let repository = try await library.openForApp()+        #expect(+            try await repository.todayPresentation(calendar: .current)+                .duplicateWorkload.toReadMatches.isEmpty)++        // Rows arriving behind the repository's back, as a mirror delivers them.+        let toRead = UUID()+        try library.seed { store in+            store.insertToReadWork(id: toRead, hostname: "dup.example", title: "The Wandering Inn")+        }++        let matches = try await repository.todayPresentation(calendar: .current)+            .duplicateWorkload.toReadMatches+        #expect(matches.map(\.capturedWorkID) == [captured])+        #expect(matches.first?.choices.map(\.toReadWorkID) == [toRead])+    }++    @Test("A pair an import creates appears at the next publication")+    func importCreatesAPair() async throws {+        let source = try await M5Fixture()+        let captured = try await source.repository.createWork(+            NewWorkDraft(displayTitle: "Beware of Chicken: Volume 1", hostname: "example.com"))+        let toRead = try await source.repository.createWork(+            NewWorkDraft(+                displayTitle: "Beware of Chicken", hostname: "example.com", readingStatus: .toRead))+        let archive = try BackupV15Codec.encode(+            payload: try await source.repository.backupV15Snapshot(),+            metadata: BackupGoldenLibrary.metadata)++        let target = try await M5Fixture()+        #expect(+            try await target.repository.todayPresentation(calendar: .current)+                .duplicateWorkload.toReadMatches.isEmpty)+        try await target.repository.confirmImport(plan: try BackupImporter.plan(from: archive))++        let matches = try await target.repository.todayPresentation(calendar: .current)+            .duplicateWorkload.toReadMatches+        #expect(matches.map(\.capturedWorkID) == [captured.id])+        #expect(matches.first?.choices.map(\.toReadWorkID) == [toRead.id])+    }++    /// The scan, the gate counters and the pass itself are the same whether or+    /// not a to-read work that pairs is present.+    ///+    /// A regression guard, not evidence for Req 1.3. The scan and the pass+    /// never call the matcher, so this holds by construction today; what Req+    /// 1.3 rests on is that structure (Decision 1). The test is here to fail if+    /// someone later wires candidates into the scan or the pass.+    @Test("A reconcile pass is unchanged by to-read works")+    func reconcileIgnoresToReadWorks() async throws {+        let captured = UUID(uuidString: "A0000000-0000-4000-8000-000000000001")!+        let sharedEntry = UUID(uuidString: "A0000000-0000-4000-8000-000000000002")!+        let toRead = UUID(uuidString: "A0000000-0000-4000-8000-000000000003")!++        func library(withToRead: Bool) throws -> PublicationFixture {+            let library = try PublicationFixture()+            try library.seed { store in+                store.insertSite(hostname: "dup.example")+                let work = store.insertWork(+                    id: captured, hostname: "dup.example", title: "Mother of Learning", offset: 0)+                // A divergent Entry set, so the scan and the pass have work.+                store.insertEntry(+                    id: sharedEntry, hostname: "dup.example", key: "one", title: "A", offset: 0,+                    note: "first", work: work)+                store.insertEntry(+                    id: sharedEntry, hostname: "dup.example", key: "one", title: "A", offset: 5,+                    note: "second", work: work)+                if withToRead {+                    store.insertToReadWork(+                        id: toRead, hostname: "dup.example", title: "Mother of Learning")+                }+            }+            return library+        }++        let without = try library(withToRead: false)+        let with = try library(withToRead: true)+        #expect(+            try DuplicateScan.run(context: try with.readContext())+                == DuplicateScan.run(context: try without.readContext()))+        #expect(+            try LibraryToleranceScan.scan(context: try with.readContext()).duplicateCandidateCount+                == LibraryToleranceScan.scan(context: try without.readContext())+                .duplicateCandidateCount)++        let withRepository = try await with.openForApp()+        let withoutRepository = try await without.openForApp()+        // The pair is there to be ignored.+        #expect(+            try await withRepository.todayPresentation(calendar: .current)+                .duplicateWorkload.toReadMatches.count == 1)+        let withOutcome = try await withRepository.reconcileAfterSync(tier: .full)+        let withoutOutcome = try await withoutRepository.reconcileAfterSync(tier: .full)+        #expect(withOutcome == withoutOutcome)+        #expect(+            try DuplicateScan.run(context: try with.readContext())+                == DuplicateScan.run(context: try without.readContext()))+    }++    /// Req 3.3. The merge that confirms a pair lands in the merge planner;+    /// here the survivor is seeded as that merge leaves it: the captured work+    /// gone, the to-read work holding its title and reading status.+    @Test("A to-read work confirmed on one item leaves every other item")+    func confirmedToReadLeavesOtherItems() async throws {+        let library = try PublicationFixture()+        let first = UUID(uuidString: "B0000000-0000-4000-8000-000000000001")!+        let second = UUID(uuidString: "B0000000-0000-4000-8000-000000000002")!+        let toRead = UUID(uuidString: "B0000000-0000-4000-8000-000000000003")!+        try library.seed { store in+            store.insertSite(hostname: "dup.example")+            store.insertWork(+                id: first, hostname: "dup.example", title: "Mother of Learning", offset: 0)+            store.insertWork(+                id: second, hostname: "dup.example", title: "Mother of Learning (Book 2)",+                offset: 5)+            store.insertToReadWork(id: toRead, hostname: "dup.example", title: "Mother of Learning")+        }+        let repository = try await library.openForApp()+        let before = try await repository.todayPresentation(calendar: .current)+            .duplicateWorkload.toReadMatches+        #expect(before.map(\.capturedWorkID) == [first, second])+        #expect(before.map { $0.choices.map(\.toReadWorkID) } == [[toRead], [toRead]])++        try library.seed { store in+            for work in try store.context.fetch(FetchDescriptor<Work>()) where work.id == first {+                for membership in work.siteMemberships ?? [] { store.context.delete(membership) }+                store.context.delete(work)+            }+            for work in try store.context.fetch(FetchDescriptor<Work>()) where work.id == toRead {+                work.readingStatus = .reading+                work.lastParsedTitle = "Mother of Learning"+                work.titleProvenance = .parsed+            }+        }++        let after = try await repository.todayPresentation(calendar: .current)+            .duplicateWorkload+        #expect(after.toReadMatches.isEmpty)+        #expect(after.toReadMatch(for: second) == nil)+    }+     // MARK: - Scan-shaped helpers      private static func entrySet(@@ -588,6 +823,19 @@ private final class PublicationSeedStore {         return work     } +    /// A work as the New Work form makes it (`to-read` Req 2.1): a manual+    /// title, no parsed title, reading status `toRead`.+    @discardableResult+    func insertToReadWork(id: UUID = UUID(), hostname: String, title: String) -> Work {+        let work = Work.create(+            in: context, id: id, title: title, hostname: hostname,+            site: try? LibraryRepository.fetchSites(hostname: hostname, context: context).first,+            timestamp: PublicationFixture.epoch)+        work.titleProvenance = .manual+        work.readingStatus = .toRead+        return work+    }+     @discardableResult     func insertTitlePattern(         id: UUID = UUID(), site: Site, isActive: Bool = false, version: Int = 1,@@ -602,3 +850,53 @@ private final class PublicationSeedStore {         return pattern     } }++/// A library whose one site is taught well enough for `projectCapture` to mint+/// a Work — the shape `ReleaseDayWritePathTests` uses, because `capture(_:)`+/// applies no rules (`docs/agent-notes/testing.md`).+private struct ToReadCaptureFixture {+    let directory: URL+    let repository: LibraryRepository++    init() async throws {+        directory = FileManager.default.temporaryDirectory+            .appending(path: "AsterismToReadCapture-\(UUID())", directoryHint: .isDirectory)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        repository = try await LibraryRepository.openForApp(+            LibraryConfiguration(rootDirectory: directory),+            clock: FixedRepositoryClock(PublicationFixture.epoch),+            saveStrategy: ModelContextSaveStrategy()).repository+    }++    /// Teaching needs a `Site` row, and the conservative capture door mints+    /// one.+    func teach() async throws {+        _ = try await repository.capture(+            CaptureDraft(+                captureTitle: "A Serial - Chapter 0", captureTitleSource: .manual,+                rawURLString: "https://example.com/read?id=serial&chapter=0",+                canonicalURLString: nil, note: "", rating: nil))+        let contract = try await repository.projectComposedTeaching(+            hostname: "example.com",+            request: ComposedTeachingRequest(+                titleDefinition: .phrase(+                    prefix: "", separator: " - ", suffix: "", order: .workThenChapter),+                urlDefinition: .workAndSequence(+                    work: URLFieldSelector(locator: .query(name: ExactScalarString("id"))),+                    sequence: URLFieldSelector(+                        locator: .query(name: ExactScalarString("chapter"))))))+        guard case .committed = try await repository.commitComposedTeaching(contract) else {+            throw CocoaError(.fileWriteUnknown)+        }+    }++    func capture(title: String, rawURL: String) async throws -> EntrySnapshot {+        let contract = try await repository.projectCapture(+            hostname: "example.com", captureTitle: title, captureTitleSource: .safariDocument,+            rawURLString: rawURL, canonicalURLString: nil, note: "", rating: nil)+        guard case .committed(let snapshot) = try await repository.commitCapture(contract) else {+            throw CocoaError(.fileWriteUnknown)+        }+        return snapshot+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/M4ToReadMatchScalePerformanceTests.swift Added +240 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToReadMatchScalePerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToReadMatchScalePerformanceTests.swiftnew file mode 100644index 00000000..e1415605--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToReadMatchScalePerformanceTests.swift@@ -0,0 +1,240 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++// MARK: - What the to-read match costs at M4 scale (Req 6.1, 6.2)++/// `to-read-capture-match`'s scale measurements, in the house style of the M4+/// suites next door: the whole `PerformanceDistribution` is recorded, the+/// `median` is what any assertion rests on, the `p95` is asserted only under+/// `CONTROLLED=1`, and every number is reported either way. Run with+/// `make test-performance-m4`.+///+/// **The fixture is layered, not perturbed.** `seedM4ToReadMatchLayer` adds 50+/// to-read works and the 10 captured works its prefix arm pairs with to the+/// seeded 1,000-Work / 5,000-Entry graph, in a store of this suite's own. Req+/// 6.1's "no existing arm's input or band changes" is answered by the other+/// suites measuring their own untouched stores; `todayPublication` keeps its+/// fixture and its number.+///+/// **Nothing here is comparable to a device.** Every number is host-only and+/// comparable to a later run of the same command on the same machine and to+/// nothing else. The bands are recorded with the spec, never in this file.+@Suite(+    "M4 to-read match scale budgets", .serialized,+    .enabled(if: ProcessInfo.processInfo.environment["ASTERISM_RUN_PHYSICAL_PERFORMANCE"] == "1"))+struct M4ToReadMatchScalePerformanceTests {++    private let iterations = 20++    /// Req 6.1's figure, asserted as the requirement names it, and the only+    /// assertion on the arm (Q52). No regression ceiling sits below it: the+    /// fixture already runs the matcher's single-bucket worst case — every+    /// title starts with `story` (Q46), so every to-read work scans the whole+    /// 1,010-work first-word bucket (Q41) — and a matcher that stopped+    /// bucketing would do the same work here, so a ceiling could catch+    /// nothing the budget does not. First measured at 0.0196–0.0198 s median+    /// on a loaded host. Most of the arm is normalising the thousand captured+    /// titles on the fixture's one hostname, not comparing them.+    private let derivationBudget = Duration.milliseconds(100)+    /// Req 6.2: the existing Today budget, unchanged.+    private let todayPublishBudget = Duration.seconds(2)+    /// Above the budget rather than below it: the publication is a 5,000-Entry+    /// read whose band belongs to `todayPublication`, and this arm only has to+    /// show that the matcher adds nothing to it. The ceiling keeps a run that+    /// drifts past the budget failing loudly if the budget is ever moved into a+    /// known-issue block.+    private let publicationCeiling = Duration.seconds(3)++    // MARK: - Req 6.1 — candidate derivation alone++    @Test("Deriving to-read candidates over 50 to-read works ≤ 100 ms (Req 6.1)")+    func derivationOverLayeredFixture() async throws {+        let store = try await M4ToReadMatchPerformanceStore()+        let container = try LibraryRepository.openContainer(at: store.storeURL)+        defer { withExtendedLifetime(container) {} }+        let context = ModelContext(container)++        // The inputs, fetched and built outside the timer exactly as+        // `todayPresentation` builds them: the publication already holds every+        // one of them for its own projection, so what Req 6.1 adds to it is the+        // `candidates` call alone.+        let entries = try context.fetch(FetchDescriptor<Entry>())+        let works = try context.fetch(FetchDescriptor<Work>())+        let sites = try context.fetch(FetchDescriptor<Site>())+        let types = try LibraryRepository.workTypeDirectory(context: context)+        let distinctPairs = try DuplicateScan.distinctPairKeys(context: context)+        let workSets = DuplicateScan.workSets(+            of: works, types: types, distinctPairs: distinctPairs)+        let groups = LibraryRepository.workGroups(works, types: types)++        func derive() -> [ToReadMatchItem] {+            ToReadMatcher.candidates(+                works: works, sites: sites, entries: entries, groups: groups,+                distinctPairs: distinctPairs, workSets: workSets, quarantine: [:])+        }++        // Correctness once, before the timer: a derivation that paired nothing+        // would be a fast number about the wrong thing.+        let items = derive()+        expectFixtureShape(items)++        // Accumulated and asserted after the closure, so the optimiser cannot+        // drop a result nobody reads.+        var derived = 0+        let measured = measureDistribution(iterations: iterations) {+            derived += derive().count+        }+        #expect(derived >= LibraryRepository.m4ToReadMatchPairCount * iterations)+        expectWithinBudget("to-read-match-derivation", measured, derivationBudget)+    }++    // MARK: - Req 6.2 — Today's publication with to-read works present++    /// The existing `todayPublication` arm keeps its own fixture and budget;+    /// this one is the same read over the layered store, so the matcher is+    /// inside the interval with real pairs to find.+    @Test("Publishing Today with 50 to-read works present ≤ 2 s (Req 6.2)")+    func publicationOverLayeredFixture() async throws {+        let store = try await M4ToReadMatchPerformanceStore()+        let repository = try await store.openApp()++        var calendar = Calendar(identifier: .gregorian)+        calendar.timeZone = try #require(TimeZone(identifier: "UTC"))++        let measured = try await measureDistributionAsync(iterations: iterations) {+            _ = try await repository.todayPresentation(calendar: calendar)+        }+        expectWithinBudget("to-read-match-publication", measured, todayPublishBudget)+        expectWithinCeiling("to-read-match-publication", measured, publicationCeiling)++        let presentation = try await repository.todayPresentation(calendar: calendar)+        expectFixtureShape(presentation.duplicateWorkload.toReadMatches)+    }++    // MARK: - Req 4.6 — the merge commit's re-check, reported++    /// Reported only, with no budget: the re-check runs under the exclusive+    /// lock on every confirm, and the number is here so that cost is on record.+    /// A fresh `ModelContext` per sample, built outside the timer, because the+    /// commit runs it in its own locked context rather than one that already+    /// holds every row.+    @Test("Re-checking one to-read pair under the merge commit (Req 4.6, reported)")+    func recheckOverLayeredFixture() async throws {+        let store = try await M4ToReadMatchPerformanceStore()+        let container = try LibraryRepository.openContainer(at: store.storeURL)+        defer { withExtendedLifetime(container) {} }++        // The first equal pair: to-read `STORY 0` against base `Story 0`.+        let toReadID = LibraryRepository.m4FixtureUUID(namespace: 31, index: 0)+        let capturedTitle = LibraryRepository.m4FixtureWorkTitle(workIndex: 0)+        let capturedID = try #require(+            try ModelContext(container).fetch(+                FetchDescriptor<Work>(predicate: #Predicate { $0.displayTitle == capturedTitle })+            ).first?.id)++        var samples: [Duration] = []+        let clock = ContinuousClock()+        for iteration in 0..<(iterations + 1) {+            let context = ModelContext(container)+            let start = clock.now+            let isCandidate = try ToReadMatcher.isCandidate(+                capturedID: capturedID, toReadID: toReadID, context: context)+            let elapsed = clock.now - start+            #expect(isCandidate, "iteration \(iteration) must still find the pair")+            if iteration > 0 { samples.append(elapsed) }+        }+        reportPerformance("to-read-match-recheck", PerformanceDistribution(samples))+    }++    // MARK: - Helpers++    /// The layer's shape, as the matcher must see it: one item per equal or+    /// prefix to-read work, one unblocked choice each, and no near miss.+    private func expectFixtureShape(+        _ items: [ToReadMatchItem], sourceLocation: SourceLocation = #_sourceLocation+    ) {+        #expect(+            items.count == LibraryRepository.m4ToReadMatchPairCount,+            "every equal and prefix to-read work must pair, got \(items.count) items",+            sourceLocation: sourceLocation)+        #expect(+            items.allSatisfy { $0.choices.count == 1 && $0.choices[0].blocked == nil },+            "each item must carry one unblocked choice", sourceLocation: sourceLocation)+        let matchedToRead = Set(items.flatMap { $0.choices.map(\.toReadWorkID) })+        let expected = Set(+            (0..<LibraryRepository.m4ToReadMatchPairCount).map {+                LibraryRepository.m4FixtureUUID(namespace: 31, index: $0)+            })+        #expect(+            matchedToRead == expected, "no near miss may pair, and every match must",+            sourceLocation: sourceLocation)+    }++    /// A copy of the private helper the other M4 suites keep, for their reason:+    /// what they share is a message naming their own band, and nothing else.+    private func expectWithinCeiling(+        _ label: String,+        _ measured: PerformanceDistribution,+        _ ceiling: Duration,+        sourceLocation: SourceLocation = #_sourceLocation+    ) {+        #expect(+            measured.median <= ceiling,+            """+            \(label) median \(measured.median) exceeded the \(ceiling) regression \+            ceiling (p95 \(measured.p95), spread \(measured.spread)x) — this is not a \+            requirement budget; the band it sits above is recorded with \+            specs/to-read-capture-match+            """,+            sourceLocation: sourceLocation)+        if PerformanceDistribution.assertsTailBudget {+            #expect(+                measured.p95 <= ceiling,+                "\(label) p95 \(measured.p95) exceeded \(ceiling) on a run declared controlled",+                sourceLocation: sourceLocation)+        }+    }+}++// MARK: - Fixture: the 1,000-Work graph with the to-read layer over it++/// The composed M4 fixture on disk with `seedM4ToReadMatchLayer` layered over+/// it, certified ready, with the seeding repository released before anything+/// is measured. A copy of `M4SeriesPerformanceStore`, for that store's reason.+private final class M4ToReadMatchPerformanceStore {+    let root: URL+    let configuration: LibraryConfiguration+    var storeURL: URL { configuration.storeURL }++    init() async throws {+        root = FileManager.default.temporaryDirectory+            .appending(+                path: "asterism-m4-to-read-perf-\(UUID().uuidString)",+                directoryHint: .isDirectory)+        configuration = LibraryConfiguration(rootDirectory: root)+        try FileManager.default.createDirectory(+            at: configuration.storeURL.deletingLastPathComponent(),+            withIntermediateDirectories: true)++        let container = try LibraryRepository.openContainer(at: configuration.storeURL)+        let seeder = LibraryRepository.makeRepository(+            configuration, container, .m4, SystemRepositoryClock(), ModelContextSaveStrategy())+        try await seeder.seedM4PerformanceFixture()+        try await seeder.seedM4ToReadMatchLayer()+        try LibraryRepository.publishReadiness(at: configuration.readinessMarkerURL)+        withExtendedLifetime(container) {}+    }++    func openApp() async throws -> LibraryRepository {+        let (_, repository) = try await LibraryRepository.openForApp(+            configuration, capabilities: .multiSite)+        return repository+    }++    deinit {+        try? FileManager.default.removeItem(at: root)+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift Modified +7 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swiftindex 353871bf..9a35b41b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift@@ -142,6 +142,13 @@ struct MultiSiteReadPathTests {             "LibraryRepository.swift", "LibraryValidator.swift",             "LibraryRepository+DuplicateResolution.swift", "LibraryRepository+Sites.swift",             "LibraryRepository+WorkDeletion.swift", "LibraryRepository+WorkMerge.swift",+            // `to-read-capture-match`: the candidate derivation buckets every+            // work by membership hostname. Both of its callers have just built+            // the Work sets over the same rows, and `DuplicateScan.WorkKeyRow`+            // reads `membershipValues` per Work, so the relationship is+            // already faulted; a membership fetch would be a second read of a+            // table the pass already holds.+            "ToReadMatcher.swift",         ]          var found: Set<String> = []
Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift Added +967 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swiftnew file mode 100644index 00000000..2e48a5b3--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift@@ -0,0 +1,967 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++/// `to-read-capture-match`: the title normalisation and match rule (Req 2.2,+/// 2.4, Definitions), and the candidate derivation over library rows (Req 1.1,+/// 2.1–2.5, 3.1–3.5).+@Suite("To-read capture match", .serialized)+struct ToReadMatcherTests {++    // MARK: - Normalisation (Definitions, Q15, Q21, Q27)++    /// Written first: the design assumes `folding(.caseInsensitive, locale:+    /// nil)` applies **full** case folding, and `ß` is the scalar a simple fold+    /// leaves alone.+    @Test("Full case folding turns ß into ss")+    func sharpSFoldsToDoubleS() {+        #expect(ToReadMatcher.normalise("Straße").text == "strasse")+        #expect(ToReadMatcher.normalise("ẞ").text == "ss")+        #expect(+            ToReadMatcher.titlesMatch(+                ToReadMatcher.normalise("Die Straße"), ToReadMatcher.normalise("DIE STRASSE")))+    }++    /// Q27: folding `İ` yields `i` plus U+0307, so marks are removed after the+    /// fold. A locale-free fold also means the dotted capital reads as `i` on+    /// every device, whatever its region.+    @Test("İ folds to a plain i, and normalising is idempotent over it")+    func dottedCapitalI() {+        let title = ToReadMatcher.normalise("İstanbul Nights")+        #expect(title.text == "istanbul nights")+        #expect(ToReadMatcher.normalise(title.text) == title)+        #expect(+            ToReadMatcher.titlesMatch(title, ToReadMatcher.normalise("ISTANBUL NIGHTS")))+    }++    @Test("Full-width Latin and an ideographic space normalise to ASCII")+    func fullWidthLatin() {+        let title = ToReadMatcher.normalise("Mother\u{3000}of\u{3000}Learning")+        #expect(title.text == "mother of learning")+        #expect(title.words == ["mother", "of", "learning"])+    }++    @Test("Punctuation and symbols become spaces, collapsed and trimmed")+    func punctuationAndSymbols() {+        let title = ToReadMatcher.normalise("  Beware   of—Chicken: ★ A Novel!  ")+        #expect(title.text == "beware of chicken a novel")+        #expect(title.words.count == 5)+    }++    /// Req 2.4 and the Definitions: a leading article is counted in neither+    /// the words nor the length, but stays in the text every comparison reads.+    @Test("A leading article is kept in the text and left out of the counts")+    func leadingArticle() {+        let wandering = ToReadMatcher.normalise("The Wandering Inn")+        #expect(wandering.text == "the wandering inn")+        #expect(wandering.words == ["the", "wandering", "inn"])+        #expect(wandering.countedWords == 2)+        #expect(wandering.countedLength == 13)++        let plain = ToReadMatcher.normalise("Beware of Chicken")+        #expect(plain.countedWords == 3)+        #expect(plain.countedLength == 17)++        // Only a leading article, and only as a whole word.+        let another = ToReadMatcher.normalise("Another Day")+        #expect(another.countedWords == 2)+        #expect(another.countedLength == 11)+    }++    // MARK: - Invisible characters and the word split (Q44)++    /// A trailing left-to-right mark is what a title copied from a+    /// right-to-left page carries, and it is invisible in the title field.+    @Test("A trailing left-to-right mark is removed")+    func leftToRightMarkRemoved() {+        let title = ToReadMatcher.normalise("Mother of Learning\u{200E}")+        #expect(title.text == "mother of learning")+        #expect(+            ToReadMatcher.titlesMatch(title, ToReadMatcher.normalise("Mother of Learning")))+    }++    /// Format characters are removed, not turned into spaces: a zero-width+    /// space or a soft hyphen sits *inside* a word.+    @Test("A zero-width space, a soft hyphen and a byte order mark are removed inside a word")+    func formatCharactersRemovedInsideWords() {+        #expect(ToReadMatcher.normalise("Mother of Lear\u{200B}ning").text == "mother of learning")+        #expect(ToReadMatcher.normalise("Mother of Learn\u{00AD}ing").text == "mother of learning")+        #expect(ToReadMatcher.normalise("\u{FEFF}Mother of Learning").text == "mother of learning")+        #expect(ToReadMatcher.normalise("Moth\u{200D}er of\u{200F} Learning").text == "mother of learning")+        #expect(+            ToReadMatcher.normalise("Mother of Learn\u{00AD}ing").words+                == ["mother", "of", "learning"])+    }++    /// The emoji become spaces and the joiners between them are removed, so+    /// nothing is left after the title's own three words.+    @Test("A trailing joined emoji leaves the title's three words")+    func joinedEmojiLeavesThreeWords() {+        let title = ToReadMatcher.normalise("Beware of Chicken 👨‍👩‍👧")+        #expect(title.text == "beware of chicken")+        #expect(title.words == ["beware", "of", "chicken"])+        #expect(+            ToReadMatcher.titlesMatch(title, ToReadMatcher.normalise("Beware of Chicken")))+    }++    /// Words are split on the space scalar, not on `Character`: a space+    /// followed by a spacing combining mark (U+0903) is one grapheme, and a+    /// `Character` split would not separate the words there.+    @Test("Words split on the space scalar even where a mark follows it")+    func wordsSplitOnSpaceScalar() {+        let title = ToReadMatcher.normalise("Beware of \u{0903}Chicken")+        #expect(title.words.count == 3)+        #expect(title.words.first == "beware")+        #expect(title.words.joined(separator: " ") == title.text)+        #expect(title.countedWords == 3)+    }++    @Test("An article-only title counts nothing and prefixes nothing")+    func articleOnlyTitle() {+        let the = ToReadMatcher.normalise("The")+        #expect(the.text == "the")+        #expect(the.countedWords == 0)+        #expect(the.countedLength == 0)+        // Equal text is still equal (Req 2.2's equality arm has no floor)…+        #expect(ToReadMatcher.titlesMatch(the, ToReadMatcher.normalise("THE!")))+        // …but it clears no prefix floor.+        #expect(!ToReadMatcher.titlesMatch(the, ToReadMatcher.normalise("The Wandering Inn")))+    }++    // MARK: - The Req 2.4 table++    struct TitleCase: Sendable, CustomTestStringConvertible {+        let toRead: String+        let captured: String+        let matches: Bool++        var testDescription: String { "\(toRead) / \(captured) → \(matches)" }+    }++    /// A struct argument, not a tuple: a tuple-argument case can compile and+    /// never run (`docs/agent-notes/testing.md`).+    static let requirementTable: [TitleCase] = [+        TitleCase(toRead: "Mother of Learning", captured: "mother of learning!", matches: true),+        TitleCase(toRead: "The Wandering Inn", captured: "The Wandering Inn (Volume 1)", matches: true),+        TitleCase(+            toRead: "Beware of Chicken", captured: "Beware of Chicken: A Xianxia Cultivation Novel",+            matches: true),+        TitleCase(toRead: "Café Démon", captured: "CAFE DEMON", matches: true),+        TitleCase(toRead: "The Last", captured: "The Last Wish", matches: false),+        TitleCase(toRead: "Worm", captured: "Worm (Parahumans 1)", matches: false),+        TitleCase(toRead: "Worm", captured: "Wormwood", matches: false),+        TitleCase(+            toRead: "Book 1: The Final Ascension", captured: "The Final Ascension", matches: false),+        TitleCase(toRead: "Wandering Inn", captured: "The Wandering Inn 2", matches: false),+        TitleCase(toRead: "!!!", captured: "???", matches: false),+    ]++    @Test("The Req 2.4 examples hold as stated", arguments: requirementTable)+    func requirementExamples(_ example: TitleCase) {+        let toRead = ToReadMatcher.normalise(example.toRead)+        let captured = ToReadMatcher.normalise(example.captured)+        #expect(ToReadMatcher.titlesMatch(toRead, captured) == example.matches)+    }++    /// The same table with explicit expectations, so a silently skipped+    /// parameterised case cannot turn the suite green on its own.+    @Test("The Req 2.4 table has every row")+    func requirementTableIsComplete() {+        #expect(Self.requirementTable.count == 10)+        #expect(Self.requirementTable.filter(\.matches).count == 4)+    }++    @Test("Empty text never matches, not even itself")+    func emptyNeverMatches() {+        let empty = ToReadMatcher.normalise(" — ")+        #expect(empty.text.isEmpty)+        #expect(empty.words.isEmpty)+        #expect(!ToReadMatcher.titlesMatch(empty, empty))+        #expect(!ToReadMatcher.titlesMatch(empty, ToReadMatcher.normalise("Worm")))+    }++    // MARK: - Properties++    /// Words chosen to exercise every step: marks, full-width forms, the+    /// Turkish letters, a ligature, `ß`, and punctuation glued to a word.+    private static let vocabulary = [+        "the", "a", "an", "Mother", "of", "Learning", "Café", "Démon", "naïve",+        "Worm", "of", "İstanbul", "ısık", "Straße", "final", "DŽungla", "Crème",+        "Brûlée", "(Volume", "1)", "Book:", "Chicken!", "Ωmega", "ΣΟΦΙΑ", "“quoted”",+        "rock’n’roll", "★", "—", "Zoë", "Ångström", "ÇAĞ", "Wandering", "Inn",+    ]+    private static let separators = [" ", "  ", "\u{3000}", "\t", " — ", ": ", ", "]++    private static func title(using random: inout ToReadSeededGenerator) -> String {+        let count = Int.random(in: 1...6, using: &random)+        var result = ""+        for index in 0..<count {+            if index > 0 { result += separators.randomElement(using: &random)! }+            result += vocabulary.randomElement(using: &random)!+        }+        return result+    }++    @Test("Normalising is idempotent on its own text", arguments: 1...16)+    func idempotent(seed: Int) {+        var random = ToReadSeededGenerator(seed: UInt64(seed))+        for _ in 0..<40 {+            let first = ToReadMatcher.normalise(Self.title(using: &random))+            let second = ToReadMatcher.normalise(first.text)+            #expect(second == first, "\(first.text)")+        }+    }++    @Test("titlesMatch is symmetric, and equal text always matches", arguments: 1...16)+    func symmetricAndReflexive(seed: Int) {+        var random = ToReadSeededGenerator(seed: UInt64(seed))+        for _ in 0..<40 {+            let left = ToReadMatcher.normalise(Self.title(using: &random))+            // Half the time a prefix-shaped relative, so the prefix arm is+            // exercised and not only the unequal case.+            let right = Bool.random(using: &random)+                ? ToReadMatcher.normalise(left.text + " " + Self.title(using: &random))+                : ToReadMatcher.normalise(Self.title(using: &random))+            #expect(+                ToReadMatcher.titlesMatch(left, right) == ToReadMatcher.titlesMatch(right, left),+                "\(left.text) / \(right.text)")+            if !left.text.isEmpty {+                #expect(ToReadMatcher.titlesMatch(left, ToReadMatcher.normalise(left.text)))+            }+        }+    }++    @Test("Case changes and punctuation between words never change the result",+          arguments: 1...16)+    func caseAndPunctuationInvariance(seed: Int) {+        var random = ToReadSeededGenerator(seed: UInt64(seed))+        for _ in 0..<40 {+            let leftTitle = Self.title(using: &random)+            let rightTitle = Bool.random(using: &random)+                ? leftTitle + " " + Self.title(using: &random)+                : Self.title(using: &random)+            let expected = ToReadMatcher.titlesMatch(+                ToReadMatcher.normalise(leftTitle), ToReadMatcher.normalise(rightTitle))++            // Dotless `ı` is the one letter here a locale-free fold cannot+            // round-trip: it uppercases to `I`, which folds to a dotted `i`.+            // That is the price Q15 accepts for one answer on every device, so+            // the uppercase half skips a title holding it.+            if !leftTitle.contains("ı") {+                let shouted = ToReadMatcher.normalise(leftTitle.uppercased())+                let whispered = ToReadMatcher.normalise(rightTitle.lowercased())+                #expect(+                    ToReadMatcher.titlesMatch(shouted, whispered) == expected,+                    "\(leftTitle) / \(rightTitle)")+            }++            let punctuated = leftTitle+                .split(separator: " ", omittingEmptySubsequences: false)+                .joined(separator: " … ")+            #expect(+                ToReadMatcher.titlesMatch(+                    ToReadMatcher.normalise(punctuated), ToReadMatcher.normalise(rightTitle))+                    == expected,+                "\(punctuated) / \(rightTitle)")+        }+    }+}++/// xorshift64*, as the other property suites here use; private to this file.+private struct ToReadSeededGenerator: RandomNumberGenerator {+    private var state: UInt64++    init(seed: UInt64) { state = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 }++    mutating func next() -> UInt64 {+        state ^= state >> 12+        state ^= state << 25+        state ^= state >> 27+        return state &* 2_685_821_657_736_338_717+    }+}++/// Candidate derivation over library rows (Req 1.1, 2.1–2.5, 3.1–3.5).+///+/// Rows go into an in-memory store through plain `insert`, and the inputs are+/// read back the way `todayPresentation` reads them: every Work, Site and+/// Entry row, the groups and the Work sets derived from those rows, and the+/// distinct pairs from their table.+@Suite("To-read candidate derivation", .serialized)+struct ToReadCandidateTests {++    private static func id(_ suffix: Int) -> UUID {+        UUID(uuidString: String(format: "E0000000-0000-4000-8000-%012d", suffix))!+    }++    private static let workRule = URLRuleDefinition.work(+        locator: .query(name: ExactScalarString("id")))++    private static let quarantineReason = LibraryValidationError.invalidStateTuple(+        type: "Site", id: "x", reason: "r")++    // MARK: - Shared site (Req 2.1)++    @Test("A pair needs a shared site")+    func sharedSiteRequired() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.site("c.example")+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        store.work(Self.id(2), title: "Mother of Learning", hostnames: ["c.example"], toRead: true)++        #expect(try store.candidates().isEmpty)+        #expect(try store.pairs().isEmpty)+    }++    @Test("Multi-site works match on any shared site, as one choice under the lowest hostname")+    func multiSiteWorks() throws {+        let store = try MatchStore()+        for hostname in ["a.example", "b.example", "c.example"] { store.site(hostname) }+        store.work(+            Self.id(1), title: "Mother of Learning",+            hostnames: ["c.example", "b.example", "a.example"])+        store.work(+            Self.id(2), title: "Mother of Learning", hostnames: ["b.example", "c.example"],+            toRead: true)++        let items = try store.candidates()+        #expect(items.count == 1)+        let item = try #require(items.first)+        #expect(item.capturedWorkID == Self.id(1))+        #expect(item.hostname == "b.example")+        #expect(item.choices.map(\.toReadWorkID) == [Self.id(2)])++        #expect(+            try store.pairs()+                == [MatchedPair(capturedID: Self.id(1), toReadID: Self.id(2), hostname: "b.example")])+    }++    @Test("Two to-read works never pair with each other")+    func toReadWorksDoNotPair() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        store.work(Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)++        #expect(try store.candidates().isEmpty)+    }++    // MARK: - The Work URL arm (Req 2.3, Q11, Q16, Q28)++    @Test("A .work rule that reads the to-read Work URL matches the captured identity")+    func workURLArmHits() throws {+        let store = try MatchStore()+        try store.site("a.example", rule: Self.workRule)+        store.work(+            Self.id(1), title: "A Chapter Title Nobody Typed", hostnames: ["a.example"],+            identities: ["a.example": "42"])+        store.work(+            Self.id(2), title: "My Story", hostnames: ["a.example"], toRead: true,+            workURLs: ["a.example": "https://a.example/story?id=42"])++        #expect(try store.pairs().map(\.capturedID) == [Self.id(1)])+    }++    @Test("A legacyUnverified captured identity is still matched")+    func legacyIdentityMatches() throws {+        let store = try MatchStore()+        try store.site("a.example", rule: Self.workRule)+        store.work(+            Self.id(1), title: "Unrelated", hostnames: ["a.example"],+            identities: ["a.example": "42"], identityState: .legacyUnverified)+        store.work(+            Self.id(2), title: "My Story", hostnames: ["a.example"], toRead: true,+            workURLs: ["a.example": "https://a.example/story?id=42"])++        #expect(try store.pairs().map(\.capturedID) == [Self.id(1)])+    }++    /// One captured work holding identity 42 and one to-read work whose Work+    /// URL carries it, on a site taught `rule`. The titles never match, so any+    /// pair is the Work URL arm's.+    private static func landingURLStore(rule: URLRuleDefinition) throws -> MatchStore {+        let store = try MatchStore()+        try store.site("a.example", rule: rule)+        store.work(+            Self.id(1), title: "Unrelated", hostnames: ["a.example"],+            identities: ["a.example": "42"])+        store.work(+            Self.id(2), title: "My Story", hostnames: ["a.example"], toRead: true,+            workURLs: ["a.example": "https://a.example/story?id=42"])+        return store+    }++    @Test("A .workAndSequence rule cannot read a landing URL, so the arm does not hold")+    func sequenceRuleOnLandingURLMisses() throws {+        let rule = URLRuleDefinition.workAndSequence(+            work: URLFieldSelector(locator: .query(name: ExactScalarString("id"))),+            sequence: URLFieldSelector(locator: .query(name: ExactScalarString("ch"))))+        #expect(try Self.landingURLStore(rule: rule).pairs().isEmpty)++        // The same fixture under a `.work` rule reading the same parameter does+        // match, so the miss above is the sequence selector's and not the+        // fixture's.+        #expect(+            try Self.landingURLStore(rule: Self.workRule).pairs().map(\.capturedID)+                == [Self.id(1)])+    }++    /// A `.sequence` rule supplies no work identity, so it has nothing for the+    /// arm to compare, whatever it reads from the Work URL.+    @Test("A .sequence rule gives no Work URL match")+    func sequenceOnlyRuleMisses() throws {+        let rule = URLRuleDefinition.sequence(locator: .query(name: ExactScalarString("id")))+        #expect(!rule.suppliesIdentity)+        #expect(try Self.landingURLStore(rule: rule).pairs().isEmpty)+    }++    /// The item's hostname is the lowest one the pair **matched** on, not the+    /// lowest one it shares, and a pair matching on two sites by different arms+    /// is still one choice.+    @Test("Matching by different arms on two shared sites gives one choice under the right hostname")+    func differentArmsOnTwoSites() throws {+        // The titles match, so the title arm holds on both sites; the Work URL+        // arm holds only on the higher one.+        let both = try MatchStore()+        both.site("a.example")+        try both.site("b.example", rule: Self.workRule)+        both.work(+            Self.id(1), title: "Mother of Learning", hostnames: ["a.example", "b.example"],+            identities: ["b.example": "42"])+        both.work(+            Self.id(2), title: "Mother of Learning", hostnames: ["a.example", "b.example"],+            toRead: true, workURLs: ["b.example": "https://b.example/story?id=42"])+        let items = try both.candidates()+        #expect(items.count == 1)+        #expect(items.first?.hostname == "a.example")+        #expect(items.first?.choices.map(\.toReadWorkID) == [Self.id(2)])++        // The titles do not match: only the Work URL arm on the higher site+        // holds, so that is the item's hostname although both sites are shared.+        let urlOnly = try MatchStore()+        urlOnly.site("a.example")+        try urlOnly.site("b.example", rule: Self.workRule)+        urlOnly.work(+            Self.id(1), title: "Unrelated", hostnames: ["a.example", "b.example"],+            identities: ["b.example": "42"])+        urlOnly.work(+            Self.id(2), title: "My Story", hostnames: ["a.example", "b.example"],+            toRead: true, workURLs: ["b.example": "https://b.example/story?id=42"])+        #expect(+            try urlOnly.pairs()+                == [MatchedPair(capturedID: Self.id(1), toReadID: Self.id(2), hostname: "b.example")])+        #expect(try urlOnly.candidates().map(\.hostname) == ["b.example"])+    }++    @Test("No rule, no Work URL or no captured identity, and the arm does not hold")+    func workURLArmNeedsBothSides() throws {+        let noRule = try MatchStore()+        noRule.site("a.example")+        noRule.work(+            Self.id(1), title: "Unrelated", hostnames: ["a.example"],+            identities: ["a.example": "42"])+        noRule.work(+            Self.id(2), title: "My Story", hostnames: ["a.example"], toRead: true,+            workURLs: ["a.example": "https://a.example/story?id=42"])+        #expect(try noRule.pairs().isEmpty)++        let noURL = try MatchStore()+        try noURL.site("a.example", rule: Self.workRule)+        noURL.work(+            Self.id(1), title: "Unrelated", hostnames: ["a.example"],+            identities: ["a.example": "42"])+        noURL.work(Self.id(2), title: "My Story", hostnames: ["a.example"], toRead: true)+        #expect(try noURL.pairs().isEmpty)++        let noIdentity = try MatchStore()+        try noIdentity.site("a.example", rule: Self.workRule)+        noIdentity.work(Self.id(1), title: "Unrelated", hostnames: ["a.example"])+        noIdentity.work(+            Self.id(2), title: "My Story", hostnames: ["a.example"], toRead: true,+            workURLs: ["a.example": "https://a.example/story?id=42"])+        #expect(try noIdentity.pairs().isEmpty)+    }++    // MARK: - Title arms (Req 2.2, 2.4)++    @Test("A prefix match pairs whichever side is shorter")+    func prefixMatchEitherWay() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.work(Self.id(1), title: "The Wandering Inn (Volume 1)", hostnames: ["a.example"])+        store.work(Self.id(2), title: "The Wandering Inn", hostnames: ["a.example"], toRead: true)+        store.work(Self.id(3), title: "Beware of Chicken", hostnames: ["a.example"])+        store.work(+            Self.id(4), title: "Beware of Chicken: A Xianxia Cultivation Novel",+            hostnames: ["a.example"], toRead: true)+        // A near miss under the floor.+        store.work(Self.id(5), title: "The Last Wish", hostnames: ["a.example"])+        store.work(Self.id(6), title: "The Last", hostnames: ["a.example"], toRead: true)++        #expect(+            try store.pairs().map { [$0.capturedID, $0.toReadID] }+                == [[Self.id(1), Self.id(2)], [Self.id(3), Self.id(4)]])+    }++    // MARK: - Declines (Req 2.5)++    @Test("A declined pair is excluded while the same work's other pair stays")+    func declinedPairExcluded() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        store.work(Self.id(2), title: "Mother of Learning!", hostnames: ["a.example"])+        store.work(Self.id(3), title: "mother of learning", hostnames: ["a.example"], toRead: true)+        store.work(Self.id(4), title: "Beware of Chicken", hostnames: ["a.example"])+        store.work(Self.id(5), title: "Beware of Chicken", hostnames: ["a.example"], toRead: true)+        store.distinct(Self.id(1), Self.id(3))++        #expect(+            try store.pairs().map { [$0.capturedID, $0.toReadID] }+                == [[Self.id(2), Self.id(3)], [Self.id(4), Self.id(5)]])+    }++    // MARK: - Open sets and torn groups (Req 3.5, Q13)++    @Test("Excluded while the captured work is in a same-site Work set, offered again once it resolves")+    func excludedWhileInWorkSet() throws {+        let store = try MatchStore()+        try store.site("a.example", rule: Self.workRule)+        store.work(+            Self.id(1), title: "Mother of Learning", hostnames: ["a.example"],+            identities: ["a.example": "42"])+        // The same identity on the same site: a Work set with the captured work.+        let twin = store.work(+            Self.id(2), title: "Something Else", hostnames: ["a.example"],+            identities: ["a.example": "42"])+        store.work(Self.id(3), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        #expect(try store.workSetCount() == 1)+        #expect(try store.candidates().isEmpty)++        store.delete(twin)+        #expect(try store.workSetCount() == 0)+        #expect(try store.candidates().map(\.capturedWorkID) == [Self.id(1)])+    }++    @Test("Excluded while the to-read work is in a Work set of two, offered again once it resolves")+    func toReadSideInWorkSetExcluded() throws {+        let store = try MatchStore()+        try store.site("a.example", rule: Self.workRule)+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        store.work(+            Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true,+            identities: ["a.example": "42"])+        // The same identity on the same site: a Work set with the to-read work.+        let twin = store.work(+            Self.id(3), title: "Something Else", hostnames: ["a.example"],+            identities: ["a.example": "42"])+        #expect(try store.workSetCount() == 1)+        #expect(try store.candidates().isEmpty)++        store.delete(twin)+        #expect(try store.workSetCount() == 0)+        #expect(try store.candidates().map(\.capturedWorkID) == [Self.id(1)])+    }++    /// Q38 as amended: a one-member set that publishes a review item holds its+    /// pairs back too. A split group one of whose rows has no membership is+    /// such a set: the scan reads it as divergent (a membership-less row is+    /// always the reader's call) although no member is torn.+    @Test("Excluded while the captured work is a one-member set that asks the reader")+    func oneMemberDivergentSetExcluded() throws {+        let store = try MatchStore()+        store.site("a.example")+        let bare = store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        store.work(+            Self.id(1), title: "Mother of Learning", hostnames: ["a.example"], offset: 5)+        for membership in bare.siteMemberships ?? [] { store.context.delete(membership) }+        store.work(Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)++        // The scan reads a split group's first row for its sites, so the+        // membership-less row goes first.+        let result = try store.pairs { works in+            works.filter { $0 === bare } + works.filter { $0 !== bare }+        }+        let set = try #require(result.workSets.first)+        #expect(result.workSets.count == 1)+        #expect(set.members.map(\.id) == [Self.id(1)])+        #expect(set.classification == .divergent)+        #expect(!set.isTorn)+        #expect(result.pairs.isEmpty)+    }++    @Test("Excluded while the captured work is in a cross-site title set, offered again once dismissed")+    func excludedWhileInCrossSiteSet() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.site("b.example")+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        store.work(Self.id(2), title: "Mother of Learning", hostnames: ["b.example"])+        store.work(Self.id(3), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        #expect(try store.workSetCount() == 1)+        #expect(try store.candidates().isEmpty)++        store.distinct(Self.id(1), Self.id(2))+        #expect(try store.workSetCount() == 0)+        #expect(try store.candidates().map(\.capturedWorkID) == [Self.id(1)])+    }++    @Test("Excluded while either group is torn, offered again once it is whole")+    func excludedWhileTorn() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        let toRead = store.work(+            Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        let twin = store.work(+            Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true,+            offset: 5)+        toRead.genericNotes = "one"+        twin.genericNotes = "two"+        #expect(try store.groups()[Self.id(2)]?.isTorn == true)+        #expect(try store.candidates().isEmpty)++        twin.genericNotes = "one"+        #expect(try store.groups()[Self.id(2)]?.isTorn == false)+        #expect(try store.candidates().map(\.capturedWorkID) == [Self.id(1)])+    }++    // MARK: - Blocked choices (Req 3.4, Q35)++    @Test("A quarantined hostname of either group blocks the choice")+    func quarantineBlocks() throws {+        let store = try MatchStore()+        for hostname in ["a.example", "q.example", "r.example"] { store.site(hostname) }+        store.work(+            Self.id(1), title: "Mother of Learning", hostnames: ["a.example", "q.example"])+        store.work(Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        store.work(+            Self.id(3), title: "Mother of Learning", hostnames: ["a.example", "r.example"],+            toRead: true)++        let capturedSide = try #require(+            try store.candidates(quarantine: ["q.example": Self.quarantineReason]).first)+        #expect(+            capturedSide.choices.map(\.blocked)+                == [.quarantined(hostname: "q.example"), .quarantined(hostname: "q.example")])++        let toReadSide = try #require(+            try store.candidates(quarantine: ["r.example": Self.quarantineReason]).first)+        #expect(toReadSide.choices.map(\.blocked) == [nil, .quarantined(hostname: "r.example")])+    }++    @Test("Differing series block the choice; one side in a series does not")+    func seriesConflictBlocks() throws {+        let store = try MatchStore()+        store.site("a.example")+        let captured = store.work(+            Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        let first = store.work(+            Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        store.work(Self.id(3), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        captured.seriesID = Self.id(900)+        captured.seriesPosition = 1+        first.seriesID = Self.id(901)+        first.seriesPosition = 1++        let item = try #require(try store.candidates().first)+        #expect(item.choices.map(\.blocked) == [.seriesConflict, nil])++        // The same series is not a conflict.+        first.seriesID = Self.id(900)+        let same = try #require(try store.candidates().first)+        #expect(same.choices.map(\.blocked) == [nil, nil])+    }++    @Test("An item whose choices are all blocked is still returned")+    func allBlockedItemReturned() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        store.work(Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)++        let items = try store.candidates(quarantine: ["a.example": Self.quarantineReason])+        #expect(items.count == 1)+        #expect(items.first?.choices.map(\.blocked) == [.quarantined(hostname: "a.example")])+    }++    // MARK: - Items (Req 3.1–3.3)++    @Test("One item per captured work, listing every to-read work it pairs with")+    func oneItemPerCapturedWork() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        store.work(Self.id(3), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        store.work(+            Self.id(2), title: "Mother of Learning (Book 1)", hostnames: ["a.example"],+            toRead: true)++        let items = try store.candidates()+        #expect(items.count == 1)+        let item = try #require(items.first)+        #expect(item.id == Self.id(1))+        #expect(item.capturedTitle == "Mother of Learning")+        #expect(item.choices.map(\.toReadWorkID) == [Self.id(2), Self.id(3)])+        #expect(+            item.choices.map(\.title) == ["Mother of Learning (Book 1)", "Mother of Learning"])+    }++    @Test("A to-read work pairing with two captured works is listed on both items")+    func toReadListedOnTwoItems() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.work(Self.id(2), title: "Mother of Learning", hostnames: ["a.example"])+        store.work(Self.id(1), title: "Mother of Learning (Book 2)", hostnames: ["a.example"])+        store.work(Self.id(3), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)++        let items = try store.candidates()+        #expect(items.map(\.capturedWorkID) == [Self.id(1), Self.id(2)])+        #expect(items.map { $0.choices.map(\.toReadWorkID) } == [[Self.id(3)], [Self.id(3)]])+    }++    @Test("The entry count is the captured work's logical entries")+    func entryCount() throws {+        let store = try MatchStore()+        store.site("a.example")+        let captured = store.work(+            Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        let toRead = store.work(+            Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true)+        store.entry(Self.id(100), work: captured)+        store.entry(Self.id(101), work: captured)+        // A split Entry group is one entry.+        store.entry(Self.id(101), work: captured, offset: 5)+        // The to-read work's entries are not the captured work's.+        store.entry(Self.id(102), work: toRead)+        store.entry(Self.id(103), work: nil)++        #expect(try store.candidates().first?.entryCount == 2)+    }++    // MARK: - Carrier values and determinism (Req 1.1)++    @Test("Titles and reading status come from the group's carrier")+    func carrierValues() throws {+        let store = try MatchStore()+        store.site("a.example")+        store.work(Self.id(1), title: "Mother of Learning", hostnames: ["a.example"])+        // A split group of a bare row and an authored to-read row. The carrier+        // is the authored one, so the group is a to-read work with its title.+        // The scan reads a lone split group as a one-member set; this one is+        // silently resolvable, so it does not hold the pair back (Q38).+        let bare = store.work(Self.id(2), title: "Placeholder", hostnames: ["a.example"])+        let authored = store.work(+            Self.id(2), title: "Mother of Learning", hostnames: ["a.example"], toRead: true,+            offset: 5)++        let group = try #require(try store.groups()[Self.id(2)])+        try #require(group.carrier === authored)+        try #require(group.carrier !== bare)++        let item = try #require(try store.candidates().first)+        #expect(item.capturedWorkID == Self.id(1))+        #expect(item.choices.map(\.title) == ["Mother of Learning"])+    }++    @Test("Shuffled input gives identical output", arguments: 1...6)+    func shuffledInputIsDeterministic(seed: Int) throws {+        let store = try MatchStore()+        for hostname in ["a.example", "b.example"] { store.site(hostname) }+        for index in 0..<6 {+            let hostnames = index.isMultiple(of: 2) ? ["a.example"] : ["b.example", "a.example"]+            let captured = store.work(+                Self.id(10 + index), title: "Serial \(index) of the Realm", hostnames: hostnames)+            store.entry(Self.id(200 + index), work: captured)+            store.work(+                Self.id(30 + index), title: "Serial \(index) of the Realm (Part \(index))",+                hostnames: hostnames, toRead: true)+            store.work(+                Self.id(50 + index), title: "serial \(index) of the realm",+                hostnames: ["a.example"], toRead: true)+        }++        let baseline = try store.candidates()+        #expect(baseline.count == 6)+        #expect(baseline.allSatisfy { $0.choices.count == 2 })+        var random = ToReadSeededGenerator(seed: UInt64(seed))+        #expect(try store.candidates(shuffledWith: &random) == baseline)+    }+}++/// An in-memory library whose rows are inserted directly and read back as+/// `todayPresentation` reads them.+private final class MatchStore {+    static let epoch = Date(timeIntervalSince1970: 1_800_000_000)++    let container: ModelContainer+    let context: ModelContext++    init() throws {+        let schema = Schema(versionedSchema: AsterismSchemaV16.self)+        container = try ModelContainer(+            for: schema,+            configurations: [ModelConfiguration(+                schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)])+        context = ModelContext(container)+    }++    @discardableResult+    func site(_ hostname: String) -> Site {+        let site = Site(hostname: hostname)+        site.mode = .untaught+        context.insert(site)+        return site+    }++    /// A Site with one current, reader-taught URL rule.+    @discardableResult+    func site(_ hostname: String, rule: URLRuleDefinition) throws -> Site {+        let site = site(hostname)+        let pattern = try URLRulePattern(+            version: 1, isCurrent: true, createdAt: Self.epoch, origin: .readerTaught,+            definition: rule, site: site)+        context.insert(pattern)+        site.urlRules = site.urlRuleValues + [pattern]+        return site+    }++    /// A captured work is parsed: its title is its parsed title. A to-read work+    /// is what the New Work form makes: a manual title and no parsed one.+    @discardableResult+    func work(+        _ id: UUID, title: String, hostnames: [String], toRead: Bool = false,+        identities: [String: String] = [:],+        identityState: WorkURLIdentityState = .rule,+        workURLs: [String: String] = [:], offset: TimeInterval = 0+    ) -> Work {+        let timestamp = Self.epoch.addingTimeInterval(offset)+        let work = Work.create(+            in: context, id: id, title: title, hostname: hostnames[0],+            site: siteRow(hostnames[0]), timestamp: timestamp)+        for (index, hostname) in hostnames.enumerated().dropFirst() {+            let membership = WorkSiteMembership(+                hostname: hostname, createdAt: timestamp.addingTimeInterval(Double(index)),+                workID: id, work: work, site: siteRow(hostname))+            context.insert(membership)+        }+        if toRead {+            work.readingStatus = .toRead+            work.titleProvenance = .manual+        } else {+            work.lastParsedTitle = title+            work.titleProvenance = .parsed+        }+        for membership in work.siteMemberships ?? [] {+            if let identity = identities[membership.hostname] {+                membership.urlIdentity = identity+                membership.urlIdentityState = identityState+            }+            membership.workURLString = workURLs[membership.hostname]+        }+        return work+    }++    func entry(_ id: UUID, work: Work?, offset: TimeInterval = 0) {+        let rawURL = "https://a.example/read/\(id.uuidString)"+        let entry = Entry(+            id: id, captureTitle: "Chapter", captureTitleSource: .host, rawURLString: rawURL,+            hostname: "a.example", entryIdentityKey: rawURL,+            timestamp: Self.epoch.addingTimeInterval(offset))+        context.insert(entry)+        entry.work = work+    }++    func distinct(_ a: UUID, _ b: UUID) {+        let key = WorkPairKey(a, b)+        context.insert(WorkDistinctPair(lowerWorkID: key.lower, higherWorkID: key.higher))+    }++    func delete(_ work: Work) {+        for membership in work.siteMemberships ?? [] { context.delete(membership) }+        context.delete(work)+    }++    private func siteRow(_ hostname: String) -> Site? {+        try? LibraryRepository.fetchSites(hostname: hostname, context: context).first+    }++    // MARK: Reads++    private struct Inputs {+        var works: [Work]+        var sites: [Site]+        var entries: [Entry]+        let types: WorkTypeDirectory+        let distinctPairs: Set<WorkPairKey>++        var groups: [UUID: AsterismCore.WorkGroup] { LibraryRepository.workGroups(works, types: types) }+        var workSets: [WorkDuplicateSet] {+            DuplicateScan.workSets(of: works, types: types, distinctPairs: distinctPairs)+        }+    }++    private func inputs() throws -> Inputs {+        try context.save()+        return Inputs(+            works: try context.fetch(FetchDescriptor<Work>()),+            sites: try context.fetch(FetchDescriptor<Site>()),+            entries: try context.fetch(FetchDescriptor<Entry>()),+            types: try LibraryRepository.workTypeDirectory(context: context),+            distinctPairs: try DuplicateScan.distinctPairKeys(context: context))+    }++    func groups() throws -> [UUID: AsterismCore.WorkGroup] { try inputs().groups }++    /// `pairs()` over the Work rows in the order `ordering` gives them, with+    /// the Work sets derived from that order, and the sets themselves.+    func pairs(+        ordering: ([Work]) -> [Work]+    ) throws -> (pairs: [MatchedPair], workSets: [WorkDuplicateSet]) {+        var inputs = try inputs()+        inputs.works = ordering(inputs.works)+        let workSets = inputs.workSets+        return (+            ToReadMatcher.pairs(+                works: inputs.works, sites: inputs.sites, groups: inputs.groups,+                distinctPairs: inputs.distinctPairs, workSets: workSets),+            workSets)+    }++    func workSetCount() throws -> Int { try inputs().workSets.count }++    func pairs() throws -> [MatchedPair] {+        let inputs = try inputs()+        return ToReadMatcher.pairs(+            works: inputs.works, sites: inputs.sites, groups: inputs.groups,+            distinctPairs: inputs.distinctPairs, workSets: inputs.workSets)+    }++    func candidates(+        quarantine: [String: LibraryValidationError] = [:]+    ) throws -> [ToReadMatchItem] {+        candidates(from: try inputs(), quarantine: quarantine)+    }++    func candidates(+        shuffledWith random: inout ToReadSeededGenerator+    ) throws -> [ToReadMatchItem] {+        var inputs = try inputs()+        inputs.works.shuffle(using: &random)+        inputs.sites.shuffle(using: &random)+        inputs.entries.shuffle(using: &random)+        return candidates(from: inputs, quarantine: [:])+    }++    private func candidates(+        from inputs: Inputs, quarantine: [String: LibraryValidationError]+    ) -> [ToReadMatchItem] {+        ToReadMatcher.candidates(+            works: inputs.works, sites: inputs.sites, entries: inputs.entries,+            groups: inputs.groups, distinctPairs: inputs.distinctPairs,+            workSets: inputs.workSets, quarantine: quarantine)+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift Modified +415 / -22
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swiftindex 7b06ac5b..610faca6 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergePlannerTests.swift@@ -76,7 +76,7 @@ struct WorkMergePlannerTests {         )          let outcome = try WorkMergePlanner.project(-            WorkMergeBasis(source: source, target: target, currentRule: rule)+            WorkMergeBasis(source: source, target: target, currentRule: rule), request: .merge         )          #expect(outcome.sourceID == source.snapshot.id)@@ -132,7 +132,7 @@ struct WorkMergePlannerTests {         )          let outcome = try WorkMergePlanner.project(-            WorkMergeBasis(source: source, target: target, currentRule: rule)+            WorkMergeBasis(source: source, target: target, currentRule: rule), request: .merge         )          #expect(outcome.sites.map(\.workURL) == ["https://example.com/source"])@@ -162,7 +162,7 @@ struct WorkMergePlannerTests {             workStatus: .hiatus, readingStatus: .abandoned, verdict: "gave up in book two")          let outcome = try WorkMergePlanner.project(-            WorkMergeBasis(source: source, target: target, currentRule: rule))+            WorkMergeBasis(source: source, target: target, currentRule: rule), request: .merge)          #expect(outcome.workStatus == .finished)         #expect(outcome.readingStatus == .finished)@@ -195,7 +195,7 @@ struct WorkMergePlannerTests {         let outcome = try WorkMergePlanner.project(WorkMergeBasis(             source: work(id: 2, title: "Same", releaseDays: [.friday]),             target: work(id: 1, title: "Same", notes: "Target notes", releaseDays: [.monday]),-            currentRule: rule))+            currentRule: rule), request: .merge)          #expect(outcome.releaseDays == [.monday])         #expect(outcome.retainedFields.contains(.targetReleaseDays))@@ -213,13 +213,13 @@ struct WorkMergePlannerTests {         let target = work(id: 1, title: "Same", releaseDays: [.monday, .thursday])          let empty = try WorkMergePlanner.project(WorkMergeBasis(-            source: work(id: 2, title: "Same"), target: target, currentRule: rule))+            source: work(id: 2, title: "Same"), target: target, currentRule: rule), request: .merge)         #expect(empty.discardedFields.isEmpty)          // Req 7.5: the same days in another order are the same schedule.         let agreeing = try WorkMergePlanner.project(WorkMergeBasis(             source: work(id: 3, title: "Same", releaseDays: [.thursday, .monday]),-            target: target, currentRule: rule))+            target: target, currentRule: rule), request: .merge)         #expect(agreeing.discardedFields.isEmpty)         #expect(agreeing.releaseDays == [.monday, .thursday])     }@@ -235,7 +235,7 @@ struct WorkMergePlannerTests {          let onDefaults = try WorkMergePlanner.project(WorkMergeBasis(             source: work(id: 2, title: "Same", verdict: "a fine ending"),-            target: target, currentRule: rule))+            target: target, currentRule: rule), request: .merge)         #expect(onDefaults.discardedFields.isEmpty)         #expect(onDefaults.auditBlock == nil) @@ -243,7 +243,7 @@ struct WorkMergePlannerTests {             source: work(                 id: 3, title: "Same", workStatus: .finished, readingStatus: .finished,                 verdict: "a fine ending"),-            target: target, currentRule: rule))+            target: target, currentRule: rule), request: .merge)         #expect(agreeing.discardedFields.isEmpty)         #expect(agreeing.auditBlock == nil)     }@@ -257,7 +257,7 @@ struct WorkMergePlannerTests {         let outcome = try WorkMergePlanner.project(WorkMergeBasis(             source: work(id: 2, title: "Same", workStatus: .hiatus, readingStatus: .abandoned),             target: work(id: 1, title: "Same", notes: "Target notes"),-            currentRule: rule))+            currentRule: rule), request: .merge)          #expect(outcome.discardedFields == [.sourceWorkStatus, .sourceReadingStatus])         #expect(outcome.auditBlock == nil)@@ -277,7 +277,7 @@ struct WorkMergePlannerTests {         let overDone = try WorkMergePlanner.project(WorkMergeBasis(             source: work(id: 2, title: "Same", readingStatus: .catchingUp),             target: work(id: 1, title: "Same", notes: "Target notes", readingStatus: .finished),-            currentRule: rule))+            currentRule: rule), request: .merge)         #expect(overDone.readingStatus == .finished)         #expect(overDone.discardedFields == [.sourceReadingStatus])         #expect(overDone.retainedFields.contains(.targetReadingStatus))@@ -285,7 +285,7 @@ struct WorkMergePlannerTests {         let underDone = try WorkMergePlanner.project(WorkMergeBasis(             source: work(id: 3, title: "Same", readingStatus: .abandoned),             target: work(id: 1, title: "Same", notes: "Target notes", readingStatus: .catchingUp),-            currentRule: rule))+            currentRule: rule), request: .merge)         #expect(underDone.readingStatus == .catchingUp)         #expect(underDone.discardedFields == [.sourceReadingStatus])     }@@ -337,7 +337,7 @@ struct WorkMergePlannerTests {             source: work(id: 2, entries: [entry(id: 12, url: "https://example.com/?series=42")]),             target: work(id: 1, entries: [entry(id: 11, url: "https://example.com/?series=42")]),             currentRule: rule-        ))+        ), request: .merge)         #expect(try onlySite(complete).identityDisposition             == .set(identity: ExactScalarString("42"), rule: rule.reference)) @@ -345,7 +345,7 @@ struct WorkMergePlannerTests {             source: work(id: 2, entries: [entry(id: 12, url: "https://example.com/?series=99")]),             target: work(id: 1, entries: [entry(id: 11, url: "https://example.com/?series=42")]),             currentRule: rule-        ))+        ), request: .merge)         #expect(try onlySite(split).identityDisposition == .clear)         #expect(split.issues == [.reviewURLIdentity]) @@ -353,7 +353,7 @@ struct WorkMergePlannerTests {             source: work(id: 2, entries: [entry(id: 12, url: "https://example.com/no-query")]),             target: work(id: 1, entries: [entry(id: 11, url: "https://example.com/?series=42")]),             currentRule: rule-        ))+        ), request: .merge)         #expect(try onlySite(failed).identityDisposition == .clear)         #expect(failed.issues == [.reviewURLIdentity]) @@ -366,12 +366,394 @@ struct WorkMergePlannerTests {             source: work(id: 2),             target: work(id: 1, identity: legacy),             currentRule: rule-        ))+        ), request: .merge)         let emptySite = try onlySite(empty)         #expect(emptySite.identityEvidence == .noEntries(previousIdentity: legacy))         #expect(emptySite.identityDisposition == .retain(legacy))     } +    // MARK: - `to-read-capture-match`: the `.toReadMatch` request (Req 4.1, 4.3, 4.4)++    /// A to-read work as the New Work form leaves it: a typed title, no parsed+    /// title, `toRead`, and every other value pristine.+    private func toReadTarget(+        workStatus: WorkStatus = .ongoing, verdict: String = "",+        releaseDays: [ReleaseDay] = [], notes: String = "Typed notes",+        url: String? = "https://example.com/target",+        workStatusRaw: String? = nil, releaseDaysRaw: [String]? = nil+    ) -> WorkMergeWorkBasis {+        work(+            id: 1, title: "Mother of Learning", titleProvenance: .manual, url: url,+            notes: notes, workStatus: workStatus, readingStatus: .toRead, verdict: verdict,+            releaseDays: releaseDays, lastParsedTitle: .some(nil),+            workStatusRaw: workStatusRaw, releaseDaysRaw: releaseDaysRaw)+    }++    /// The work the first captured chapter created: every value the reader+    /// could care about differs from the to-read work's.+    private func capturedSource(+        title: String = "mother of learning!", lastParsedTitle: String? = nil,+        notes: String = "Captured notes", url: String? = "https://example.com/source",+        workStatus: WorkStatus = .hiatus, readingStatusRaw: String? = nil+    ) -> WorkMergeWorkBasis {+        work(+            id: 2, title: title, titleProvenance: .parsed, url: url, notes: notes,+            workStatus: workStatus, readingStatus: .reading, verdict: "loved it",+            releaseDays: [.friday], lastParsedTitle: .some(lastParsedTitle ?? title),+            readingStatusRaw: readingStatusRaw)+    }++    @Test("A pristine to-read target takes the captured work's titles, statuses, verdict and days")+    func pristineTargetTakesTheSources() throws {+        let rule = try queryRule()+        let outcome = try WorkMergePlanner.project(+            WorkMergeBasis(source: capturedSource(), target: toReadTarget(), currentRule: rule),+            request: .toReadMatch)++        #expect(outcome.targetID == uuid(1))+        #expect(outcome.displayTitle == "mother of learning!")+        #expect(outcome.lastParsedTitle == "mother of learning!")+        #expect(outcome.titleProvenance == .parsed)+        #expect(outcome.readingStatus == .reading)+        #expect(outcome.workStatus == .hiatus)+        #expect(outcome.verdict == "loved it")+        #expect(outcome.releaseDays == [.friday])+        #expect(outcome.rawOverrides == WorkMergeRawOverrides(+            displayTitle: "mother of learning!",+            lastParsedTitle: "mother of learning!",+            titleProvenanceRaw: TitleProvenance.parsed.rawValue,+            readingStatusRaw: ReadingStatus.reading.rawValue,+            workStatusRaw: WorkStatus.hiatus.rawValue,+            verdict: "loved it",+            releaseDaysRaw: [ReleaseDay.friday.rawValue]))++        // Req 4.1: every winning side is kept, and no pristine value the+        // captured work replaces is listed as lost.+        for field in [+            WorkMergeField.sourceDisplayTitle, .sourceReadingStatus, .sourceWorkStatus,+            .sourceVerdict, .sourceReleaseDays,+        ] {+            #expect(outcome.retainedFields.contains(field), "\(field) is not retained")+        }+        for field in [+            WorkMergeField.targetDisplayTitle, .targetReadingStatus, .targetWorkStatus,+            .targetVerdict, .targetReleaseDays,+        ] {+            #expect(!outcome.retainedFields.contains(field), "\(field) is retained")+        }+        #expect(+            outcome.discardedFields+                == [.sourceWorkURL, .sourceNotes, .targetManualTitle, .targetReadingStatus])++        // Req 4.4: the captured work's block, with the typed title on its own+        // line directly under the header. The verdict won, so it is not recorded.+        #expect(outcome.auditBlock == """+        --- Merged from: mother of learning! ---+        Title before merge: Mother of Learning+        Work URL (example.com): https://example.com/source++        Captured notes+        """)+        #expect(outcome.genericNotes == "Typed notes\n\n" + outcome.auditBlock!)+    }++    @Test("A to-read target's edited status, verdict and days are kept, and the source's reported")+    func editedTargetKeepsItsOwn() throws {+        let rule = try queryRule()+        let outcome = try WorkMergePlanner.project(+            WorkMergeBasis(+                source: capturedSource(),+                target: toReadTarget(+                    workStatus: .finished, verdict: "my verdict", releaseDays: [.monday]),+                currentRule: rule),+            request: .toReadMatch)++        // Titles and reading status still come from the captured work.+        #expect(outcome.displayTitle == "mother of learning!")+        #expect(outcome.readingStatus == .reading)+        #expect(outcome.workStatus == .finished)+        #expect(outcome.verdict == "my verdict")+        #expect(outcome.releaseDays == [.monday])+        #expect(outcome.rawOverrides == WorkMergeRawOverrides(+            displayTitle: "mother of learning!",+            lastParsedTitle: "mother of learning!",+            titleProvenanceRaw: TitleProvenance.parsed.rawValue,+            readingStatusRaw: ReadingStatus.reading.rawValue,+            workStatusRaw: WorkStatus.finished.rawValue,+            verdict: "my verdict",+            releaseDaysRaw: [ReleaseDay.monday.rawValue]))++        for field in [+            WorkMergeField.sourceDisplayTitle, .sourceReadingStatus, .targetWorkStatus,+            .targetVerdict, .targetReleaseDays,+        ] {+            #expect(outcome.retainedFields.contains(field), "\(field) is not retained")+        }+        #expect(+            outcome.discardedFields == [+                .sourceWorkURL, .sourceNotes, .targetManualTitle, .targetReadingStatus,+                .sourceWorkStatus, .sourceVerdict, .sourceReleaseDays,+            ])+        // The losing verdict is reader text, so the block records it.+        #expect(outcome.auditBlock == """+        --- Merged from: mother of learning! ---+        Title before merge: Mother of Learning+        Work URL (example.com): https://example.com/source+        Verdict: loved it++        Captured notes+        """)+    }++    /// Q31: pristine is decided on the raw columns. An unknown work status reads+    /// as `.ongoing` and an unknown day as no day at all, and either would pass+    /// for the form's default if the typed values decided it.+    @Test("An unknown raw work status or release-day token on the target is not pristine")+    func unknownTargetRawIsNotPristine() throws {+        let rule = try queryRule()+        let outcome = try WorkMergePlanner.project(+            WorkMergeBasis(+                source: capturedSource(),+                target: toReadTarget(workStatusRaw: "serialising", releaseDaysRaw: ["blursday"]),+                currentRule: rule),+            request: .toReadMatch)++        let overrides = try #require(outcome.rawOverrides)+        #expect(overrides.workStatusRaw == "serialising")+        #expect(overrides.releaseDaysRaw == ["blursday"])+        // The verdict was blank, so that one is still the captured work's.+        #expect(overrides.verdict == "loved it")+        #expect(outcome.retainedFields.contains(.targetWorkStatus))+        #expect(outcome.retainedFields.contains(.targetReleaseDays))+        #expect(outcome.discardedFields.contains(.sourceWorkStatus))+        #expect(outcome.discardedFields.contains(.sourceReleaseDays))+    }++    /// Q42: a source still on the default work status contributes nothing, as+    /// a blank verdict or an empty schedule does, so losing it to an edited+    /// target is not a loss the preview lists.+    @Test("A captured work on the default work status is not listed as discarded")+    func defaultSourceWorkStatusIsNotDiscarded() throws {+        let rule = try queryRule()+        let outcome = try WorkMergePlanner.project(+            WorkMergeBasis(+                source: capturedSource(workStatus: .ongoing),+                target: toReadTarget(workStatus: .finished),+                currentRule: rule),+            request: .toReadMatch)++        #expect(outcome.workStatus == .finished)+        #expect(outcome.retainedFields.contains(.targetWorkStatus))+        #expect(!outcome.discardedFields.contains(.sourceWorkStatus))+    }++    /// Q34: the raw reading status travels verbatim, so a value a newer build+    /// wrote is not rewritten to the tolerated default on its way to the+    /// survivor.+    @Test("An unknown raw reading status on the captured work is carried verbatim")+    func unknownSourceReadingStatusIsCarried() throws {+        let rule = try queryRule()+        let outcome = try WorkMergePlanner.project(+            WorkMergeBasis(+                source: capturedSource(readingStatusRaw: "rereading"),+                target: toReadTarget(), currentRule: rule),+            request: .toReadMatch)++        #expect(outcome.rawOverrides?.readingStatusRaw == "rereading")+    }++    /// A split captured group presents its display title from the carrier and+    /// its parsed title from the representative, and the survivor takes each+    /// as the snapshot presents it.+    @Test("The overrides take the carrier's display title and the representative's parsed title")+    func splitSourceTitlesComeFromTheirRows() throws {+        let rule = try queryRule()+        let outcome = try WorkMergePlanner.project(+            WorkMergeBasis(+                source: capturedSource(+                    title: "Mother of Learning (Arc 1)", lastParsedTitle: "Mother of Learning"),+                target: toReadTarget(), currentRule: rule),+            request: .toReadMatch)++        #expect(outcome.rawOverrides?.displayTitle == "Mother of Learning (Arc 1)")+        #expect(outcome.rawOverrides?.lastParsedTitle == "Mother of Learning")+        #expect(outcome.displayTitle == "Mother of Learning (Arc 1)")+        #expect(outcome.lastParsedTitle == "Mother of Learning")+    }++    /// Req 4.4: the block is written whether or not the Merge action's own+    /// condition for one holds — here the captured work has no notes, no Work+    /// URL and a parsed title, so `.merge` would write none.+    @Test("The audit block is always written for a to-read match")+    func auditBlockIsAlwaysWritten() throws {+        let rule = try queryRule()+        let basis = try WorkMergeBasis(+            source: capturedSource(notes: "", url: nil),+            target: toReadTarget(notes: "", url: nil), currentRule: rule)++        let outcome = try WorkMergePlanner.project(basis, request: .toReadMatch)+        #expect(outcome.auditBlock == """+        --- Merged from: mother of learning! ---+        Title before merge: Mother of Learning+        """)+        #expect(outcome.genericNotes == outcome.auditBlock)+        #expect(outcome.discardedFields == [.targetManualTitle, .targetReadingStatus])+    }++    /// The ordinary Merge action is unchanged (a Non-Goal): the target keeps its+    /// title and statuses and there are no overrides. The planner has no+    /// default request (Q43), so every caller says which one it means.+    @Test("The merge request's output over the to-read fixture is unchanged")+    func mergeRequestIsUnchanged() throws {+        let rule = try queryRule()+        let basis = try WorkMergeBasis(+            source: capturedSource(), target: toReadTarget(), currentRule: rule)++        let merge = try WorkMergePlanner.project(basis, request: .merge)+        #expect(merge.rawOverrides == nil)+        #expect(merge.displayTitle == "Mother of Learning")+        #expect(merge.readingStatus == .toRead)+        #expect(merge.workStatus == .ongoing)+        #expect(merge.auditBlock?.contains("Title before merge") == false)+        #expect(!merge.discardedFields.contains(.targetManualTitle))+        #expect(!merge.retainedFields.contains(.sourceDisplayTitle))+    }++    /// Req 4.2: a `.toReadMatch` confirm is the ordinary Merge action's+    /// outcome with Req 4.3–4.4's overlay on top, so every field the overlay+    /// does not name — cover, series, links, credits, memberships, Work URLs,+    /// entries, tags, type — must come out exactly as `.merge` gives it.+    ///+    /// Swept by reflection rather than listed, so a field added to the outcome+    /// later is compared too unless it is added to the overlay's names.+    @Test("A to-read match equals the ordinary merge on every field the overlay does not name")+    func toReadMatchEqualsMergeOutsideTheOverlay() throws {+        let basis = try richToReadBasis()+        let merge = try WorkMergePlanner.project(basis, request: .merge)+        let toRead = try WorkMergePlanner.project(basis, request: .toReadMatch)++        // The fixture exercises every arm the requirement names.+        if case .adoptSource = merge.thumbnail {} else { Issue.record("Expected an adopted cover") }+        #expect(merge.membership != nil)+        #expect(!merge.discardedLinks.isEmpty)+        #expect(!merge.gainedCredits.isEmpty)+        #expect(merge.sites.count == 2)+        #expect(merge.sites.allSatisfy { $0.workURL != nil })+        #expect(!merge.movedEntryIDs.isEmpty)++        let overlay: Set<String> = [+            "displayTitle", "lastParsedTitle", "titleProvenance", "readingStatus",+            "workStatus", "verdict", "releaseDays", "genericNotes", "auditBlock",+            "retainedFields", "discardedFields", "rawOverrides",+        ]+        let mergeFields = Dictionary(+            uniqueKeysWithValues: Mirror(reflecting: merge).children.compactMap { child in+                child.label.map { ($0, String(reflecting: child.value)) }+            })+        var compared: Set<String> = []+        for child in Mirror(reflecting: toRead).children {+            guard let label = child.label, !overlay.contains(label) else { continue }+            compared.insert(label)+            #expect(+                String(reflecting: child.value) == mergeFields[label],+                "\(label) differs between .toReadMatch and .merge")+        }+        #expect(compared.isSuperset(of: [+            "thumbnail", "membership", "seriesName", "discardedLinks", "gainedCredits",+            "sites", "movedEntryIDs", "genreTags", "typeDisplay",+        ]))+        // And the overlay did apply, so the comparison is not vacuous.+        #expect(toRead.rawOverrides != nil)+        #expect(toRead.displayTitle != merge.displayTitle)+    }++    /// A captured source and a pristine to-read target with something in every+    /// field a merge moves: a cover only the source has, a series only the+    /// source is in, a link between the two, a credit only the source holds,+    /// entries on both, and a second site only the source is on.+    private func richToReadBasis() throws -> WorkMergeBasis {+        let seriesID = uuid(500)+        func side(+            id: Int, title: String, provenance: TitleProvenance, hostnames: [String],+            readingStatus: ReadingStatus, workStatus: WorkStatus, verdict: String,+            releaseDays: [ReleaseDay], notes: String, tags: [String],+            membership: SeriesMembership?, credits: [CreditDisplay],+            thumbnail: ThumbnailIdentity?, entries: [EntrySnapshot]+        ) -> WorkMergeWorkBasis {+            let snapshot = WorkSnapshot(+                id: uuid(id), displayTitle: title,+                lastParsedTitle: provenance == .manual ? nil : title,+                memberships: hostnames.enumerated().map { index, hostname in+                    WorkSiteMembershipSnapshot(+                        id: uuid(900 + id * 10 + index), hostname: hostname,+                        urlIdentity: nil, urlIdentityState: .none,+                        workURLString: "https://\(hostname)/work/\(id)",+                        createdAt: Date(timeIntervalSince1970: 1))+                },+                genericNotes: notes, genreTags: tags, titleProvenance: provenance,+                createdAt: Date(timeIntervalSince1970: 1),+                modifiedAt: Date(timeIntervalSince1970: 2), entries: entries,+                workStatus: workStatus, readingStatus: readingStatus, verdict: verdict,+                membership: membership,+                series: membership.map { SeriesDisplay(id: $0.seriesID, name: "Arcs", createdAt: nil) },+                credits: credits, thumbnail: thumbnail, releaseDays: releaseDays)+            return WorkMergeWorkBasis(+                snapshot: snapshot,+                identitiesByHostname: Dictionary(+                    uniqueKeysWithValues: hostnames.map {+                        ($0, WorkIdentitySnapshot(value: nil, state: .none, ruleReference: nil))+                    }))+        }+        let source = side(+            id: 2, title: "Mother of Learning (Arc 1)", provenance: .parsed,+            hostnames: ["example.com", "second.example"],+            readingStatus: .reading, workStatus: .hiatus, verdict: "loved it",+            releaseDays: [.friday], notes: "Captured notes", tags: ["Fantasy", "loops"],+            membership: SeriesMembership(seriesID: seriesID, position: 1),+            credits: [+                CreditDisplay(+                    rowIDs: [uuid(700)], creator: CreatorDisplay(id: uuid(701), name: "nobody103"),+                    roles: [], roleIDs: [], hiddenRoleIDs: [])+            ],+            thumbnail: ThumbnailIdentity(shape: .portrait, digest: "source-cover"),+            entries: [entry(id: 21, url: "https://example.com/read/21")])+        let target = side(+            id: 1, title: "Mother of Learning", provenance: .manual,+            hostnames: ["example.com"],+            readingStatus: .toRead, workStatus: .ongoing, verdict: "",+            releaseDays: [], notes: "Typed notes", tags: ["fantasy"],+            membership: nil, credits: [], thumbnail: nil,+            entries: [entry(id: 11, url: "https://example.com/read/11")])+        // The two sides' own link, which the merge turns into a self-link and+        // discards.+        let link = uuid(600)+        return try WorkMergeBasis(+            source: source, target: target, currentRule: nil,+            sourceLinks: [+                WorkLinkSnapshot(+                    id: link, otherWorkID: uuid(1), otherTitle: nil, linkType: "sequel",+                    modifiedAt: Date(timeIntervalSince1970: 10))+            ],+            targetLinks: [+                WorkLinkSnapshot(+                    id: link, otherWorkID: uuid(2), otherTitle: nil, linkType: "sequel",+                    modifiedAt: Date(timeIntervalSince1970: 10))+            ])+    }++    @Test("The typed title is recorded in the notes and escaped like the header")+    func titleBeforeMergeLine() {+        #expect(WorkMergeField.targetManualTitle.recordedInNotes)+        #expect(!WorkMergeField.sourceDisplayTitle.recordedInNotes)+        #expect(+            WorkMergeAuditFormatter.block(+                sourceTitle: "Source", sourceNotes: "notes", titleBeforeMerge: "Typed\ntitle")+                == "--- Merged from: Source ---\nTitle before merge: Typed\\ntitle\n\nnotes")+        #expect(+            WorkMergeAuditFormatter.block(sourceTitle: "Source", sourceNotes: "")+                == "--- Merged from: Source ---")+    }+     /// The projections above are all single-site, so "the merge's identity     /// answer" is that one row. The V7-shaped facade that used to spell this on     /// `WorkMergeOutcome` went with the columns at V9.@@ -411,7 +793,7 @@ struct WorkMergePlannerTests {             WorkMergeBasis(                 source: work(id: 2, title: "Source", thumbnail: dropped),                 target: work(id: 1, title: "Target", thumbnail: kept),-                currentRule: rule))+                currentRule: rule), request: .merge)         #expect(both.thumbnail == .keepTarget)         #expect(both.retainedFields.contains(.targetThumbnail))         #expect(both.discardedFields.contains(.sourceThumbnail))@@ -423,7 +805,7 @@ struct WorkMergePlannerTests {             WorkMergeBasis(                 source: work(id: 2, title: "Source"),                 target: work(id: 1, title: "Target", thumbnail: kept),-                currentRule: rule))+                currentRule: rule), request: .merge)         #expect(targetOnly.thumbnail == .keepTarget)         #expect(targetOnly.retainedFields.contains(.targetThumbnail))         #expect(!targetOnly.discardedFields.contains(.sourceThumbnail))@@ -441,7 +823,7 @@ struct WorkMergePlannerTests {             WorkMergeBasis(                 source: work(id: 2, title: "Source", thumbnail: adopted),                 target: work(id: 1, title: "Target"),-                currentRule: rule))+                currentRule: rule), request: .merge)          #expect(outcome.thumbnail == .adoptSource(adopted))         #expect(outcome.retainedFields.contains(.sourceThumbnail))@@ -452,7 +834,7 @@ struct WorkMergePlannerTests {         let neither = try WorkMergePlanner.project(             WorkMergeBasis(                 source: work(id: 2, title: "Source"), target: work(id: 1, title: "Target"),-                currentRule: rule))+                currentRule: rule), request: .merge)         #expect(neither.thumbnail == .none)         #expect(!neither.retainedFields.contains(.targetThumbnail))         #expect(!neither.retainedFields.contains(.sourceThumbnail))@@ -473,12 +855,20 @@ struct WorkMergePlannerTests {         thumbnail: ThumbnailIdentity? = nil,         releaseDays: [ReleaseDay] = [],         identity: WorkIdentitySnapshot = .init(value: nil, state: .none, ruleReference: nil),-        entries: [EntrySnapshot] = []+        entries: [EntrySnapshot] = [],+        // `to-read-capture-match`: the parsed title separately from the display+        // title (a split group presents them from two rows), and the carrier's+        // raw columns where a test needs a spelling the typed values cannot+        // carry. Nil is the typed value's own spelling.+        lastParsedTitle: String?? = .none,+        workStatusRaw: String? = nil,+        readingStatusRaw: String? = nil,+        releaseDaysRaw: [String]? = nil     ) -> WorkMergeWorkBasis {         let snapshot = WorkSnapshot(             id: uuid(id),             displayTitle: title,-            lastParsedTitle: title,+            lastParsedTitle: lastParsedTitle ?? title,             memberships: [                 WorkSiteMembershipSnapshot(                     id: uuid(900 + id), hostname: hostname,@@ -498,7 +888,10 @@ struct WorkMergePlannerTests {             thumbnail: thumbnail,             releaseDays: releaseDays         )-        return WorkMergeWorkBasis(snapshot: snapshot, identity: identity)+        return WorkMergeWorkBasis(+            snapshot: snapshot, identity: identity,+            workStatusRaw: workStatusRaw, readingStatusRaw: readingStatusRaw,+            releaseDaysRaw: releaseDaysRaw)     }      private func entry(id: Int, url: String) -> EntrySnapshot {
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeSeriesLinkTests.swift Modified +7 / -7
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeSeriesLinkTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeSeriesLinkTests.swiftindex 0362ae59..94808fb4 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeSeriesLinkTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeSeriesLinkTests.swift@@ -28,7 +28,7 @@ struct WorkMergeSeriesLinkTests {             WorkMergeBasis(                 source: work(id: 2, membership: (Self.seriesA, 2.5), seriesName: "Ashfall Cycle"),                 target: work(id: 1, membership: (Self.seriesA, 1), seriesName: "Ashfall Cycle"),-                currentRule: nil))+                currentRule: nil), request: .merge)          #expect(outcome.membership == SeriesMembership(seriesID: Self.seriesA, position: 1))         #expect(outcome.seriesName == "Ashfall Cycle")@@ -48,7 +48,7 @@ struct WorkMergeSeriesLinkTests {             WorkMergeBasis(                 source: work(id: 2, membership: (Self.seriesB, 3), seriesName: "Quiet Shelf"),                 target: work(id: 1),-                currentRule: nil))+                currentRule: nil), request: .merge)          #expect(outcome.membership == SeriesMembership(seriesID: Self.seriesB, position: 3))         #expect(outcome.seriesName == "Quiet Shelf")@@ -63,7 +63,7 @@ struct WorkMergeSeriesLinkTests {     @Test("Neither side in a series reports no series field")     func noMembershipEitherSide() throws {         let outcome = try WorkMergePlanner.project(-            WorkMergeBasis(source: work(id: 2), target: work(id: 1), currentRule: nil))+            WorkMergeBasis(source: work(id: 2), target: work(id: 1), currentRule: nil), request: .merge)          #expect(outcome.membership == nil)         #expect(outcome.seriesName == nil)@@ -84,7 +84,7 @@ struct WorkMergeSeriesLinkTests {                 WorkMergeBasis(                     source: work(id: 2, membership: (Self.seriesB, 1), seriesName: "Quiet Shelf"),                     target: work(id: 1, membership: (Self.seriesA, 1), seriesName: "Ashfall Cycle"),-                    currentRule: nil))+                    currentRule: nil), request: .merge)         }          // An unresolved side has no name to give, so the label is nil and the@@ -96,7 +96,7 @@ struct WorkMergeSeriesLinkTests {                 WorkMergeBasis(                     source: work(id: 2, membership: (Self.seriesB, 1), seriesName: nil),                     target: work(id: 1, membership: (Self.seriesA, 1), seriesName: "Ashfall Cycle"),-                    currentRule: nil))+                    currentRule: nil), request: .merge)         }          let reason = WorkMergePlanningError.seriesConflict(@@ -148,7 +148,7 @@ struct WorkMergeSeriesLinkTests {                 targetLinks: [                     snapshot(id: selfLinkID, other: sourceID, type: "sequel", modified: 10),                     snapshot(id: targetToThird, other: third, type: "adaptation", modified: 9),-                ]))+                ]), request: .merge)          #expect(outcome.discardedLinks.map(\.id) == [selfLinkID, sourceToThird])         #expect(outcome.discardedLinks.map(\.linkType) == ["sequel", "spin-off"])@@ -170,7 +170,7 @@ struct WorkMergeSeriesLinkTests {                 ],                 targetLinks: [                     snapshot(id: targetToThird, other: third, type: "adaptation", modified: 9)-                ]))+                ]), request: .merge)          #expect(outcome.discardedLinks.map(\.id) == [targetToThird])     }
Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift Added +588 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swiftnew file mode 100644index 00000000..765ea061--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkMergeToReadMatchTests.swift@@ -0,0 +1,588 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++/// `to-read-capture-match` Req 4.2–4.6 through the repository: the commit of a+/// `.toReadMatch` merge writes the planner's raw overrides to every target row,+/// re-checks the candidate rule under the lock, and keeps its request across a+/// refresh.+///+/// The library is seeded row by row, as the group-participation tests do, so a+/// split group and an unknown raw status can be put in front of the commit.+@Suite("Merge commit for a to-read match", .serialized)+struct WorkMergeToReadMatchTests {++    private static let noLongerACandidate = "These works no longer look like the same story."++    // MARK: - Req 4.2, 4.3: what the survivor carries++    @Test("An unchanged library commits every override, and the survivor keeps the to-read UUID")+    func confirmWritesEveryOverride() async throws {+        let library = try ToReadMergeFixture()+        let captured = UUID()+        let toRead = UUID()+        var entryID = UUID()+        try library.seed { store in+            store.insertSite()+            let work = store.insertCaptured(+                id: captured, title: "Mother of Learning (Arc 1)", offset: 0)+            entryID = store.insertEntry(key: "one", offset: 0, work: work).id+            store.insertToRead(id: toRead, title: "Mother of Learning", offset: 20)+        }+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        #expect(contract.request == .toReadMatch)+        let overrides = try #require(contract.outcome.rawOverrides)+        library.save.resetCounts()++        // Nothing changed behind the preview, so it commits rather than+        // refreshing.+        let result = try await repository.commitMerge(contract)+        #expect(result == .committed(targetID: toRead))+        #expect(library.save.attemptCount == 1)++        let rows = try library.rows(of: toRead)+        #expect(rows.count == 1)+        #expect(try library.rows(of: captured).isEmpty)+        let row = try #require(rows.first)+        #expect(row.overrides == overrides)+        #expect(row.overrides == WorkMergeRawOverrides(+            displayTitle: "Mother of Learning (Arc 1)",+            lastParsedTitle: "Mother of Learning (Arc 1)",+            titleProvenanceRaw: TitleProvenance.parsed.rawValue,+            readingStatusRaw: ReadingStatus.reading.rawValue,+            workStatusRaw: WorkStatus.hiatus.rawValue,+            verdict: "loved it",+            releaseDaysRaw: [ReleaseDay.friday.rawValue]))+        // Req 4.4: the captured work's notes and the typed title both survive.+        #expect(row.genericNotes.contains("Typed notes"))+        #expect(row.genericNotes.contains("Captured notes"))+        #expect(row.genericNotes.contains("Title before merge: Mother of Learning"))+        #expect(try library.entryWorkIDs() == [entryID: toRead])++        let survivor = try await repository.work(id: toRead)+        #expect(survivor.readingStatus == .reading)+        #expect(survivor.displayTitle == "Mother of Learning (Arc 1)")+    }++    /// Q31, Q34: raw columns are copied, never re-encoded from a tolerated enum.+    @Test("Unknown raw statuses on the captured work are copied verbatim")+    func unknownCapturedRawStatusesAreCopied() async throws {+        let library = try ToReadMergeFixture()+        let captured = UUID()+        let toRead = UUID()+        try library.seed { store in+            store.insertSite()+            store.insertCaptured(+                id: captured, title: "Mother of Learning", offset: 0,+                readingStatusRaw: "rereading", workStatusRaw: "serialising")+            store.insertToRead(id: toRead, title: "Mother of Learning", offset: 20)+        }+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        #expect(try await repository.commitMerge(contract) == .committed(targetID: toRead))++        let row = try #require(try library.rows(of: toRead).first)+        #expect(row.overrides.readingStatusRaw == "rereading")+        #expect(row.overrides.workStatusRaw == "serialising")+    }++    @Test("An unknown raw work status on the to-read work is kept as not pristine")+    func unknownToReadWorkStatusIsKept() async throws {+        let library = try ToReadMergeFixture()+        let captured = UUID()+        let toRead = UUID()+        try library.seed { store in+            store.insertSite()+            store.insertCaptured(id: captured, title: "Mother of Learning", offset: 0)+            store.insertToRead(+                id: toRead, title: "Mother of Learning", offset: 20,+                workStatusRaw: "paused-by-author")+        }+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        #expect(try await repository.commitMerge(contract) == .committed(targetID: toRead))++        let row = try #require(try library.rows(of: toRead).first)+        #expect(row.overrides.workStatusRaw == "paused-by-author")+        // The reading status is not one of the three the to-read work can keep.+        #expect(row.overrides.readingStatusRaw == ReadingStatus.reading.rawValue)+    }++    /// Q34: the captured group's carrier and representative differ, so its+    /// display title and its parsed title come from different rows. The commit+    /// writes what the preview showed, not what either source row holds on its+    /// own; and a split to-read group takes the overrides on every row, or the+    /// merge would tear it.+    @Test("Split groups: the previewed parsed title is written, to every target row")+    func splitGroupsTakeThePreviewedOverrides() async throws {+        let library = try ToReadMergeFixture()+        let captured = UUID()+        let toRead = UUID()+        try library.seed { store in+            store.insertSite()+            // The representative: earliest, bare, parsed.+            store.insertCaptured(id: captured, title: "Mother of Learning", offset: 0, bare: true)+            // The carrier: an authored title that differs from its own parse.+            store.insertCaptured(+                id: captured, title: "Mother of Learning (Arc 1)", offset: 10,+                parsedTitle: "Mother of Learning, Arc One", provenance: .manual)+            store.insertToRead(id: toRead, title: "Mother of Learning", offset: 20)+            store.insertToRead(id: toRead, title: "Mother of Learning", offset: 30)+        }+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        let overrides = try #require(contract.outcome.rawOverrides)+        #expect(overrides.displayTitle == "Mother of Learning (Arc 1)")+        #expect(overrides.lastParsedTitle == "Mother of Learning")++        #expect(try await repository.commitMerge(contract) == .committed(targetID: toRead))++        let rows = try library.rows(of: toRead)+        #expect(rows.count == 2)+        #expect(rows.allSatisfy { $0.overrides == overrides })+        #expect(Set(rows.map(\.modifiedAt)).count == 1)+        #expect(try library.rows(of: captured).isEmpty)+    }++    // MARK: - Req 3.3: a confirm clears the to-read work from every item++    @Test("Confirming a to-read work on one item removes it from the other at the next publication")+    func confirmRemovesTheToReadWorkFromTheOtherItem() async throws {+        let library = try ToReadMergeFixture()+        let first = UUID()+        let second = UUID()+        let toRead = UUID()+        try library.seed { store in+            store.insertSite()+            // Two captured works with different titles, so they are no Work+            // set, each a whole-word prefix match for the one to-read work.+            store.insertCaptured(id: first, title: "Mother of Learning (Arc 1)", offset: 0)+            store.insertCaptured(id: second, title: "Mother of Learning Side Stories", offset: 10)+            store.insertToRead(id: toRead, title: "Mother of Learning", offset: 20)+        }+        let repository = try await library.openForApp()++        let before = try await repository.todayPresentation(calendar: .current)+            .duplicateWorkload+        #expect(before.toReadMatch(for: first)?.choices.map(\.toReadWorkID) == [toRead])+        #expect(before.toReadMatch(for: second)?.choices.map(\.toReadWorkID) == [toRead])++        let contract = try await repository.projectMerge(+            sourceWorkID: first, targetWorkID: toRead, request: .toReadMatch)+        #expect(try await repository.commitMerge(contract) == .committed(targetID: toRead))++        let after = try await repository.todayPresentation(calendar: .current)+            .duplicateWorkload+        #expect(after.toReadMatch(for: first) == nil)+        // The survivor is no longer to-read, so the other item has no choice+        // left and is not published at all.+        #expect(after.toReadMatch(for: second) == nil)+        #expect(!after.toReadMatches.contains { item in+            item.choices.contains { $0.toReadWorkID == toRead }+        })+    }++    // MARK: - Req 4.5: later captures land on the survivor++    @Test("A later capture on a rule-taught site reuses the survivor")+    func laterCaptureReusesTheSurvivor() async throws {+        let fixture = try await TaughtToReadFixture()+        try await fixture.teach()+        let toRead = try await fixture.repository.createWork(+            NewWorkDraft(+                displayTitle: "Mother of Learning", hostname: "example.com",+                readingStatus: .toRead))+        let first = try await fixture.capture(+            title: "Mother of Learning (Book 1) - Chapter 1",+            rawURL: "https://example.com/read?id=mol&chapter=1")+        let captured = try #require(first.workID)+        #expect(captured != toRead.id)++        let contract = try await fixture.repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead.id, request: .toReadMatch)+        #expect(+            try await fixture.repository.commitMerge(contract)+                == .committed(targetID: toRead.id))++        let second = try await fixture.capture(+            title: "Mother of Learning (Book 1) - Chapter 2",+            rawURL: "https://example.com/read?id=mol&chapter=2")+        #expect(second.workID == toRead.id)+        #expect(try await fixture.repository.work(id: toRead.id).entries.count == 2)+    }++    // MARK: - Req 4.6: the candidate rule, re-checked at the commit++    @Test("A decline recorded behind the preview invalidates the commit and changes nothing")+    func declineBehindThePreviewInvalidates() async throws {+        let library = try ToReadMergeFixture()+        let (captured, toRead) = try library.seedPair()+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        try await repository.recordDistinctPairs([WorkPairKey(captured, toRead)])+        library.save.resetCounts()++        #expect(+            try await repository.commitMerge(contract)+                == .invalidated(reason: Self.noLongerACandidate))+        #expect(library.save.attemptCount == 0)+        try library.expectPairUntouched(captured: captured, toRead: toRead)+    }++    /// A title edit changes the basis, so the commit is stale; the pair no+    /// longer matches either, and that is answered at this first confirm rather+    /// than after a refreshed preview (Q53).+    @Test("A to-read title edited out of match invalidates the first stale commit")+    func titleEditedOutOfMatchInvalidates() async throws {+        let library = try ToReadMergeFixture()+        let (captured, toRead) = try library.seedPair()+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        try library.seed { store in+            for work in try store.works(id: toRead) { work.displayTitle = "Worm" }+        }+        library.save.resetCounts()++        #expect(+            try await repository.commitMerge(contract)+                == .invalidated(reason: Self.noLongerACandidate))+        #expect(library.save.attemptCount == 0)+        try library.expectPairUntouched(captured: captured, toRead: toRead, toReadTitle: "Worm")+    }++    @Test("Either work joining a duplicate set behind the preview invalidates the commit")+    func joiningADuplicateSetInvalidates() async throws {+        let library = try ToReadMergeFixture()+        let (captured, toRead) = try library.seedPair()+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        // A second work with the captured work's parsed title on the same site:+        // the two are a Work set, and Req 3.5 withholds every pair either is in.+        try library.seed { store in+            store.insertCaptured(title: "Mother of Learning (Arc 1)", offset: 40)+        }+        library.save.resetCounts()++        #expect(+            try await repository.commitMerge(contract)+                == .invalidated(reason: Self.noLongerACandidate))+        #expect(library.save.attemptCount == 0)+        try library.expectPairUntouched(captured: captured, toRead: toRead)+    }++    @Test("A failed save leaves both works as they were")+    func failedSaveLeavesTheLibraryUnchanged() async throws {+        let library = try ToReadMergeFixture()+        let (captured, toRead) = try library.seedPair()+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        library.save.shouldFail = true+        await #expect(throws: LibraryRepositoryError.self) {+            try await repository.commitMerge(contract)+        }+        library.save.shouldFail = false++        try library.expectPairUntouched(captured: captured, toRead: toRead)+    }++    // MARK: - The request survives a refresh++    @Test("A refreshed contract still carries .toReadMatch and commits as one")+    func refreshedContractKeepsTheRequest() async throws {+        let library = try ToReadMergeFixture()+        let (captured, toRead) = try library.seedPair()+        let repository = try await library.openForApp()++        let contract = try await repository.projectMerge(+            sourceWorkID: captured, targetWorkID: toRead, request: .toReadMatch)+        try library.seed { store in+            for work in try store.works(id: toRead) { work.genericNotes = "Edited elsewhere" }+        }++        guard case .refreshed(let fresh) = try await repository.commitMerge(contract) else {+            Issue.record("Expected .refreshed")+            return+        }+        #expect(fresh.request == .toReadMatch)+        let overrides = try #require(fresh.outcome.rawOverrides)+        #expect(try await repository.commitMerge(fresh) == .committed(targetID: toRead))++        let row = try #require(try library.rows(of: toRead).first)+        #expect(row.overrides == overrides)+        #expect(row.genericNotes.contains("Edited elsewhere"))+    }+}++// MARK: - Fixture++private final class ToReadMergeFixture {+    static let epoch = Date(timeIntervalSince1970: 1_800_000_000)+    static let hostname = "match.example"++    let directory: URL+    let configuration: LibraryConfiguration+    let save = InstrumentedSaveStrategy()+    private var containers: [ModelContainer] = []++    init() throws {+        directory = FileManager.default.temporaryDirectory+            .appending(path: "AsterismToReadMerge-\(UUID())", directoryHint: .isDirectory)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        configuration = LibraryConfiguration(rootDirectory: directory)+        try FileManager.default.createDirectory(+            at: configuration.storeURL.deletingLastPathComponent(),+            withIntermediateDirectories: true)+    }++    /// Writes through a container of its own, so a call after `openForApp` is+    /// a change arriving behind the repository's back, as a mirror delivers it.+    func seed(_ body: (ToReadMergeSeedStore) throws -> Void) throws {+        let container = try LibraryRepository.openContainer(at: configuration.storeURL)+        let store = ToReadMergeSeedStore(context: ModelContext(container))+        try body(store)+        try store.context.save()+        try SiteRelationshipPopulationPass.run(context: store.context)+        withExtendedLifetime(container) {}+        try LibraryRepository.publishReadiness(at: configuration.readinessMarkerURL)+    }++    /// One captured work with one entry and one pristine to-read work that+    /// pairs with it by title prefix.+    func seedPair() throws -> (captured: UUID, toRead: UUID) {+        let captured = UUID()+        let toRead = UUID()+        try seed { store in+            store.insertSite()+            let work = store.insertCaptured(+                id: captured, title: "Mother of Learning (Arc 1)", offset: 0)+            store.insertEntry(key: "one", offset: 0, work: work)+            store.insertToRead(id: toRead, title: "Mother of Learning", offset: 20)+        }+        return (captured, toRead)+    }++    func openForApp() async throws -> LibraryRepository {+        let (_, repository) = try await LibraryRepository.openForApp(+            configuration, capabilities: .multiSite,+            clock: FixedRepositoryClock(Self.epoch),+            saveStrategy: save)+        return repository+    }++    private func readContext() throws -> ModelContext {+        let container = try LibraryRepository.openContainer(at: configuration.storeURL)+        containers.append(container)+        return ModelContext(container)+    }++    func rows(of id: UUID) throws -> [MergedWorkRow] {+        try readContext().fetch(FetchDescriptor<Work>())+            .filter { $0.id == id }+            .sorted { $0.createdAt < $1.createdAt }+            .map(MergedWorkRow.init)+    }++    func entryWorkIDs() throws -> [UUID: UUID?] {+        Dictionary(+            uniqueKeysWithValues: try readContext().fetch(FetchDescriptor<Entry>())+                .map { ($0.id, $0.work?.id) })+    }++    /// Req 4.6: both works exist exactly as `seedPair` left them, the entry+    /// still on the captured work.+    func expectPairUntouched(+        captured: UUID, toRead: UUID, toReadTitle: String = "Mother of Learning",+        sourceLocation: SourceLocation = #_sourceLocation+    ) throws {+        let capturedRow = try #require(+            try rows(of: captured).first, sourceLocation: sourceLocation)+        #expect(+            capturedRow.overrides.displayTitle == "Mother of Learning (Arc 1)",+            sourceLocation: sourceLocation)+        let toReadRow = try #require(try rows(of: toRead).first, sourceLocation: sourceLocation)+        #expect(+            toReadRow.overrides == WorkMergeRawOverrides(+                displayTitle: toReadTitle, lastParsedTitle: nil,+                titleProvenanceRaw: TitleProvenance.manual.rawValue,+                readingStatusRaw: ReadingStatus.toRead.rawValue,+                workStatusRaw: WorkStatus.ongoing.rawValue, verdict: "", releaseDaysRaw: []),+            sourceLocation: sourceLocation)+        #expect(toReadRow.genericNotes == "Typed notes", sourceLocation: sourceLocation)+        #expect(+            Set(try entryWorkIDs().values) == [captured], sourceLocation: sourceLocation)+    }++    deinit {+        try? FileManager.default.removeItem(at: directory)+    }+}++/// The columns a `.toReadMatch` commit writes, read off one stored row.+private struct MergedWorkRow {+    let overrides: WorkMergeRawOverrides+    let genericNotes: String+    let modifiedAt: Date++    init(_ work: Work) {+        overrides = WorkMergeRawOverrides(+            displayTitle: work.displayTitle,+            lastParsedTitle: work.lastParsedTitle,+            titleProvenanceRaw: work.titleProvenanceRaw,+            readingStatusRaw: work.readingStatusRaw,+            workStatusRaw: work.workStatusRaw,+            verdict: work.verdict,+            releaseDaysRaw: work.releaseDaysRaw)+        genericNotes = work.genericNotes+        modifiedAt = work.modifiedAt+    }+}++private final class ToReadMergeSeedStore {+    let context: ModelContext++    init(context: ModelContext) { self.context = context }++    @discardableResult+    func insertSite() -> Site {+        let site = Site(hostname: ToReadMergeFixture.hostname)+        site.mode = .untaught+        context.insert(site)+        return site+    }++    func works(id: UUID) throws -> [Work] {+        try context.fetch(FetchDescriptor<Work>()).filter { $0.id == id }+    }++    /// A captured work: parsed unless told otherwise, with a value the reader+    /// could care about in every field a to-read match decides, unless `bare`.+    @discardableResult+    func insertCaptured(+        id: UUID = UUID(), title: String, offset: TimeInterval,+        parsedTitle: String? = nil, provenance: TitleProvenance = .parsed,+        readingStatusRaw: String = ReadingStatus.reading.rawValue,+        workStatusRaw: String = WorkStatus.hiatus.rawValue, bare: Bool = false+    ) -> Work {+        let work = insertWork(id: id, title: title, offset: offset)+        work.lastParsedTitle = parsedTitle ?? title+        work.titleProvenanceRaw = provenance.rawValue+        // Every authored field at its default, so the row folds silently into+        // an authored sibling rather than tearing the group.+        guard !bare else { return work }+        work.readingStatusRaw = readingStatusRaw+        work.workStatusRaw = workStatusRaw+        work.verdict = "loved it"+        work.releaseDaysRaw = [ReleaseDay.friday.rawValue]+        work.genericNotes = "Captured notes"+        return work+    }++    /// A to-read work as the New Work form makes it: a manual title, no parsed+    /// title, every other value pristine.+    @discardableResult+    func insertToRead(+        id: UUID = UUID(), title: String, offset: TimeInterval,+        workStatusRaw: String = WorkStatus.ongoing.rawValue+    ) -> Work {+        let work = insertWork(id: id, title: title, offset: offset)+        work.titleProvenance = .manual+        work.readingStatus = .toRead+        work.workStatusRaw = workStatusRaw+        work.genericNotes = "Typed notes"+        return work+    }++    private func insertWork(id: UUID, title: String, offset: TimeInterval) -> Work {+        let work = Work.create(+            in: context, id: id, title: title, hostname: ToReadMergeFixture.hostname,+            site: try? LibraryRepository.fetchSites(+                hostname: ToReadMergeFixture.hostname, context: context).first,+            timestamp: ToReadMergeFixture.epoch.addingTimeInterval(offset))+        work.modifiedAt = ToReadMergeFixture.epoch.addingTimeInterval(offset)+        return work+    }++    @discardableResult+    func insertEntry(key: String, offset: TimeInterval, work: Work) -> Entry {+        let rawURL = "https://\(ToReadMergeFixture.hostname)/read/\(key)"+        let entry = Entry(+            id: UUID(), captureTitle: "Chapter \(key)", captureTitleSource: .host,+            rawURLString: rawURL, hostname: ToReadMergeFixture.hostname,+            entryIdentityKey: rawURL,+            timestamp: ToReadMergeFixture.epoch.addingTimeInterval(offset))+        entry.conservativeIdentityKey = rawURL+        entry.lastSharedAt = ToReadMergeFixture.epoch.addingTimeInterval(offset)+        context.insert(entry)+        entry.work = work+        entry.editCitations { $0.workAssignment = .manual }+        return entry+    }+}++/// A site taught a `.workAndSequence` rule, so a capture mints a URL identity+/// and a later one reuses it — the shape `DuplicatePublicationTests` uses,+/// because `capture(_:)` applies no rules (`docs/agent-notes/testing.md`).+private struct TaughtToReadFixture {+    let repository: LibraryRepository++    init() async throws {+        let directory = FileManager.default.temporaryDirectory+            .appending(path: "AsterismToReadMergeTaught-\(UUID())", directoryHint: .isDirectory)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        repository = try await LibraryRepository.openForApp(+            LibraryConfiguration(rootDirectory: directory),+            clock: FixedRepositoryClock(ToReadMergeFixture.epoch),+            saveStrategy: ModelContextSaveStrategy()).repository+    }++    func teach() async throws {+        // Teaching needs a `Site` row, and the conservative capture door mints+        // one.+        _ = try await repository.capture(+            CaptureDraft(+                captureTitle: "A Serial - Chapter 0", captureTitleSource: .manual,+                rawURLString: "https://example.com/read?id=serial&chapter=0",+                canonicalURLString: nil, note: "", rating: nil))+        let contract = try await repository.projectComposedTeaching(+            hostname: "example.com",+            request: ComposedTeachingRequest(+                titleDefinition: .phrase(+                    prefix: "", separator: " - ", suffix: "", order: .workThenChapter),+                urlDefinition: .workAndSequence(+                    work: URLFieldSelector(locator: .query(name: ExactScalarString("id"))),+                    sequence: URLFieldSelector(+                        locator: .query(name: ExactScalarString("chapter"))))))+        guard case .committed = try await repository.commitComposedTeaching(contract) else {+            throw CocoaError(.fileWriteUnknown)+        }+    }++    func capture(title: String, rawURL: String) async throws -> EntrySnapshot {+        let contract = try await repository.projectCapture(+            hostname: "example.com", captureTitle: title, captureTitleSource: .safariDocument,+            rawURLString: rawURL, canonicalURLString: nil, note: "", rating: nil)+        guard case .committed(let snapshot) = try await repository.commitCapture(contract) else {+            throw CocoaError(.fileWriteUnknown)+        }+        return snapshot+    }+}

Docs (11)

CHANGELOG.md Modified +49 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex add46702..63254dd8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -236,6 +236,55 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ### Added +- **To-read capture match: the sheet and its performance arms (T-2366,+  `specs/to-read-capture-match/`, tasks 13–16).** When a captured work may+  be a story already waiting in To Read, Today's duplicate banner counts it+  (all-blocked items included), a row under Elsewhere says "May belong to a+  story in To Read", and the work's row in Works carries a "To Read?" pill.+  Either one opens a sheet with the captured work and one choice per+  to-read work. A blocked choice (quarantined site, conflicting series)+  gives its reason. Choosing one opens the merge preview in the same sheet,+  with the `.toReadMatch` request and the to-read work preset as the+  target. The preview shows the typed title the merge replaces. Confirming+  closes the sheet and opens the survivor on the stack that opened it.+  A plain cancel returns to the card as it was; only a refused or+  invalidated confirm refreshes before the card comes back. Both ways out+  are disabled while the commit runs (Q47–Q49). "None of+  these" records every listed pair through `recordDistinctPairs`, then+  refreshes without a reconcile pass (Q25). A new UI-test scenario,+  `seeded-tolerated-to-read-match`, drives the journeys on iPhone, at+  AccessibilityXXXL and in the iPad wide layout. Row B15 of the manual Mac+  checklist covers the sheet's wide layout. `M4ToReadMatchScalePerformanceTests`+  adds three arms:+  - derivation: 0.018 s against a 100 ms budget;+  - publication: 0.904 s against Today's 2 s budget;+  - the commit's re-check: 0.218 s, reported only.++  The target is now 50 tests in 9 suites (`specs/to-read-capture-match/verification-run.md`).++- **To-read capture match: the matcher and the merge, in Core (T-2366,+  `specs/to-read-capture-match/`, tasks 1–12).** `ToReadMatcher` pairs a+  to-read work with another work on a shared site when the site's URL rule+  reads the same Work URL from both, or when their normalised titles are+  equal or one is a whole-word prefix of the other. Normalisation applies+  NFKD, a locale-free full case fold and NFKD again, then drops nonspacing+  marks and format characters, turns punctuation and symbols into spaces,+  and splits words on U+0020 (Q27, Q44). A pair is left out when it was+  declined, when either work sits in a work set that publishes a review+  item, or when either is torn (Q38). The pairs are derived only in+  `todayPresentation`, as a second kind of item on the duplicate workload,+  `toReadMatches`. The scan and the reconcile pass never see them, and+  `reviewCount` is unchanged. `recordDistinctPairs` records every declined+  pair in one commit. A `.toReadMatch` merge request keeps the to-read+  work's UUID and takes the captured work's titles and statuses, while+  keeping a work status, verdict or release days the reader had edited. It+  records the typed title in the audit block and writes raw values+  verbatim, and it re-checks the candidate rule under the lock, at the+  first confirm even when the preview is stale, so a pair that stopped+  matching is refused rather than refreshed (Q53). A `.refreshed` contract+  keeps its request, so a refresh cannot turn into a plain merge. No schema, marker or+  archive change. The app surfaces follow in the next phase.+ - **A site or a URL when creating a work, in the app (T-2365,   `specs/new-work-url-field/`, task 4).** The New Work form's second field   is titled "Site or URL", which the Mac draws and VoiceOver reads on
CLAUDE.md Modified +1 / -1
diff --git a/CLAUDE.md b/CLAUDE.mdindex 964d855a..4c101281 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -68,7 +68,7 @@ invocations where a target exists. - `make test-quick` — unit-test bundle only (simulator), preceded by `build-mac`: a macOS compile failure fails it (Req 9.1). The Mac build is never installed or launched. `SKIP_MAC=1` drops that dependency loudly and owes a clean `make build-mac` before the push. - `make test` / `make test-ui` — full suites (simulator, iPhone); they skip the iPad-only suites by name - `make test-ui-ipad` — the wide-layout and wide-layout-accessibility suites on `IPAD_SIMULATOR` (simulator, safe)-- `make test-performance-m4` — M4 Core budgets, host only, no device, safe to run. **~21 minutes** (1,093 s of test time measured 2026-08-28, 1,120 s over 28 tests on 2026-08-30 after `character-ranking` added its own, and **1,120.6 s over 32 tests on 2026-09-05** after T-1910 added four Work-bearing preview arms — all quiet-host runs, all `EXIT=0` with the same eight known issues, so the 21 minutes still holds and the four added arms cost no measurable wall time. T-2093 took the settling pass from ~7.3 s to ~1.7 s per sample; three contended runs on 2026-09-05 measured 1,136 s, 1,237 s and 1,085 s over the same 32 tests, all `EXIT=0` with **seven** known issues. A *loaded* run of those same 32 tests took 1,380 s and breached a regression ceiling on an untouched arm; that is host contention, not a band. Add a ~190 s release build to any of them): most of it is the worst-case single-hostname consolidation in `M4ScalePerformanceTests` (5 samples, each paying its own ~40 s divert before a ~40 s measurement) and the Req 10.1 settling pass (10 samples, each re-seeding 1,350 duplicate rows plus an untimed observation pass). The V4→V5 migration measurement is **gone** — `retire-migration-chain` deleted the pass it timed along with the suite. **The target exits 0 on a quiet host**, with the accepted breaches reported as `withKnownIssue` known issues rather than failures — **ten** since `work-thumbnails` (four before `multi-site-works`, nine after it, eight after `drop-superseded-columns`, seven after T-2093, eight after `series-and-related-works`, nine after `work-creators`), and **eleven on a loaded host**, because `creator-converge-noop` is wrapped `isIntermittent` and only records when the host is busy. Three are long-standing: Req 5.5's three diagnosis re-derivations. Three are Req 5.4's capture-projection arms (0.093–0.102 s pre-V8 → 0.160–0.170 s at V9 → 0.169–0.176 s at V10 → **0.179–0.205 s at V12** → 0.158–0.164 s at V13 on a quieter host, the one on a path the reader waits on; V12's three new tables and V13's two are empty on that path and cost it nothing the run's own host variance does not explain, still well inside a 250 ms ceiling). The seventh is the **full**-tier no-op reconcile, and V9 recovered most of it: 1.07 s → **0.0296–0.0302 s** once `V8PopulationPass` was deleted with the columns and `MembershipReconciler.heal` was gated on the diagnosis, which is still 3.0× a 10 ms ceiling drawn before the library had a membership table; V10 left it there (0.0301 s), V12 did too (0.0308 s) and so did V13 (0.0302 s). Req 10.1's *observation* pass **retired** with that fall (2.69 s → 1.01 s, back inside its 2 s budget, and 1.02 s at V10), and its **settling** pass retired at T-2093: 88% of that pass was SwiftData maintaining `Site.entries` inside the deletion phase's one `save` (6.42 s before the fix, 0.41 s after; the measured 8.0 ms per deleted row over a 5,000-row Site is supporting evidence, not the arithmetic — only the 250 Entry losers of the 300 deleted rows sit in `Site.entries`), and detaching a chunk's doomed rows from their Site in one rewrite of that array took it from 7.3 s to ~1.6 s, inside its 2 s budget, with the 11 s floor under the known issue gone too (`specs/bugfixes/settling-pass-budget/`, Decision 32). The eighth is `series-and-related-works` Req 14.6's link dedupe, a 10 ms budget measured at 0.0100–0.0112 s over 500 links — the low end is `place-extraction`'s run at 0.010032 s, 0.3% over the budget and the closest it has come to fitting, which would turn a quiet host into a *second* way to be red: the whole-table fetch the phase opens with is 79–83% of that, so the budget sits under what SwiftData charges to materialise the rows (Q59 of that spec). The ninth is `work-creators` Req 11.6's credit dedupe, a 50 ms budget measured at 0.0591–0.0651 s over ~2,000 credits, of which the whole-table fetch is 76% (Q73 of that spec, 130 ms ceiling). The intermittent eleventh is that spec's `creator-converge-noop`, in budget at 0.0081–0.0100 s against 10 ms across five samples and never more than 19% clear of it, so it is asserted `isIntermittent` with a 20 ms ceiling (Q74). The tenth is `work-thumbnails` Q80's **`backup-export-thumbnails` peak**: the real exporter over the covered fixture writes a **51.1 MB** archive and peaks **330–462 MB** over its baseline, past the 400 MB Q61 accepted from an estimate, recorded rather than re-based, with a 600 MB regression ceiling asserted outside the block. It is deliberately **not** `isIntermittent`, which means a run whose peak lands *under* 400 MB fails the target with `Known issue was not recorded` — that fired for the first time on 2026-09-13, on a memory-pressured host at 330.2 MB, and a lower peak there is the allocator reclaiming sooner, not the export getting cheaper (`specs/work-thumbnails/verification-run.md` §2.2). Its sibling `backup-import-thumbnails` **meets** the 400 MB plainly at 63.5–159.2 MB, with a settled baseline of 103–144 MB over five runs on one host (`specs/work-thumbnails/verification-run.md` §4.1), and `thumbnail-bytes-read` (fifty on-demand cover reads, Req 7.2) is reported only, 0.032–0.231 s under the 3 s class ceiling. Its other creator arms are `credits-resolve-and-filter` at 0.0144–0.0154 s under a 20 ms budget, `dedupe-credits-fetch` at 0.0477–0.0496 s reported only, `creator-detail` at 0.0363–0.0376 s under 50 ms, and the two read arms `works-snapshot-creators` (1.75–2.11 s) and `creators-list` (0.274–0.284 s) under the 3 s class ceiling. `series-and-related-works` adds `M4SeriesScalePerformanceTests`, `work-creators` adds `M4CreatorScalePerformanceTests` and `empty-library` adds `M4EmptyLibraryPerformanceTests` — one suite, one test, the `empty-library-m4` arm, which empties the covered fixture's **7,009 rows** three times over and costs the target ~50 s. Run **on its own** it measures **5.544–5.942 s** of median over five runs, every sample 5.541–6.244 s, and it is strikingly load-insensitive: those five spanned a one-minute load average of 5 to 241 and moved 7.2%, the loudest run *below* the second-loudest. Run **inside the target**, after twenty minutes of other suites have been through the page cache, the same arm reads **7.712 s** — which is why its regression ceiling is **16 s** (2.07× the in-target median) rather than the 12 s the solo band alone would have given; reported rather than budgeted (Q18 of that spec). `specs/empty-library/verification-run.md` has the runs, the per-phase split — entries 71.6%, memberships 23.8%, works 4.5% — and what the design's first risk turned out to be: no undetached inverse dominates, because children go before parents, so every parent's inverse array is already empty by the time the parent is deleted, and the works phase is the *cheapest* per row in the list. So the suite count is **8** and the test count **47**: `empty-library` added `M4EmptyLibraryPerformanceTests` and its one arm, and `launch-to-today` added `launchReads` — Req 1.3's two reported-only arms, `launch-reads-full` and `launch-reads-today`, one more test in `M4ToleratedScalePerformanceTests` and no new suite — on top of the 45 `update-schedule` reached by adding `todayPublication`, Req 10.5's Today composition arm, likewise one more test in that suite and no new suite, itself on top of the 44 `work-thumbnails` reached by adding three arms and no suite — `thumbnail-bytes-read`, `backup-export-thumbnails` and `backup-import-thumbnails`, all three in `M4DuplicateScalePerformanceTests` and all three reported rather than budgeted, together worth 2.5–4 minutes of the run. **Both `empty-library` and `launch-to-today` were measured against a 46-test target and each reported 46 in its own branch; 47 is the two of them together.** It was 41 at `place-extraction`, measured as one run at **1,070 s**; the three runs made on the `work-thumbnails` branch measured **1,896 s, 2,683 s and 5,037 s** on a machine that was never quiet, so they set no band and moved none — two of them disagree with each other by 1.7× on the same arms, and an arm that never opens a store doubled (`specs/work-thumbnails/verification-run.md` §2.3). **A quiet-host run of the covered fixture is still owed**, and since `catch-up-mode` that fixture also holds 66 base works on `catchingUp`, which `WorkAuthoredContent.isBare` counts as authored, so every band below the `todayPublication` arm (**0.896 s** since `launch-to-today` amended it, see below; 0.84 s on a loaded host before that, `specs/catch-up-mode/verification-run.md`) is unverified against the fixture as it now stands. That arm is `place-ranking-200x50` at **0.0035 s** against a 10 ms budget and a 50 ms ceiling, recorded beside its sibling `character-ranking-200x50` at **0.0037 s** — the ranker is one generic implementation over `RecordRow` and the point of the arm is that the second conformance costs what the first does. The character arm's own number moved up from 0.0023–0.0025 s in the same change, which is the cost of `CharacterRanking` becoming `RecordRanking`; read 0.0037 s as its new resting place, not as a regression. Every one has a regression ceiling asserted *outside* its known-issue block, so a run that drifts further still fails; `RUNS=3` completes all three runs. `launch-to-today` added the two `launchReads` arms and **amended** `todayPublication`. The `launchReads` pair is reported with no budget and times the repository reads that stand between the store being open and Today being drawable: `launch-reads-full` (`todayPresentation` + `works` + `siteNames`) at **2.435 s** and `launch-reads-today` (`todayPresentation` + `siteNames`) at **0.852 s**, against 2.497 s for the full arm on the before commit measured twelve minutes earlier on the same host — a **1.645 s, 65.9%** fall in what the reader waits on, with the full arm itself unmoved (−2.5%), so the works read was relocated and not removed (`specs/launch-to-today/verification-run.md` §4). Read them as read time and not as time-to-first-Today: the store open, the capture drain and every app-side derivation sit outside them, and on a real library far fewer than 466 of 1,000 works qualify for Today. `todayPublication` no longer makes its own `works()` read or its own `TodaySchedule.build` call — `todayPresentation` builds the schedule and the work titles inside the read since Decision 2 of that spec — and it measures **0.896 s** median at spread 1.08×, inside its 2 s budget with 1.10 s of headroom, agreeing with the 0.903 s an independent run measured the same day. That whole-target run was 1,272.6 s over the 46 tests the target then had, `EXIT=0`, nine known issues; `empty-library`'s arm has since added about 50 s and a forty-seventh test. See `specs/launch-to-today/verification-run.md` for the launch figures and the one like-for-like before/after pair this target has been given, `specs/work-thumbnails/verification-run.md` for the current numbers and for what a contended host does to all of them, `specs/place-extraction/verification-run.md` for the last quiet-host band, `specs/work-creators/verification-run.md` and `specs/bugfixes/settling-pass-budget/` for the previous ones, `specs/series-and-related-works/verification-run.md` for the ones before those, `specs/work-and-reading-status/verification-run.md` §4 for the previous ones, `specs/drop-superseded-columns/verification-run.md` and `specs/multi-site-works/verification-run.md` §4 and §7 for the previous ones, and `docs/agent-notes/testing.md` for recording a band.+- `make test-performance-m4` — M4 Core budgets, host only, no device, safe to run. **~21 minutes** (1,093 s of test time measured 2026-08-28, 1,120 s over 28 tests on 2026-08-30 after `character-ranking` added its own, and **1,120.6 s over 32 tests on 2026-09-05** after T-1910 added four Work-bearing preview arms — all quiet-host runs, all `EXIT=0` with the same eight known issues, so the 21 minutes still holds and the four added arms cost no measurable wall time. T-2093 took the settling pass from ~7.3 s to ~1.7 s per sample; three contended runs on 2026-09-05 measured 1,136 s, 1,237 s and 1,085 s over the same 32 tests, all `EXIT=0` with **seven** known issues. A *loaded* run of those same 32 tests took 1,380 s and breached a regression ceiling on an untouched arm; that is host contention, not a band. Add a ~190 s release build to any of them): most of it is the worst-case single-hostname consolidation in `M4ScalePerformanceTests` (5 samples, each paying its own ~40 s divert before a ~40 s measurement) and the Req 10.1 settling pass (10 samples, each re-seeding 1,350 duplicate rows plus an untimed observation pass). The V4→V5 migration measurement is **gone** — `retire-migration-chain` deleted the pass it timed along with the suite. **The target exits 0 on a quiet host**, with the accepted breaches reported as `withKnownIssue` known issues rather than failures — **ten** since `work-thumbnails` (four before `multi-site-works`, nine after it, eight after `drop-superseded-columns`, seven after T-2093, eight after `series-and-related-works`, nine after `work-creators`), and **eleven on a loaded host**, because `creator-converge-noop` is wrapped `isIntermittent` and only records when the host is busy. Three are long-standing: Req 5.5's three diagnosis re-derivations. Three are Req 5.4's capture-projection arms (0.093–0.102 s pre-V8 → 0.160–0.170 s at V9 → 0.169–0.176 s at V10 → **0.179–0.205 s at V12** → 0.158–0.164 s at V13 on a quieter host, the one on a path the reader waits on; V12's three new tables and V13's two are empty on that path and cost it nothing the run's own host variance does not explain, still well inside a 250 ms ceiling). The seventh is the **full**-tier no-op reconcile, and V9 recovered most of it: 1.07 s → **0.0296–0.0302 s** once `V8PopulationPass` was deleted with the columns and `MembershipReconciler.heal` was gated on the diagnosis, which is still 3.0× a 10 ms ceiling drawn before the library had a membership table; V10 left it there (0.0301 s), V12 did too (0.0308 s) and so did V13 (0.0302 s). Req 10.1's *observation* pass **retired** with that fall (2.69 s → 1.01 s, back inside its 2 s budget, and 1.02 s at V10), and its **settling** pass retired at T-2093: 88% of that pass was SwiftData maintaining `Site.entries` inside the deletion phase's one `save` (6.42 s before the fix, 0.41 s after; the measured 8.0 ms per deleted row over a 5,000-row Site is supporting evidence, not the arithmetic — only the 250 Entry losers of the 300 deleted rows sit in `Site.entries`), and detaching a chunk's doomed rows from their Site in one rewrite of that array took it from 7.3 s to ~1.6 s, inside its 2 s budget, with the 11 s floor under the known issue gone too (`specs/bugfixes/settling-pass-budget/`, Decision 32). The eighth is `series-and-related-works` Req 14.6's link dedupe, a 10 ms budget measured at 0.0100–0.0112 s over 500 links — the low end is `place-extraction`'s run at 0.010032 s, 0.3% over the budget and the closest it has come to fitting, which would turn a quiet host into a *second* way to be red: the whole-table fetch the phase opens with is 79–83% of that, so the budget sits under what SwiftData charges to materialise the rows (Q59 of that spec). The ninth is `work-creators` Req 11.6's credit dedupe, a 50 ms budget measured at 0.0591–0.0651 s over ~2,000 credits, of which the whole-table fetch is 76% (Q73 of that spec, 130 ms ceiling). The intermittent eleventh is that spec's `creator-converge-noop`, in budget at 0.0081–0.0100 s against 10 ms across five samples and never more than 19% clear of it, so it is asserted `isIntermittent` with a 20 ms ceiling (Q74). The tenth is `work-thumbnails` Q80's **`backup-export-thumbnails` peak**: the real exporter over the covered fixture writes a **51.1 MB** archive and peaks **330–462 MB** over its baseline, past the 400 MB Q61 accepted from an estimate, recorded rather than re-based, with a 600 MB regression ceiling asserted outside the block. It is deliberately **not** `isIntermittent`, which means a run whose peak lands *under* 400 MB fails the target with `Known issue was not recorded` — that fired for the first time on 2026-09-13, on a memory-pressured host at 330.2 MB, and a lower peak there is the allocator reclaiming sooner, not the export getting cheaper (`specs/work-thumbnails/verification-run.md` §2.2). Its sibling `backup-import-thumbnails` **meets** the 400 MB plainly at 63.5–159.2 MB, with a settled baseline of 103–144 MB over five runs on one host (`specs/work-thumbnails/verification-run.md` §4.1), and `thumbnail-bytes-read` (fifty on-demand cover reads, Req 7.2) is reported only, 0.032–0.231 s under the 3 s class ceiling. Its other creator arms are `credits-resolve-and-filter` at 0.0144–0.0154 s under a 20 ms budget, `dedupe-credits-fetch` at 0.0477–0.0496 s reported only, `creator-detail` at 0.0363–0.0376 s under 50 ms, and the two read arms `works-snapshot-creators` (1.75–2.11 s) and `creators-list` (0.274–0.284 s) under the 3 s class ceiling. `series-and-related-works` adds `M4SeriesScalePerformanceTests`, `work-creators` adds `M4CreatorScalePerformanceTests` and `empty-library` adds `M4EmptyLibraryPerformanceTests` — one suite, one test, the `empty-library-m4` arm, which empties the covered fixture's **7,009 rows** three times over and costs the target ~50 s. Run **on its own** it measures **5.544–5.942 s** of median over five runs, every sample 5.541–6.244 s, and it is strikingly load-insensitive: those five spanned a one-minute load average of 5 to 241 and moved 7.2%, the loudest run *below* the second-loudest. Run **inside the target**, after twenty minutes of other suites have been through the page cache, the same arm reads **7.712 s** — which is why its regression ceiling is **16 s** (2.07× the in-target median) rather than the 12 s the solo band alone would have given; reported rather than budgeted (Q18 of that spec). `specs/empty-library/verification-run.md` has the runs, the per-phase split — entries 71.6%, memberships 23.8%, works 4.5% — and what the design's first risk turned out to be: no undetached inverse dominates, because children go before parents, so every parent's inverse array is already empty by the time the parent is deleted, and the works phase is the *cheapest* per row in the list. So the suite count is **9** and the test count **50**: `to-read-capture-match` added `M4ToReadMatchScalePerformanceTests`, three arms over its own store with `seedM4ToReadMatchLayer` over the base fixture (50 to-read works and 10 captured prefix partners) — `to-read-match-derivation` against a 100 ms budget and no ceiling below it, because the fixture already runs the matcher's single-bucket worst case (Q52 of that spec), `to-read-match-publication` against the 2 s Today budget and a 3 s ceiling, and `to-read-match-recheck` reported only — measured only on a loaded host so far (0.0196–0.0198 s, 0.910–0.959 s and 0.212–0.232 s median over two filtered runs, and 0.0182 s, 0.904 s and 0.218 s inside a 1,214.4 s whole-target run), so its quiet-host band is still owed; `empty-library` added `M4EmptyLibraryPerformanceTests` and its one arm, and `launch-to-today` added `launchReads` — Req 1.3's two reported-only arms, `launch-reads-full` and `launch-reads-today`, one more test in `M4ToleratedScalePerformanceTests` and no new suite — on top of the 45 `update-schedule` reached by adding `todayPublication`, Req 10.5's Today composition arm, likewise one more test in that suite and no new suite, itself on top of the 44 `work-thumbnails` reached by adding three arms and no suite — `thumbnail-bytes-read`, `backup-export-thumbnails` and `backup-import-thumbnails`, all three in `M4DuplicateScalePerformanceTests` and all three reported rather than budgeted, together worth 2.5–4 minutes of the run. **Both `empty-library` and `launch-to-today` were measured against a 46-test target and each reported 46 in its own branch; 47 is the two of them together, and 50 adds `to-read-capture-match`'s three.** It was 41 at `place-extraction`, measured as one run at **1,070 s**; the three runs made on the `work-thumbnails` branch measured **1,896 s, 2,683 s and 5,037 s** on a machine that was never quiet, so they set no band and moved none — two of them disagree with each other by 1.7× on the same arms, and an arm that never opens a store doubled (`specs/work-thumbnails/verification-run.md` §2.3). **A quiet-host run of the covered fixture is still owed**, and since `catch-up-mode` that fixture also holds 66 base works on `catchingUp`, which `WorkAuthoredContent.isBare` counts as authored, so every band below the `todayPublication` arm (**0.896 s** since `launch-to-today` amended it, see below; 0.84 s on a loaded host before that, `specs/catch-up-mode/verification-run.md`) is unverified against the fixture as it now stands. That arm is `place-ranking-200x50` at **0.0035 s** against a 10 ms budget and a 50 ms ceiling, recorded beside its sibling `character-ranking-200x50` at **0.0037 s** — the ranker is one generic implementation over `RecordRow` and the point of the arm is that the second conformance costs what the first does. The character arm's own number moved up from 0.0023–0.0025 s in the same change, which is the cost of `CharacterRanking` becoming `RecordRanking`; read 0.0037 s as its new resting place, not as a regression. Every one has a regression ceiling asserted *outside* its known-issue block, so a run that drifts further still fails; `RUNS=3` completes all three runs. `launch-to-today` added the two `launchReads` arms and **amended** `todayPublication`. The `launchReads` pair is reported with no budget and times the repository reads that stand between the store being open and Today being drawable: `launch-reads-full` (`todayPresentation` + `works` + `siteNames`) at **2.435 s** and `launch-reads-today` (`todayPresentation` + `siteNames`) at **0.852 s**, against 2.497 s for the full arm on the before commit measured twelve minutes earlier on the same host — a **1.645 s, 65.9%** fall in what the reader waits on, with the full arm itself unmoved (−2.5%), so the works read was relocated and not removed (`specs/launch-to-today/verification-run.md` §4). Read them as read time and not as time-to-first-Today: the store open, the capture drain and every app-side derivation sit outside them, and on a real library far fewer than 466 of 1,000 works qualify for Today. `todayPublication` no longer makes its own `works()` read or its own `TodaySchedule.build` call — `todayPresentation` builds the schedule and the work titles inside the read since Decision 2 of that spec — and it measures **0.896 s** median at spread 1.08×, inside its 2 s budget with 1.10 s of headroom, agreeing with the 0.903 s an independent run measured the same day. That whole-target run was 1,272.6 s over the 46 tests the target then had, `EXIT=0`, nine known issues; `empty-library`'s arm has since added about 50 s and a forty-seventh test. See `specs/launch-to-today/verification-run.md` for the launch figures and the one like-for-like before/after pair this target has been given, `specs/work-thumbnails/verification-run.md` for the current numbers and for what a contended host does to all of them, `specs/place-extraction/verification-run.md` for the last quiet-host band, `specs/work-creators/verification-run.md` and `specs/bugfixes/settling-pass-budget/` for the previous ones, `specs/series-and-related-works/verification-run.md` for the ones before those, `specs/work-and-reading-status/verification-run.md` §4 for the previous ones, `specs/drop-superseded-columns/verification-run.md` and `specs/multi-site-works/verification-run.md` §4 and §7 for the previous ones, and `docs/agent-notes/testing.md` for recording a band. - `make test-performance-chunks` — host-only calibration sweep of the shared bulk chunk constant (import commits and the reconciler re-pin). No device, safe to run, but gated on `ASTERISM_RUN_CHUNK_SWEEP=1` and **~20 minutes per run**, so it is deliberately *not* part of `make test-performance-m4`. It asserts nothing — a calibration is reported, not budgeted. Re-run it when the bulk write paths change (Q53 and the task 25 section of `specs/cloudkit-mirroring/implementation.md`). - `make test-performance-m4-recent` — **physical device, see above** 
docs/agent-notes/testing.md Modified +6 / -2
diff --git a/docs/agent-notes/testing.md b/docs/agent-notes/testing.mdindex 885ee095..85e28237 100644--- a/docs/agent-notes/testing.md+++ b/docs/agent-notes/testing.md@@ -484,10 +484,14 @@ the test count is **44** — and `update-schedule` added one arm, `todayPublicat suites**, measured over three runs at 1,175–1,211 s (`specs/update-schedule/verification-run.md` §5) — and `launch-to-today` added one more, `launchReads` (Req 1.3, two reported-only arms), and no suite, so the-current shape is **46 tests in 7 suites**, measured on a loaded host at 1,239 s,+target was **46 tests in 7 suites**, measured on a loaded host at 1,239 s, 1,174 s and 1,272.6 s (`specs/launch-to-today/verification-run.md` §1, §2 and §4.3 — the first and last `EXIT=0` with nine known issues, the middle one-`EXIT=2` on the documented `backup-export-thumbnails` under-peak). Measured on their own, filtered, release, two runs+`EXIT=2` on the documented `backup-export-thumbnails` under-peak) — and+`empty-library` added one test in one suite and `to-read-capture-match` three+tests in one suite, so the current shape is **50 tests in 9 suites**, measured+once on a loaded host at 1,214.4 s, `EXIT=0` with nine known issues+(`specs/to-read-capture-match/verification-run.md` §2). Measured on their own, filtered, release, two runs (the second on a busier host, which is what the duration spread is): `thumbnail-bytes-read` **0.055 s / 0.169 s / 0.091 s** median for fifty on-demand reads (1.1–3.4 ms each, against a 3 s class ceiling);
specs/OVERVIEW.md Modified +13 / -0
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex ed8d6fff..5202f767 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -53,6 +53,7 @@ | [Remove Article Mode](#remove-article-mode) | 2026-09-21 | Done — `make test` carries UI failures `main` owns, so Req 7.1 is not met as written (Q34) | Full spec (T-2336). Removes articles mode: the one-way Site state, its UI and repository operations, `SiteMode.articles` with every arm over it, and the `article` default work type. Schema V16 drops `Site.junkSuffixRule`, the one column only the mode used, and the archive moves to 15/16; 14/15 backups stop importing. No conversion is built, because no articles Site exists (Decision 1, Q10). Three commits: remove the mode, schema V16, archive and documents. | | [To Read](#to-read) | 2026-09-21 | Done | Full spec (T-2354). A fifth reading status, `toRead`, which the New Work form gives every work it creates and the reader can set in edit mode. A capture or a Move To into a to-read work makes it `reading` in the same commit; nothing else promotes. To-read works stay off Today's plan. No schema, marker or archive generation change. The share-sheet path is deferred to T-2363. | | [New Work URL Field](#new-work-url-field) | 2026-09-22 | Done | Smolspec (T-2365). The New Work form's site field accepts a bare hostname or an HTTP(S) URL with the scheme optional; a URL reduces to the host capture derives and is stored as that site's Work URL after the validator's on-host check. The field is relabelled with the URL keyboard, and `LibraryRepositoryError` becomes `LocalizedError` so every form shows a readable message. No schema change. The confirm-same-story dedup prompt is T-2366. |+| [To-Read Capture Match](#to-read-capture-match) | 2026-09-23 | Done | Full spec (T-2366). Pairs a to-read work with another work on a shared site whose Work URL or normalised title matches, derived in Today's publication, and asks the reader on a card sheet from the duplicate review surfaces. Confirming opens the merge preview with a `.toReadMatch` request that keeps the to-read UUID and takes the captured work's titles and statuses; declining records every listed pair as a synced `WorkDistinctPair`. No schema change. |  --- @@ -877,3 +878,15 @@ Smolspec (T-2365). The New Work form's site field accepts a bare hostname or an - [tasks.md](new-work-url-field/tasks.md) - [decision_log.md](new-work-url-field/decision_log.md) - [implementation.md](new-work-url-field/implementation.md)++## To-Read Capture Match++**Created:** 2026-09-23 · **Status:** Done — all sixteen tasks implemented. Q1–Q52 and Decisions 1–2 in the log.++Full spec (T-2366). Finds pairs of a to-read work and another work on a shared site whose Work URL (read through the site's URL rule) or normalised title says they are the same story, derived in Today's publication as a second kind of item on the duplicate workload, never in the scan or the reconcile pass. The reader answers on a card sheet reached from the Today banner and the Works row: a to-read choice opens the merge preview with a `.toReadMatch` request, in which the survivor keeps the to-read work's UUID and takes the captured work's titles and statuses, keeping a work status, verdict or release days the reader had edited and recording the typed title in the audit block; "None of these" records every listed pair as a synced `WorkDistinctPair`. No schema, marker or archive change.++- [requirements.md](to-read-capture-match/requirements.md)+- [design.md](to-read-capture-match/design.md)+- [tasks.md](to-read-capture-match/tasks.md)+- [decision_log.md](to-read-capture-match/decision_log.md)+- [verification-run.md](to-read-capture-match/verification-run.md)
specs/ipad-and-mac-layouts/verification-run.md Modified +1 / -0
diff --git a/specs/ipad-and-mac-layouts/verification-run.md b/specs/ipad-and-mac-layouts/verification-run.mdindex 7e3d6553..3a984898 100644--- a/specs/ipad-and-mac-layouts/verification-run.md+++ b/specs/ipad-and-mac-layouts/verification-run.md@@ -939,6 +939,7 @@ should have happened. | B12 | 7.1 | Close the window, then click the Dock icon | The one existing window comes forward; no second main window is ever created | | | B13 | 7.2 | Select a tab and a row, quit, relaunch | The tab and the row come back | | | B14 | 4.1, Q19/Q51 | A build whose App Group is not provisioned | The `.unavailable` screen names the reason and offers **no** Retry (a retry provably cannot succeed); every other failure keeps its Retry | |+| B15 | `to-read-capture-match` 3.6, Q30 | `Development` only. With a captured work paired with a work in To Read (a to-read work titled *The Wandering Inn*, then a captured chapter of *The Wandering Inn (Volume 1)* on the same site), open it from Today's duplicate banner → **Elsewhere** row, and again from the Works row's **To Read?** pill. Choose the to-read work, cancel the preview, then choose it again and confirm; on a second pair, choose **None of these** | The sheet opens at a readable size over the wide window, with the question, the captured title, site and chapter count, one button per to-read work (a blocked one disabled with its reason under it) and **None of these**, all reachable with Tab and VoiceOver. A choice replaces the card with the merge preview **inside the same sheet** — no second sheet, no nested toolbar — and its cancel brings the card back. Confirming closes the sheet and shows the survivor, carrying the captured title, in the detail column. None of these closes the sheet and the pill goes | |  ### C. Mac — commands and menus 
specs/to-read-capture-match/decision_log.md Added +130 / -0
diff --git a/specs/to-read-capture-match/decision_log.md b/specs/to-read-capture-match/decision_log.mdnew file mode 100644index 00000000..d7da2567--- /dev/null+++ b/specs/to-read-capture-match/decision_log.md@@ -0,0 +1,130 @@+# Decision Log: To-Read Capture Match++## Quick Decisions++| ID | Date | Decision | Rationale |+|----|------|----------|-----------|+| Q1 | 2026-09-23 | Full spec, not a smolspec (T-2366) | Owner-approved. The match rule is a user-owned behaviour choice, the decline memory touches a synced contract, and placement (capture commit vs review surface) is contested |+| Q2 | 2026-09-23 | The spec is named `to-read-capture-match` | Owner's pick |+| Q3 | 2026-09-23 | Match on strong keys only: a Work URL arm or a title arm, never "any to-read work on the site" | Owner's pick. Asking about every to-read work with no entries would prompt on most captures from a site with a backlog |+| Q4 | 2026-09-23 | The title arm is normalised equality, or a whole-word prefix whose shorter side has at least three words or twelve scalars, a leading article not counted; fixed by the example table in Req 2.4 | Owner's pick at the requirements review. The first floor (two words, eight characters) failed its own example and let "the last" pair with every "The Last …". Prefix rather than containment anywhere keeps "Book 1: Ascend" style false positives out. Accepted cost: short single-word titles such as "Worm" never pair by prefix |+| Q5 | 2026-09-23 | The question surfaces through the duplicate review surfaces (Today banner, duplicates-only filter, Works row), not at capture | Owner's pick. It covers share-extension and drained captures without a second path, and the capture path may not await anything. Candidates are derived where Today and the Works list build their review workload, so they appear at the next publication; T-2329 (no reconcile after a capture) does not delay them |+| Q6 | 2026-09-23 | A declined pair is recorded as a synced `WorkDistinctPair` | Owner's pick. The table is already synced, backed up, deduped and re-pointed on merge, so no device re-asks and no schema bump is needed. Its meaning widens from cross-site title edges to any pair the reader has said are different, and a decline therefore also suppresses a later cross-site title edge between the same two works (Req 5.3, Q19) |+| Q7 | 2026-09-23 | The captured side is any work that is not to-read, including pairs that exist when the feature ships | Owner's pick. Restricting to recently captured works would need a creation-order rule and miss the duplicates already in libraries |+| Q8 | 2026-09-23 | One review item per captured work, listing every to-read work it pairs with; the reader picks one or "None of these", which declines every listed pair | Owner's pick. One card per pair would leave stale cards after confirming one of them |+| Q9 | 2026-09-23 | On confirm the to-read work survives, keeps its UUID, and takes the captured work's display title, parsed title and title provenance; the typed title is kept in an audit block (Q18) | Owner's pick, re-confirmed at the requirements review. The merge record otherwise keeps only the source's title, so the typed one would vanish without trace. Provenance moves with the title so re-parse and the bare check treat the survivor as captured |+| Q10 | 2026-09-23 | On confirm reading status comes from the captured work; work status, verdict and release days come from it unless the to-read work's value differs from what the New Work form gave it | Owner's pick at the requirements review. The existing merge keeps the target's values, which for a to-read work are mostly the form's defaults; taking reading status alone would leave "finished, ongoing, no verdict". A value the reader set on the to-read work by hand is still respected |+| Q11 | 2026-09-23 | The Work URL arm runs the site's URL rule on the to-read work's Work URL and compares the located work with the captured work's URL identity | Owner's pick at the requirements review. Captures never store a Work URL, so comparing two stored Work URLs almost never fires; T-2365's pasted URL is only useful when the rule reads it. A rule that needs a sequence selector cannot read a landing URL, so the arm simply does not hold there (Req 2.3) |+| Q12 | 2026-09-23 | Confirming shows the existing merge preview before committing | Requirements review: the merge discards the typed title, cover or Work URL choices, and the reader must see what goes |+| Q13 | 2026-09-23 | A pair is not offered while either work is in an open Work duplicate set or a torn group; a quarantine or series conflict is shown on the item instead of offered | Requirements review. Merging across an open set gives order-dependent outcomes, and offering a choice the merge is certain to refuse wastes a tap |+| Q14 | 2026-09-23 | The cost requirement targets the path Today waits on, not the duplicate scan | Requirements review. Candidates are derived where Today builds its workload, not in the scan. How it is measured is Q20 |+| Q15 | 2026-09-23 | Normalisation is NFKD, nonspacing marks removed, locale-free default case folding, P and S categories replaced by spaces, whitespace collapsed | Requirements review. Req 1.1 needs the same pairs on every device, which a locale-dependent fold (the Turkish dotted i) would break. Order amended by Q27 |+| Q16 | 2026-09-23 | The Work URL arm applies the site's rule to the Work URL exactly as to a captured URL; no work-only extraction mode | Second requirements review. A rule needing a sequence selector cannot read a landing URL and the arm then does not hold; adding a work-only mode would be a second parser for one arm |+| Q17 | 2026-09-23 | The confirm overrides (Req 4.3, 4.4) are applied on top of the Merge action's outcome, outside the fold it shares with duplicate resolution | Second requirements review. The fold keeps the target's title and statuses and is shared with the resolution sheet (duplicate-reconciliation Q51); changing it would change that sheet too. The cover already follows this pattern (Q56 there) |+| Q18 | 2026-09-23 | The confirm keeps the Merge action's audit block for the captured work, records as discarded only values that lose under Req 4.3, and adds one line with the to-read work's typed title | Owner's pick at the second requirements review. Replacing the block would drop the captured work's notes and discarded Work URLs, and a block headed by the typed title would misattribute those notes |+| Q19 | 2026-09-23 | A decline only suppresses a future cross-site title edge; it removes none at the time | Second requirements review. A candidate pair always shares a site, and a cross-site edge needs disjoint site sets, so no such edge exists when the reader declines |+| Q20 | 2026-09-23 | Cost is a dedicated arm with its own 50-work to-read fixture extension and a 100 ms budget; `todayPublication` keeps its 2 s budget and its input | Owner-accepted at the second requirements review. Adding to-read works to the shared M4 fixture would move every band, and `todayPublication`'s 1.1 s of headroom could not catch a derivation regression. 100 ms is an estimate to be checked at the first measurement |+| Q21 | 2026-09-23 | Title normalisation uses full case folding and accepts disagreement between devices on different Unicode versions for newly assigned scalars | Second requirements review. Titles using scalars assigned after either device's Unicode tables are rare, and the owner updates every device |+| Q22 | 2026-09-23 | Confirm is allowed when the merge leaves the survivor without a URL identity on the site; Req 4.5 promises later captures land on it only when it has one | Owner's pick at the second requirements review. Only a to-read work that already holds entries with a different identity reaches this case; refusing would push the reader to the same merge by hand, and changing capture matching is a Non-Goal |+| Q23 | 2026-09-23 | The item opens a card sheet; a to-read choice opens the existing merge preview with that target preset (in place of the card, Q30) | Owner's pick at design. One layout whether there is one choice or several; the preview is reused rather than duplicated |+| Q24 | 2026-09-23 | In Today's duplicates-only view the item is an Elsewhere row reading "May belong to a story in To Read" | Owner's pick at design. No new section to lay out |+| Q25 | 2026-09-23 | Decline refreshes snapshots but schedules no reconcile | A distinct pair between two works that share a site changes no duplicate set (Req 5.3), so a pass would be a no-op |+| Q26 | 2026-09-23 | The typed-title line reads `Title before merge: <title>` and the discarded field is labelled "Your title" | Matches the merge preview's plain labels; the audit line has to name what it records without the card's context |+| Q27 | 2026-09-23 | Normalisation folds case before removing nonspacing marks, with a second NFKD between them | Design self-review. Folding `İ` yields `i` plus U+0307, so removing marks first left a mark that a second pass would remove: normalisation was not idempotent. Amends the Definitions and Q15; itself amended by Q44 |+| Q28 | 2026-09-23 | The Work URL arm compares against captured identities in state `.rule` or `.legacyUnverified` | Design self-review. Req 2.3 names the captured work's URL identity without restricting its state; a legacy identity is still the value capture reuses on |+| Q29 | 2026-09-23 | The Today banner adds `toReadMatches.count` itself; `DuplicateWorkload.reviewCount`, `isEmpty` and `allItems` keep describing duplicate sets | Design self-review. Settings and Check Library read the same workload and have no row for a candidate, so folding the count into `reviewCount` would make them report work they cannot show |+| Q30 | 2026-09-23 | The card sheet replaces its content with the merge view rather than pushing it; `WorkMergeModel` takes a preset target and a `start()` that skips the destination picker; cancel returns to the card and a commit closes the sheet and shows the survivor | Design review. `WorkMergeView` owns a `NavigationStack` and loads destinations in its `.task`, so a push nested two stacks and landed on the picker |+| Q31 | 2026-09-23 | The confirm copies raw status, verdict and release-day columns verbatim from the captured carrier row, and decides "pristine" on the to-read carrier's raw columns | Design review. Writing through the tolerated enums would turn an unknown raw value into a default on write; reads tolerant, writes not |+| Q32 | 2026-09-23 | The commit re-check fetches no `Entry` rows and skips the blocked check; it shares `pairs` with the publication | Design review. The Entry fetch is the dominant cost of Today's reads and only feeds the displayed count; quarantine and series are already refused by the commit and the planner |+| Q33 | 2026-09-23 | Two extra performance arms: `to-read-match-publication` (Today over the to-read layer, 2 s) and `to-read-match-recheck` (reported) | Design review. Req 6.2 was otherwise argued rather than measured, and the re-check runs under the exclusive lock |+| Q34 | 2026-09-23 | The merge basis carries the carrier's raw status, provenance and release-day columns, and the outcome carries the raw values the survivor will get; the commit writes those projected values | Design peer review. The planner could not tell an unknown raw status from its default, and re-reading the source row at commit would write a `lastParsedTitle` from a different row than the preview showed for a split group. Supersedes the "copied from the source carrier row" wording of Q31 |+| Q35 | 2026-09-23 | An item whose choices are all blocked still counts in the Today banner | Owner's pick at design. "None of these" is still an action the reader can take |+| Q36 | 2026-09-23 | A decline follows its works through later merges and collapses, as distinct pairs already do, even where it then suppresses a pair the reader never saw | Owner's pick at design. Merging the captured work into another says both are the same story as the one declined against; dropping declines on merge would diverge from existing distinct-pair handling |+| Q37 | 2026-09-23 | The Today banner keeps its duplicates wording when the count includes to-read matches | Owner's pick at design. A to-read match is a likely duplicate work |+| Q38 | 2026-09-23 | Req 3.5's "open Work duplicate set" is a Work set of two or more works, or any Work set that publishes a review item (classification other than `.silentlyResolvable`, the test `DuplicateWorkload` publishes on); a silently resolvable one-member set holds nothing back, and a lone split group is otherwise excluded only when torn | Implementation (task 4), amended at the design-critic review. `DuplicateScan.workSets` returns a lone split group as a one-member set, and a converged one stays a set for good because its rows are never deleted, so "a member of any set" would hide its pairs permanently. Merging a whole split group is not order-dependent and the merge already carries every row. The amendment: a one-member set can still be `.divergent` without being torn (a split group with a membership-less row), and then the reader is already being asked about that work on the same surfaces |+| Q39 | 2026-09-23 | `ToReadMatcher.swift` is on the `MultiSiteReadPathTests` allowlist for reading `Work.siteMemberships`, on the precondition that every caller builds the Work sets over the same rows before calling `pairs` | Implementation review. `DuplicateScan.WorkKeyRow` reads `membershipValues` per Work while the sets are built, so the relationship is already faulted and a membership fetch would read a table the caller already holds. A new caller that skips the sets would pay a fault per Work |+| Q40 | 2026-09-23 | The item's entry count is taken through `entry.work?.id` on the fetched Entry rows, counting distinct entry UUIDs | Implementation review. `Entry` has no `workID` column (the design said it had); the to-one is already faulted by the publication's Entry sets, and `work.entries` is still never read. Supersedes the design's "`workID` column" wording |+| Q41 | 2026-09-23 | The title arms use one first-word bucket per hostname, checked with `titlesMatch`, in place of the design's separate equality index and prefix scan | Implementation review. Equal non-empty titles share their first word and a whole-word prefix shares it too, so one bucket finds every pair either index would; one code path and one test surface. Output is identical |+| Q42 | 2026-09-23 | A `.toReadMatch` preview lists `.sourceReadingStatus` as retained, and a losing source value is listed as discarded only where it would have contributed under the fold: work status not the default (`ongoing`), verdict not blank, release days not empty, and differing from the winner | Implementation, and the design-critic review for work status. The survivor always takes the captured reading status, so it is a retained field. The fold's rule is that a default contributes nothing; verdict and release days already followed it and work status now does too, so an `ongoing` source is not reported lost to an edited to-read work |+| Q43 | 2026-09-23 | Neither `WorkMergePlanner.project` nor `LibraryRepository.projectMerge` defaults `request:`; a `LibraryProviding` protocol extension supplies the `.merge` overload for the app's existing callers | Design-critic review. A default on the planner let a caller silently project a plain merge where a `.toReadMatch` was meant, the mistake the commit's re-projection must never make. Protocol requirements cannot carry a default, so the overload is the one convenience. Corrects the design, whose "Merge request" section said `projectMerge` defaulted the parameter while its integration table said it did not |+| Q44 | 2026-09-23 | Normalisation also removes every format character (general category Cf) where it removes nonspacing marks, and words are split on the U+0020 scalar, not on `Character` | Design-critic review. Zero-width spaces and joiners, direction marks, soft hyphens and byte order marks are invisible in a title and sit inside words, so they are removed rather than turned into spaces; a trailing U+200E made "Mother of Learning" unequal to itself. A space followed by a spacing mark is one grapheme, so a `Character` split did not separate those words. Amends the Definitions' order after Q27 |+| Q45 | 2026-09-23 | Today's publication passes the repository's `quarantined` latch to the matcher, not `diagnostics.quarantineMap()` | Design-critic review. The merge commit refuses through `quarantineReason(hostname:)`, which reads that latch; reading the same one means a choice shows as blocked exactly when the commit would refuse it. `isCandidate` reads no quarantine at all, because the commit's refusal runs before it |+| Q46 | 2026-09-23 | `seedM4ToReadMatchLayer` also seeds the 10 captured works its prefix to-read works pair with, beside the design's 50 to-read works | Task 16. Every base work is titled `Story <n>`, two words and at most nine scalars, so it is never long enough to be the shorter side of a Req 2.4 prefix match and nothing is left to be shorter than it; the prefix arm needs a longer captured title. All 60 titles start with `story`, so every to-read work scans the whole 1,010-work first-word bucket (Q41's worst case on this fixture) |+| Q47 | 2026-09-23 | A committed confirm shows the survivor on the stack that opened the card (Today for the Elsewhere row, Works for the pill) through `showWork(on:)`, which resets that stack to `[.work(survivor)]`; the other stack is not cleaned | Design-critic review. The card is a sheet over either tab, so the survivor belongs where the reader asked. `replaceWork`, which the ordinary Merge uses, swaps only the top work and assumes the reader was on the merged work's page, which a card opened from a list row is not. A route to the captured work on the other stack is left as it is: the ordinary Merge has the same gap, and closing it is not this feature's |+| Q48 | 2026-09-23 | `WorkMergeModel.targetTitle`, the to-read work's typed title the preview lists as discarded, is read from the contract's basis (`basis.target.snapshot.displayTitle`) | Design-critic review. The outcome carries the title the survivor will have, not the one it loses, and the basis is the observation the preview was projected from, so the discarded value is the one the commit will discard. A separate `work(id:)` read could disagree with it |+| Q49 | 2026-09-23 | The merge view's `onCancel` covers both its ways out, the toolbar X and the error view's Dismiss; both are disabled and `returnToCard()` is a no-op while the merge is submitting; returning from an error state (a refusal or `.invalidated`) awaits a refresh of diagnoses and snapshots before the card reloads; and the to-read host keeps the merge view from dismissing on its own commit, through a separate `dismissesOnCommit: false` rather than by supplying `onCancel` (amended by Q55) | Design-critic review (M1, m2, m3). Leaving mid-commit dropped the merge model and with it the survivor the host routes to. After a refusal the last publication still showed the card as it was, so it offered the pair that had just been refused. The to-read host closes the sheet when it routes to the survivor, and the merge view's own `dismiss()` raced it. The ordinary Merge host passes no `onCancel` and keeps dismissing on commit |+| Q50 | 2026-09-23 | The fixture kind's raw value is `"to-read-match"`, although its siblings are camelCase, and the UI-test bundle repeats the fixture's fixed UUIDs rather than importing them | Design-critic review, decision only; nothing is renamed. The raw value is what makes the launch argument read as the spec's scenario name, `seeded-tolerated-to-read-match`, and renaming it now would move a name three UI suites launch by. The UI-test bundle spells the three UUIDs once in `ToReadMatchScenario` for those three suites. `DuplicatePublicationTests.seededToReadScenarioPublishesItsItem` pins the Core side, the item the seeder publishes and its choices against `ToReadMatchFixture`'s constants, so a seeder drift fails there rather than as a UI timeout. It does not compare the two spellings: a changed Core UUID still needs the UI copy changed by hand |+| Q51 | 2026-09-23 | Accessibility labels: the card's header is one combined element (question, captured title, site and chapter count); a choice reads "Same story as <title>", or "<title>. <reason>" when blocked, with the visible reason line hidden; the decline reads "None of these is the same story" | Design-critic review. The combined header is read as the question it is, not as three fragments. "Same story as" says what the tap answers, where the bare title would sound like navigation. A blocked choice carries its reason in its own label because VoiceOver users meet a disabled button, not the caption under it. The decline's label completes the sentence the visible "None of these" leaves to the question above it |+| Q52 | 2026-09-23 | The derivation arm asserts Req 6.1's 100 ms budget and nothing below it; the first measurement, 0.0196–0.0198 s median over two filtered runs on a loaded host, is recorded against Q20's estimate, and the 50 ms regression ceiling is removed | Design-critic review (M2). The measurement puts Q20's estimate at about five times the cost. A sub-budget ceiling exists to catch a drift the fixture could hide, but this fixture already runs Q41's single-bucket worst case: every title starts with `story` (Q46), so every to-read work scans the whole 1,010-work bucket, and a matcher that stopped bucketing would do the same work and not fire it. With nothing a ceiling could catch that the budget does not, the budget is the assertion |+| Q53 | 2026-09-24 | A stale `.toReadMatch` confirm runs `ToReadMatcher.isCandidate` before returning `.refreshed`, and returns `.invalidated` with Req 4.6's reason when the pair no longer matches; a stale pair that still matches refreshes as before, carrying `.toReadMatch` | Pre-push review. Req 4.6 re-evaluates the rule "at the moment of confirming", and the refresh-first order answered it only at the second confirm, after showing a preview of a merge that could not land. The title-edit test now expects `.invalidated` at the first confirm |+| Q54 | 2026-09-24 | `isCandidate` reads the distinct pairs first and returns false for a declined pair before fetching Works or Sites; it builds the Work sets over every row but passes only the pair's rows and their groups to `pairs` | Pre-push review. Req 3.5's exclusion needs every open set, so the sets stay whole; whether this pair matches depends on nothing but its two works, so indexing the rest of the library under the exclusive lock was wasted. The pair's result is unchanged |+| Q55 | 2026-09-24 | `WorkMergeView` takes `dismissesOnCommit: Bool = true`, separate from `onCancel`; the to-read sheet passes `false` | Pre-push review. Q49 tied "does not dismiss on commit" to "supplies `onCancel`", so a future host wanting a custom cancel would silently lose its dismissal. Two parameters say two things. The ordinary host passes neither and is unchanged |+| Q56 | 2026-09-24 | `AppLibraryModel.LibraryNotOpen` stays beside `LibraryRepositoryError.libraryUnavailable`, a known duplicate | Pre-push review, decision only. Both mean "no open library", but `ToReadMatchModelTests` pins the type the decline throws, and the Core case carries an operation and a reason the app side has neither of. Folding them is a cleanup for when a second app-side caller needs one |++## Decision 1: Candidates Are a Sibling Item Type on DuplicateWorkload++**Date**: 2026-09-23+**Status**: accepted++### Context++The review surfaces read `DuplicateWorkload`, whose items are `DuplicateReviewItem`s keyed by a `DuplicateSetKey` and looked up by record type and member ID. A candidate is a star (one captured work, several to-read works), not a set, and must never reach the reconciler (Req 1.3).++### Decision++Add `toReadMatches: [ToReadMatchItem]` beside `reviewItems`, looked up by captured work ID, counted in the Today banner but not in `reviewCount` (Q29), and derived by a pure `ToReadMatcher` called from `todayPresentation`.++### Rationale++Every `DuplicateReviewItem` consumer assumes a set: survivor choice, `routes(for:)`'s one-set-per-record assumption, dismissal, and the resolution sheet. A separate list keeps those untouched and makes the parity audit short. Deriving in `todayPresentation` reuses rows it already fetched and cannot leak into `DuplicateScanResult`.++### Alternatives Considered++- **A new `DuplicateScan.RecordType` and set kind**: candidates as sets in `DuplicateScan.run` - Rejected: the scan's result feeds the reconciler and its gate counters, which Req 1.3 forbids, and a star does not fit a set key.+- **A new `DuplicateResolutionRoute` case on `DuplicateReviewItem`**: reuse the item type - Rejected: `key` and `memberIDs` would carry a pair list the set-based consumers misread; every consumer would need a guard.++### Consequences++**Positive:**+- No change to the scan, the reconciler or the existing review items.+- Candidates are recomputed at every publication, so they cannot go stale beyond one publication.++**Negative:**+- Two lookups on the Works row and two row sources in Today's Elsewhere section.+- Candidates are only as fresh as Today's publication; a surface that does not read that workload never shows them.++---++## Decision 2: Confirm Is a Merge Request, Not a Separate Commit++**Date**: 2026-09-23+**Status**: accepted++### Context++Req 4.2 wants the Merge action's outcome for every field it does not name, and Req 4.3–4.4 override titles, statuses and the audit block. The fold that computes a merge's fields is shared with duplicate resolution (Q17).++### Decision++Add `WorkMergeRequest.toReadMatch`. The planner applies the overrides after the fold, as the cover block does, and the commit writes the overridden fields and re-checks the candidate rule when that request is present.++### Rationale++The merge commit already handles entries, memberships, identity, credits, characters, places, links, series, distinct-pair re-pointing, refusals and stale-preview detection. A request case inherits all of it, and the preview and the commit compare one outcome, so a stale preview still refreshes.++### Alternatives Considered++- **A separate `commitToReadMatch` repository call**: merge, then write the overrides - Rejected: two saves, so a failure between them leaves a merged work with the wrong title and status, and the preview would not show the final values.+- **Change `WorkVariantUnion.fold`**: pass the overrides into the shared fold - Rejected: the fold is shared with the duplicate resolution sheet, which would change it too (Q17).++### Consequences++**Positive:**+- One commit, one preview, one set of refusals.+- The ordinary Merge action is unchanged (Non-Goal).++**Negative:**+- `WorkMergePlanner.project` and the commit's target loop grow a request branch.+- `projectMerge` and `WorkMergeModel` gain a `request` parameter.++---
specs/to-read-capture-match/design.md Added +179 / -0
diff --git a/specs/to-read-capture-match/design.md b/specs/to-read-capture-match/design.mdnew file mode 100644index 00000000..90078195--- /dev/null+++ b/specs/to-read-capture-match/design.md@@ -0,0 +1,179 @@+# Design: To-Read Capture Match++## Overview++A pure matcher derives candidate pairs inside Today's publication, from rows that publication already fetches, and `DuplicateWorkload` carries them as a second kind of review item (Decision 1). The item opens a card sheet; a to-read choice opens the existing merge preview with a new merge request that applies Req 4.3–4.4 on top of the ordinary merge outcome (Decision 2), and "None of these" records every listed pair as a `WorkDistinctPair` in one commit.++## Architecture++```mermaid+flowchart LR+  TP[todayPresentation<br/>shared lock] -->|works, sites, entries,<br/>groups, distinctPairs,<br/>workSets, quarantined latch| M[ToReadMatcher.candidates]+  M --> W[DuplicateWorkload.toReadMatches]+  W --> T[Today banner + Elsewhere row]+  W --> WR[Works row pill]+  T & WR --> S[ToReadMatchSheet]+  S -->|to-read choice| MV[WorkMergeView<br/>request .toReadMatch]+  S -->|None of these| D[recordDistinctPairs]+  MV --> C[commitMerge<br/>re-checks candidate rule]+```++Nothing is added to `DuplicateScan.run`, `DuplicateScanResult`, the reconcile pass, the settling ledger or the gate counters (Req 1.3). The matcher's callers are `todayPresentation` and the commit re-check; the Works list already reuses Today's workload (`AppScreens.swift:183`), so one publication serves both surfaces (Req 1.2). Declines are the only write that reaches the scan, through the existing `distinctPairKeys` read.++A confirmed pair stops being offered at the next publication because the survivor takes the captured work's reading status, which is never `toRead`, so it is no longer a to-read work; this is what removes it from other items (Req 3.3) and what makes a confirm final.++### Integration points++| Site | Change |+|---|---|+| `LibraryRepository+TodayPresentation.swift`, after `workGroups` is built (:80) | Call `ToReadMatcher.candidates(...)` with the fetched `works`, `sites`, `entryRows`, `workGroups`, `distinctPairs`, `workSets` and the repository's `quarantined` latch, the one the commit's `quarantineReason(hostname:)` reads (Q45). The `DuplicateWorkload` construction (:55) and the `duplicateRoutes` read of it (:58) move below that call |+| `DuplicateWorkload.swift:97` | New stored `toReadMatches: [ToReadMatchItem]`, an `init` parameter defaulted to `[]` (so `.empty` and existing test call sites are unchanged), and `toReadMatch(for capturedWorkID:)`. `reviewCount`, `isEmpty` and `allItems` are unchanged: they describe duplicate sets |+| `AppLibraryModel.duplicateBannerCount` (:1850) | `reviewCount + toReadMatches.count + pendingConflicts.count` |+| `WorkMergeAuditFormatter.block` (`WorkMergePlanner.swift:18`) | New defaulted parameter `titleBeforeMerge: String? = nil`, written as the line `Title before merge: <escaped title>` directly after the header |+| `WorkMergePlanner.project(_:)` (:107) | Becomes `project(_ basis:, request: WorkMergeRequest)`; after the cover block (:134-157), when the request is `.toReadMatch`, apply the overrides below and rebuild `retainedFields`, `discardedFields`, `auditBlock` and `genericNotes` |+| `LibraryRepository+WorkMerge.swift` `projectMerge` (:322, :335) and commit (:368, :380) | `projectMerge` gains `request:` and passes it to the planner and into the contract; the commit re-projects with `contract.request` at :368 and builds its `.refreshed` contract with it at :380, so a `.toReadMatch` preview is compared with a `.toReadMatch` re-projection and a refresh never degrades to a plain merge |+| `LibraryProviding.swift:518`, `MockLibraryProvider.swift:901` | The protocol requirement gains `request:` with no default (protocol requirements cannot carry one); a protocol extension supplies the `.merge` convenience overload for existing callers |+| `LibraryRepository+WorkMerge.swift` commit, after the torn and quarantine refusals (:421-443) | When the request is `.toReadMatch`, run `ToReadMatcher.isCandidate` under the lock and return `.invalidated("These works no longer look like the same story.")` when it is false (Req 4.6). The same check also runs in the stale branch, before `.refreshed` is returned: a `.toReadMatch` confirm whose basis is stale and whose pair no longer matches is invalidated at that first confirm rather than refreshed into a preview the next confirm would refuse (Q53). A stale pair that still matches refreshes as before, carrying `.toReadMatch` |+| `WorkMergeWorkBasis` (`ProjectionContract.swift:538`), built in `buildMergeBasis` | Gains the carrier row's raw columns: `workStatusRaw`, `readingStatusRaw`, `titleProvenanceRaw` and `releaseDaysRaw` (the stored token array, undecoded). The planner reads them, and the commit's basis comparison then covers a raw-only change behind the preview |+| `WorkMergeOutcome` (`ProjectionContract.swift:840`) | Gains `rawOverrides: WorkMergeRawOverrides?`, set only for `.toReadMatch`: the raw `displayTitle`, `lastParsedTitle`, `titleProvenanceRaw`, `readingStatusRaw`, `workStatusRaw`, `verdict` and `releaseDaysRaw` the survivor will carry, taken from the source basis as the snapshot projects each field (titles and statuses from the carrier, `lastParsedTitle` from the representative) |+| `LibraryRepository+WorkMerge.swift` target-row loop (:505-524) | When `rawOverrides` is present, write each of its values to every target row, only where the row differs. The commit writes the projected values, never re-reads the source row, so it writes exactly what the preview showed; raw columns are copied, never re-encoded from a tolerated enum, so an unknown raw value survives (CLAUDE.md: reads tolerant, writes not) |+| `LibraryRepository+DuplicateResolution.swift:29` | New `recordDistinctPairs(_ pairs: [WorkPairKey])`; `recordDistinctPair` becomes a one-pair call to it |+| `TodayView.swift` `RecentDuplicatePlan` (:1072-1076, :1225-1290) | One `Elsewhere` row per `ToReadMatchItem`, text "May belong to a story in To Read", new route case `.toReadMatch(capturedWorkID)`, opened through a new `onResolveToReadMatch: ((UUID) -> Void)?` beside `onResolveDuplicate` (:64, :862) |+| `WorksView.swift:693-719` | A work's row shows a pill styled as the resolve pill, labelled "To Read?", accessibility label "Check whether <title> belongs to a story in To Read", identifier `work-to-read-match-pill`, when `toReadMatch(for: work.id)` is non-nil; it calls a new `onResolveToReadMatch(work.id)` |+| `AppScreens.swift` (:99, :183, :214) | Wires both `onResolveToReadMatch` closures to `AppNavigation` |+| `AppNavigation.swift` (beside :293, :297), `ContentView.presentedContent` (:602) | New presented state `presentingToReadMatch: PresentedToReadMatch?` shown beside `resolvingDuplicateSet`, so compact and wide layouts share the sheet |++### Parity audit: consumers of `DuplicateWorkload`++| Consumer | Needs equivalent | Why |+|---|---|---|+| `AppLibraryModel.duplicateBannerCount` | yes | Req 3.1, the banner counts each item once |+| Today `RecentDuplicatePlan` Elsewhere rows | yes | Req 3.1, duplicates-only filter |+| Works row resolve pill (`WorksView.swift:707`) | yes | Req 3.1 |+| `reviewCount`, `isEmpty`, `allItems` | no | Describe duplicate sets; the banner adds the new count itself so the consumers below stay correct |+| Settings sync summary (`SettingsSyncModel.swift:119`) | no | Reports repair state; a question to the reader is not damage |+| Check Library headline and list (`MaintenanceViewModels.swift:208-215`, :542) | no | Lists duplicate sets and diagnoses; it has no row for a candidate, so it must not count one |+| `item(for:type:)`, `route(for:type:)`, `routes(for:)` | no | Keyed by `DuplicateSetKey`; candidates are looked up by captured work ID |+| `canonicalWorkIDs` in Today and `works()` | no | Picks a set's survivor; candidates are not sets |+| `dismissable(for:type:)` and the Works dismiss pills | no | For cross-site title sets; "None of these" is the decline here |+| `AppNavigation.route(toResolve:)`, `resolveRoute(for:type:workload:)` | no | Take a `DuplicateSetKey`; the new route is separate |+| Work detail duplicate row | no | Req 3.1 names Today and the Works row only |++## Components and Interfaces++### `ToReadMatcher` (Core, new file `ToReadMatcher.swift`)++```swift+enum ToReadMatcher {+    static func normalise(_ title: String) -> NormalisedTitle+    static func titlesMatch(_ a: NormalisedTitle, _ b: NormalisedTitle) -> Bool   // Req 2.2 title arms, 2.4+    static func pairs(works: [Work], sites: [Site], groups: [UUID: WorkGroup],+                      distinctPairs: Set<WorkPairKey>, workSets: [WorkDuplicateSet]) -> [MatchedPair]+    static func candidates(works: [Work], sites: [Site], entries: [Entry],+                           groups: [UUID: WorkGroup], distinctPairs: Set<WorkPairKey>,+                           workSets: [WorkDuplicateSet],+                           quarantine: [String: LibraryValidationError]) -> [ToReadMatchItem]+    static func isCandidate(capturedID: UUID, toReadID: UUID, context: ModelContext) throws -> Bool+}+struct MatchedPair: Hashable { let capturedID: UUID; let toReadID: UUID; let hostname: String }+struct NormalisedTitle: Hashable { let text: String; let words: [Substring]; let countedWords: Int; let countedLength: Int }+```++- **Determinism (Req 1.1):** pure over its inputs; reads no clock, no `PersistentIdentifier`, no device state. Items are sorted by captured work UUID and choices by to-read UUID.+- **Which values:** titles, reading status and series come from the group's carrier row (`WorkGroup.carrier`), as the snapshot does. Memberships are the union over the group's rows, one per hostname, picked as the merge planner picks a group's membership for a hostname, read through `Work.siteMemberships`, which the Work sets have already faulted (the file is on the `MultiSiteReadPathTests` allowlist, Q39). Hostnames are compared as stored; they are normalised on write. The site for a hostname is `SiteResolutionOrder.winnersByHostname(sites)[hostname]`.+- **Normalise:** `decomposedStringWithCompatibilityMapping`, `folding(options: .caseInsensitive, locale: nil)`, `decomposedStringWithCompatibilityMapping` again, drop every scalar whose `generalCategory` is `.nonspacingMark` or `.format` (Q44), map every scalar in a P* or S* category to a space, collapse whitespace runs using `M2Unicode.isWhitespace`, trim. Marks are dropped after folding, because folding `İ` produces `i` plus a combining mark (Q27). `words` splits `text` on the U+0020 scalar, not on `Character` (Q44). `countedWords` and `countedLength` skip a leading `the`, `a` or `an` word and its space; `text` and `words` keep it (Req 2.4).+- **Algorithm:** collect the offered to-read groups and their hostnames first, and return nothing when there are none, before any captured work is indexed. Then index only the captured works' memberships on those hostnames. For each such hostname:+  1. `[first word: [captured]]`, one bucket for both title arms, since equal titles and a whole-word prefix both share the first word (Q41).+  2. `[identity value: [captured]]` over memberships whose `urlIdentityState` is `.rule` or `.legacyUnverified`, compared as `ExactScalarString`.+  3. For each to-read work: check the captured titles in its first-word bucket with `titlesMatch`; apply the site's `currentURLRule` through `URLRuleApplicator.apply(_:to:)` to the membership's `workURLString` and look up the identity, skipping when there is no rule, `suppliesIdentity` is false, there is no Work URL, or `apply` throws (Req 2.3).+  Each title is normalised once per call.+- **Exclusions:** drop a pair in `distinctPairs` (Req 2.5), or where either work is a member of a set in `workSets` that has two or more members or publishes a review item (classification not `.silentlyResolvable`), or its group is torn (Req 3.5, Q38).+- **Blocked choices (Req 3.4):** `blocked: ToReadMatchBlock?` is `.quarantined(hostname)` for the lowest membership hostname of either group that the `quarantined` latch holds (Q45), through `LibraryRepository.quarantinedHostnames(of:in:)`, the helper the merge commit's refusal also calls; and `.seriesConflict` when both carriers have a series and the IDs differ, through `SeriesMembership.areInDifferentSeries`, the test `WorkMergePlanner.project` and the merge picker also apply. The card's wording for both comes from `WorkMergeModel.refusalMessage(for:)`, which the picker's rows use too. Blocked choices stay in the item so the reason shows; an item whose choices are all blocked is still published, because "None of these" stays available.+- **Entry count (Req 3.2):** counted as distinct entry UUIDs over the fetched entry rows by `entry.work?.id`, never through `work.entries`; `Entry` has no `workID` column (Q40).+- **`pairs` and `candidates`:** `pairs` applies the match rule and the exclusions and returns one `MatchedPair` per work pair, carrying the lowest shared hostname on which it matched, so a pair matching on two sites is one pair. `candidates` calls it, then adds entry counts, titles and blocked reasons to build the items; an item's `hostname` is the lowest among its pairs'.+- **`isCandidate`:** reads the distinct pairs first and returns false for a declined pair before anything else is fetched; otherwise fetches every `Work` and `Site` row (no `Entry` rows), computes `workSets` over every Work as `todayPresentation` does, and calls `pairs` with only the two works' rows and their groups, since no other work changes whether this pair matches (Q54), then checks that the pair is present. Sharing `pairs` with the publication means the two cannot disagree. It does not repeat the blocked check: the commit's quarantine refusal runs before it and the planner throws on a series conflict. It runs only on a confirm, under the exclusive lock; its cost is the Work fetch plus `workSets` plus `pairs`, measured by the `to-read-match-recheck` arm.++### `ToReadMatchItem` (Core, in `DuplicateWorkload.swift`)++```swift+public struct ToReadMatchItem: Sendable, Equatable, Identifiable {+    public let capturedWorkID: UUID          // id+    public let capturedTitle: String+    public let hostname: String              // lowest shared hostname on which a choice matched+    public let entryCount: Int+    public let choices: [Choice]+    public struct Choice: Sendable, Equatable { let toReadWorkID: UUID; let title: String; let blocked: ToReadMatchBlock? }+}+```++### Merge request `.toReadMatch`++`WorkMergeRequest` gains `.toReadMatch`, and `WorkMergeField` gains `targetManualTitle` (label "Your title", `recordedInNotes = true`) and `sourceDisplayTitle` (label "Title"). `projectMerge(sourceWorkID:targetWorkID:request:)` and `WorkMergePlanner.project(_:request:)` gain `request` with no default; a `LibraryProviding` protocol extension supplies the `.merge` overload (Q43). The captured work is the source, the to-read work the target. After the fold and the cover block, for `.toReadMatch` the planner sets:++| Outcome field | Value |+|---|---|+| `displayTitle`, `lastParsedTitle`, `titleProvenance` | source's |+| `readingStatus` | source's |+| `workStatus`, `verdict`, `releaseDays` | each source's, unless the target's is not pristine. Pristine is decided on the target basis's raw columns: `workStatusRaw == "ongoing"`, `verdict` blank by `M2Unicode.isBlank`, `releaseDaysRaw` an empty array; an unknown raw value or token is not pristine |+| `retainedFields` | rebuilt: the fold's list with every title, reading-status, work-status, verdict and release-days entry removed, then `sourceDisplayTitle` and `sourceReadingStatus`, and for each of work status, verdict and release days the side that wins (`source*` or `target*`) |+| `discardedFields` | rebuilt: the fold's list with every title, reading-status, work-status, verdict and release-days entry removed, then `targetManualTitle` always, `targetReadingStatus` always, and for each of work status, verdict and release days the source's field when the source loses, its value is not the default (`ongoing`, blank, empty) and it differs from the winner's; a pristine target that loses is never listed (Q42) |+| `auditBlock` | `WorkMergeAuditFormatter.block(sourceTitle: source title, discardedWorkURLs: as the fold computed, sourceVerdict: source verdict only if it lost, sourceNotes: source notes, titleBeforeMerge: target display title)`, always written |+| `genericNotes` | target notes with that block appended by `WorkMergeAuditFormatter.append` |++The header still names the captured work, which is where the notes below it came from; the typed title is its own labelled line (Req 4.4).++### Decline++`recordDistinctPairs(_ pairs: [WorkPairKey]) async throws`: one exclusive lock, the existing idempotent per-pair body, one `saveStrategy.save`. `AppLibraryModel.declineToReadMatch(_ item:)` passes every listed choice, blocked ones included (Req 5.1), then calls `refreshDiagnosesAndSnapshots()`. It schedules no reconcile (Q25).++### App (new files in `ViewModels/` and `Views/`)++- `ToReadMatchModel` (`@Observable`): looks the item up in the current workload when it appears; if it is gone, the sheet shows "Already resolved" as `DuplicateResolutionView` does for `duplicate-resolution-resolved-elsewhere`. `choose(_:)` builds `WorkMergeModel(sourceWorkID: captured, library:, onMutation:, request: .toReadMatch, presetTargetID: toReadID)`, which is the merge phase. `decline()` calls the library model and closes the sheet on success. `phase` is derived, never stored: closed once a decline has landed, merging while there is a merge model, loading until the first `load()`, then card or resolved-elsewhere by whether the item is published. `committedTargetID` is the merge model's.+- `ToReadMatchSheet`: one sheet with two phases. The card phase shows "Is this the same story?", the captured title, host and "N chapters", one bordered button per choice (a blocked one disabled with its reason below, worded by `WorkMergeModel.refusalMessage(for:)` as the picker's rows are), and "None of these". The merge phase replaces the card with `WorkMergeView` whenever the model holds a merge model; the view keeps its own `NavigationStack`, and there is no push, so no nested stack. Identifiers are `to-read-match-<capturedID>-confirm-<toReadID>` and `to-read-match-<capturedID>-none`, using `uuidString` like the merge identifiers, and `to-read-match-sheet` is set once on the sheet's container.+- **Leaving the merge phase (Q49, Q55).** The sheet passes `onCancel: returnToCard` and `dismissesOnCommit: false`. `onCancel` covers both ways out of the merge view, the toolbar X and the error view's Dismiss. Both are disabled while the merge is submitting, and `returnToCard()` is a no-op then, so a landing merge cannot be left and its survivor lost. A plain cancel from the preview returns to the card as it stands, with nothing written (Req 4.1); only a return from an error state (a refusal or an `.invalidated` commit) first awaits a refresh of diagnoses and snapshots, so the card does not offer the pair that was just refused. `dismissesOnCommit` is separate from `onCancel`: the ordinary host passes neither and keeps dismissing on its own commit.+- **The survivor (Q47).** On a committed confirm the sheet hands `committedTargetID` to the host, which closes the sheet and shows the survivor through `AppNavigation.showWork(_:on:)` on the stack that opened the card (Today for the Elsewhere row, Works for the pill), resetting that stack to `[.work(survivor)]`. `replaceWork`, which the ordinary Merge uses, is not used: it assumes the reader was on the merged work's page. A route to the captured work on the other stack is left as it is, as the ordinary Merge leaves it.+- `WorkMergeModel.init` gains `request:` (default `.merge`) and `presetTargetID: UUID?` (default `nil`), and preconditions that a `.toReadMatch` request has a preset target. A new `start()` replaces the view's direct `loadDestinations()` call in `.task` (`WorkMergeView.swift:50`): with a preset target it calls `selectTarget(presetTargetID)` and never enters `.pickingDestination`; without one it calls `loadDestinations()` as today. `WorkMergeView` gains `onCancel` and `dismissesOnCommit` (above), labels for the two new field cases, and a value line for `targetManualTitle` in `discardedValue` (:448) showing the typed title, as `.sourceSeries` shows its series.++## Data Models++No schema change. `WorkDistinctPair` gains a writer and keeps its columns. `WorkMergeRequest` and `WorkMergeField` gain one case each; neither is persisted or archived.++## Error Handling++| Failure | Behaviour |+|---|---|+| Pair no longer a candidate at commit | `.invalidated` with the message above, shown through the existing `merge-error-message` path (Req 4.6) |+| Quarantine, torn group, series conflict at commit | Existing refusals, unchanged |+| `recordDistinctPairs` save fails | Throws; the sheet shows the error and stays open; nothing is recorded, since there is one save |+| URL rule unreadable or `apply` throws | The Work URL arm does not hold for that work; no log, no diagnosis |++## Testing Strategy++**Core (`make test-core`), new `ToReadMatcherTests.swift`:**+- The Req 2.4 table as a parameterised test, plus `ß`/`ss`, `İ`, full-width Latin, and an article-only title.+- Property tests with swift-testing arguments over titles generated from a seeded list of words with diacritics, punctuation, full-width and Turkish letters: `normalise` is idempotent on its `text`; `titlesMatch` is symmetric; equal normalised text always matches; changing case or inserting punctuation between words never changes the result.+- `candidates`: shared site and multi-site works (2.1); the Work URL arm with a `.work` rule, a `.workAndSequence` rule on a landing URL, no rule, no Work URL, and a `legacyUnverified` captured identity (2.3); a declined pair excluded while the same work's other pair stays (2.5); excluded while in a work set or torn, including a cross-site title set, and offered again once it resolves (3.5); blocked choices for quarantine and series (3.4); one item per captured work with several choices, and one to-read work listed on two items (3.1, 3.3); identical output over shuffled input (1.1); entry count through `entry.work?.id`.+- `DuplicatePublicationTests`: a seeded pair appears in `todayPresentation().duplicateWorkload.toReadMatches`; `reviewCount` and `isEmpty` are unchanged by it; a reconcile pass gives the same `DuplicateScanResult` and gate counters with and without to-read works present (1.3).+- `WorkMergePlannerTests`: the Req 4.3 table with pristine and edited targets; retained and discarded lists; the audit block keeps the captured notes, discarded Work URLs and the `Title before merge` line (4.1, 4.3, 4.4); `.merge` output unchanged; and over a basis with a cover, a series, a link, a credit, entries and a second site, the `.toReadMatch` outcome equals the `.merge` outcome on every field the overlay does not name, swept by reflection (4.2).+- `WorkMergeToReadMatchTests`: the commit writes every overridden field and the survivor keeps the to-read UUID (4.2); an unknown raw reading or work status on the captured work is copied verbatim, and an unknown raw work status on the to-read work is kept as not pristine; a later capture on a `.rule` site reuses the survivor (4.5); a commit after a decline recorded behind the preview returns `.invalidated` and changes nothing (4.6); a `.toReadMatch` commit with an unchanged library commits rather than returning `.refreshed`, and a stale but still matching one returns a `.refreshed` contract that still carries `.toReadMatch`.+- More `WorkMergeToReadMatchTests`: a split captured group whose carrier and representative differ writes the previewed `lastParsedTitle`, and every row of a split target group receives the overrides (4.2, 4.3); invalidation at the first stale confirm when the to-read title is edited out of match (Q53), invalidation when either work joins a duplicate set after the preview, and a failed save leaving the library unchanged (4.6); after confirming a to-read work listed on two items through `projectMerge` and `commitMerge`, the next `todayPresentation` lists it on neither (3.3).+- `DuplicatePublicationTests` also: a pair created by a capture, by a sync-shaped insert and by an import each appears at the next `todayPresentation` (1.2).+- `recordDistinctPairs`: every pair in one commit, idempotent, none saved on failure (5.1); a declined pair survives a backup export and import round trip, and is re-pointed through a later merge and a later duplicate collapse so it stays declined (5.2).+- `CrossSiteDuplicateScanTests`: decline a candidate pair, then remove their shared site so their site sets are disjoint with equal titles; no cross-site title set forms (5.3).++**App (`make test-quick`):**+- `ToReadMatchModelTests`: choose, decline and a stale item.+- `WorkMergeModelTests`: with `presetTargetID`, `start()` projects that target and the state never passes through `.pickingDestination`; without it, behaviour is unchanged.+- `DuplicateSurfaceTests`: the banner count and the Elsewhere row.++**UI (`make test-ui`, `make test-ui-ipad`):** a `seeded-tolerated-to-read-match` scenario with one captured work paired with two to-read works, one of them in a conflicting series. Tests: Today banner → Elsewhere row → sheet → choice → preview → merge, after which the sheet is closed and the survivor's detail is shown; choice → preview → cancel returns to the card and both works remain (4.1); Works row pill → "None of these" → pill gone; the sheet at `AccessibilityXXXL` on iPhone and in the wide layout on iPad, with every choice reached through the accessibility element tree as the existing accessibility journeys do (3.6). The Mac wide layout is covered by the `build-mac` compile in `make test-quick` and by a row in the manual Mac checklist, which is the owner's to run.++**Performance:** `M4ToReadMatchScalePerformanceTests`, with a private store over the base fixture plus `seedM4ToReadMatchLayer()` (50 to-read works on `m4FixtureHostname`: 20 equal after normalising, 10 prefix matches, 20 near misses, and the 10 captured works the prefix matches pair with, Q46), following `seedM4SeriesFixture`. Every title on the layer starts with `story`, so every to-read work scans the whole 1,010-work first-word bucket, Q41's worst case on this fixture. Three arms:+- `to-read-match-derivation` times `ToReadMatcher.candidates` over rows fetched as `todayPresentation` fetches them, 20 samples, `expectWithinBudget` at 100 ms (Req 6.1). No regression ceiling sits under the budget (Q52): the fixture already runs the single-bucket worst case, so a ceiling could catch nothing the budget does not.+- `to-read-match-publication` times `todayPresentation` over the layered store, 20 samples, `expectWithinBudget` at the 2 s `todayPublishBudget` (Req 6.2 with to-read works present), with a 3 s regression ceiling. The existing `todayPublication` arm keeps its fixture and budget.+- `to-read-match-recheck` times `isCandidate` for one pair, reported only, so the exclusive-lock cost of a confirm is on record.++## Risks and Assumptions++- Assumption: `String.folding(options: .caseInsensitive, locale: nil)` applies full case folding (`ß` → `ss`) on iOS and macOS | Verify: the `ß` case in `ToReadMatcherTests`, written first | If wrong: fold per scalar with `lowercaseMapping` of `uppercaseMapping` and pin the divergent scalars in the same test.+- Risk: the prefix scan over a large site exceeds 100 ms even with first-word bucketing | Verify: the `to-read-match-derivation` arm | If wrong: keep each first-word bucket sorted by `text` and binary-search the range of titles that start with the shorter title's text followed by a space.
specs/to-read-capture-match/requirements.md Added +117 / -0
diff --git a/specs/to-read-capture-match/requirements.md b/specs/to-read-capture-match/requirements.mdnew file mode 100644index 00000000..2ec7a8a5--- /dev/null+++ b/specs/to-read-capture-match/requirements.md@@ -0,0 +1,117 @@+# Requirements: To-Read Capture Match++## Introduction++A work made by hand with the New Work form starts as `toRead` and has no URL identity. Capture already lands on such a work when the parsed title equals the reader's title exactly; otherwise the first captured chapter creates a second work that no duplicate scan links to it. This feature finds those pairs — a to-read work and another work on a shared site whose Work URL or title says they are the same story — and asks the reader on the existing duplicate review surfaces; confirming merges the two into the to-read work and declining is remembered on every device. Transit ticket T-2366.++## Non-Goals++- No change to which work a capture lands on: capture-time matching and the capture commit are unchanged, and nothing is asked in the share sheet or the in-app capture flow.+- No new reconcile trigger, reconcile phase or duplicate scan record type; candidates never feed the duplicate scan, the collapse phase, the settling ledger or the full-tier gate counters.+- No automatic merge, not even on a Work URL match.+- No candidates across sites, and none for a to-read work that has no site.+- No fuzzy matching beyond [2.2](#2.2)–[2.4](#2.4): no edit distance, no transliteration, no model call.+- No schema version, readiness marker or archive generation change.+- No to-read works added from the share sheet (T-2363).+- No change to the ordinary Merge action, which still never promotes (`to-read` Req 5.3).++## Definitions++- **To-read work**: as defined in `specs/to-read/requirements.md`. All values of a work named here are the ones its snapshot carries, never a single row's.+- **Captured work**: any work that is not a to-read work, whether or not a capture created it.+- **Candidate pair**: an unordered pair of one to-read work and one captured work that meets [2.1](#2.1)–[2.2](#2.2) and is not excluded by [2.5](#2.5) or [3.5](#3.5).+- **Normalised title**: the title after, in order: Unicode compatibility decomposition (NFKD); Unicode full default case folding with no locale (`ß` becomes `ss`); NFKD again; removal of every nonspacing mark (general category Mn) and every format character (general category Cf, such as a zero-width space or a soft hyphen); replacement of every scalar in general categories P and S by a space; collapse of whitespace runs to one space; trimming. The result is identical in every locale; devices on different Unicode versions may disagree on newly assigned scalars, which is accepted.+- **Word**: a run of scalars between U+0020 spaces in a normalised title. **Length**: the number of Unicode scalars in a normalised title, spaces included. A leading `the`, `a` or `an` word, with the space after it, is counted in neither, but stays part of the title for every comparison.+- **Pristine to-read value**: the value the New Work form gives a work — work status `ongoing`, a verdict that is blank (empty or whitespace only), an empty set of release days.+- **Declined pair**: a pair the reader has answered "none of these" for, on any device.+- Review surfaces, review item, duplicates-only filter, open duplicate set and torn group are as defined in `specs/duplicate-reconciliation/requirements.md`; the merge preview is the existing Merge action's preview.++## Requirements++### 1. Finding the Pair++**User Story:** As a reader, I want the app to notice when a chapter I captured probably belongs to a work in To Read, so that I do not end up with the same story twice.++**Acceptance Criteria:**++1. <a name="1.1"></a>The system SHALL derive candidate pairs from synced library content only, so that two devices holding the same content derive the same pairs, and SHALL include pairs that already exist in the library when this feature ships.  +2. <a name="1.2"></a>WHEN a capture, a sync arrival, an import or any other change produces or removes a candidate pair, THEN the review surfaces SHALL reflect it the next time Today or the Works list publishes its review items, and no capture SHALL wait on that publication.  +3. <a name="1.3"></a>Deriving candidate pairs SHALL NOT change what any reconcile pass converges, collapses or counts.  ++### 2. The Match Rule++**User Story:** As a reader, I want to be asked only when the two works really look like one story, so that the question does not come up on every capture.++**Acceptance Criteria:**++1. <a name="2.1"></a>Both works of a candidate pair SHALL have a membership on at least one shared site; [2.2](#2.2) is evaluated per shared site and a match on any one of them suffices.  +2. <a name="2.2"></a>A pair SHALL match on a shared site WHEN the Work URL arm of [2.3](#2.3) holds, OR the two normalised display titles are equal and non-empty, OR the title prefix arm of [2.4](#2.4) holds.  +3. <a name="2.3"></a>The Work URL arm SHALL hold WHEN applying the site's current URL rule to the to-read work's Work URL on that site, exactly as it is applied to a captured URL, succeeds and yields a work identity equal, scalar for scalar, to the captured work's URL identity on that site; the arm SHALL NOT hold, and SHALL NOT fail the match, WHEN the site has no rule, either side lacks the value, or applying the rule does not succeed.  +4. <a name="2.4"></a>The title prefix arm SHALL hold WHEN the shorter normalised title is a whole-word prefix of the longer AND the shorter has at least three words or a length of at least twelve; the examples below SHALL hold as stated.  ++   | To-read title | Captured title | Match |+   |---|---|---|+   | Mother of Learning | mother of learning! | yes (equal) |+   | The Wandering Inn | The Wandering Inn (Volume 1) | yes (prefix, 13 scalars) |+   | Beware of Chicken | Beware of Chicken: A Xianxia Cultivation Novel | yes (prefix, 3 words) |+   | Café Démon | CAFE DEMON | yes (equal) |+   | The Last | The Last Wish | no (1 word, 4 scalars) |+   | Worm | Worm (Parahumans 1) | no (1 word, 4 scalars) |+   | Worm | Wormwood | no (not a whole-word prefix) |+   | Book 1: The Final Ascension | The Final Ascension | no (not a prefix; the shorter passes the floor) |+   | Wandering Inn | The Wandering Inn 2 | no (the article stays in the comparison) |+   | !!! | ??? | no (empty after normalising) |++5. <a name="2.5"></a>A declined pair SHALL NOT be offered again on any device, while every other pair either work belongs to is still offered.  ++### 3. Asking the Reader++**User Story:** As a reader, I want the question to show up where I already resolve duplicates, so that I have one place to tidy my library.++**Acceptance Criteria:**++1. <a name="3.1"></a>Each captured work with at least one candidate pair SHALL produce exactly one review item, counted once in the Today duplicate banner, shown under the duplicates-only filter, and reachable from the captured work's Works list row as other review items are.  +2. <a name="3.2"></a>The review item SHALL show the captured work's title, site and entry count, list every to-read work it pairs with by title, ask "Is this the same story?", and offer one choice per listed to-read work plus "None of these".  +3. <a name="3.3"></a>WHERE a to-read work pairs with more than one captured work, each captured work's item SHALL list it, and confirming it on one item SHALL remove it from the others at the next publication.  +4. <a name="3.4"></a>WHERE merging a listed pair would be refused for a quarantined site of either work or a series conflict, the item SHALL show that reason beside that choice and SHALL NOT offer it, while "None of these" stays available.  +5. <a name="3.5"></a>WHILE either work of a pair is in an open Work duplicate set or its group is torn, the pair SHALL NOT be offered, and it SHALL be offered again at the first publication after that set is resolved or that group is whole.  +6. <a name="3.6"></a>Every choice on the review item SHALL be reachable and operable with VoiceOver and at `UICTContentSizeCategoryAccessibilityXXXL` on iPhone, and in the wide layouts on iPad and Mac, carrying the accessibility identifiers `to-read-match-<capturedWorkID>-confirm-<toReadWorkID>` and `to-read-match-<capturedWorkID>-none`; the item's identity is the captured work's UUID.  ++### 4. Confirming++**User Story:** As a reader, I want confirming to leave one work holding everything, so that the story I planned to read now shows what I have read of it.++**Acceptance Criteria:**++1. <a name="4.1"></a>WHEN the reader chooses a to-read work, THEN the system SHALL show the merge preview, with the to-read work as the survivor and its discarded-field list listing the to-read work's display title and every value that loses under [4.3](#4.3) where that value is not its field's default and differs from the winner's (Q42), and listing no value that [4.3](#4.3) keeps and no pristine to-read value it replaces, and SHALL change nothing until the reader confirms it; cancelling SHALL leave both works and the review item as they were.  +2. <a name="4.2"></a>WHEN the reader confirms, THEN the captured work SHALL be merged into the to-read work, which keeps its UUID, with the existing Merge action's outcome for every field [4.3](#4.3) does not name, including entries, notes, cover, series, links, credits, characters, places, site memberships and Work URLs, and with URL identity re-derived per site as that action derives it; the values [4.3](#4.3) names SHALL be applied on top of that outcome, and resolving an ordinary duplicate set SHALL be unchanged.  +3. <a name="4.3"></a>The survivor SHALL take:  ++   | Field | Value |+   |---|---|+   | Display title, parsed title, title provenance | the captured work's |+   | Reading status | the captured work's |+   | Work status, verdict, release days | each the captured work's, unless the to-read work's value differs from its pristine to-read value, in which case the to-read work's |++4. <a name="4.4"></a>The survivor's notes SHALL gain the audit block the Merge action writes for the captured work, recording as discarded only values that lose under [4.3](#4.3), plus one line recording the to-read work's display title, written whether or not the Merge action's own condition for a block holds, so neither the captured work's notes nor the title the reader typed are lost.  +5. <a name="4.5"></a>WHEN the next capture of the story is committed after a confirmed merge AND the survivor has a URL identity on the capture's site, THEN the capture SHALL land on the survivor through the existing capture matching.  +6. <a name="4.6"></a>WHEN the pair no longer meets the full candidate rule, evaluated again at the moment of confirming, or the merge is refused or fails, THEN the library SHALL be unchanged and the reader SHALL see why, as the existing Merge action reports a refusal.  ++### 5. Declining++**User Story:** As a reader, I want "no" to be final, so that I am not asked about the same two works again on this device or another.++**Acceptance Criteria:**++1. <a name="5.1"></a>WHEN the reader chooses "None of these", THEN the system SHALL record every pair listed on that item as declined in one commit and SHALL leave both works otherwise unchanged.  +2. <a name="5.2"></a>A declined pair SHALL sync to the reader's other devices, survive a backup export and import, and follow its works through a later merge or duplicate collapse as distinct pairs already do.  +3. <a name="5.3"></a>A declined pair SHALL also suppress a cross-site title edge between the same two works should their sites later become disjoint, as a distinct pair does today, and SHALL suppress no other edge, duplicate set or review item.  ++### 6. Cost++**User Story:** As a reader with a large library, I want this check to cost nothing I can notice, so that Today stays as quick to draw as it is.++**Acceptance Criteria:**++1. <a name="6.1"></a>Candidate derivation SHALL take no more than 100 ms, measured by its own performance arm over the M4 fixture extended with 50 to-read works whose titles include matches and near misses under [2.4](#2.4); the extension SHALL be loaded by that arm only, so no existing arm's input or band changes.  +2. <a name="6.2"></a>Today's publication, including candidate derivation, SHALL stay within its existing 2 s budget.  
specs/to-read-capture-match/tasks.md Added +170 / -0
diff --git a/specs/to-read-capture-match/tasks.md b/specs/to-read-capture-match/tasks.mdnew file mode 100644index 00000000..05f3d61c--- /dev/null+++ b/specs/to-read-capture-match/tasks.md@@ -0,0 +1,170 @@+---+references:+    - specs/to-read-capture-match/requirements.md+    - specs/to-read-capture-match/design.md+    - specs/to-read-capture-match/decision_log.md+---+# To-Read Capture Match++## Matcher++- [x] 1. Write normalisation and title-match tests for ToReadMatcher <!-- id:a8q34o4 -->+  - New Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift+  - Write the ß to ss case first: it verifies the design's full-case-folding assumption; if folding(.caseInsensitive, locale: nil) fails it, switch normalise to per-scalar lowercaseMapping of uppercaseMapping and pin the divergent scalars here+  - Req 2.4 table as a parameterised test, plus İ, full-width Latin and an article-only title+  - Property tests with swift-testing arguments over titles generated from a seeded word list with diacritics, punctuation, full-width and Turkish letters: normalise is idempotent on text; titlesMatch is symmetric; equal text always matches; case changes and punctuation between words never change the result+  - Red is a compile failure on ToReadMatcher+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [2.2](requirements.md#2.2), [2.4](requirements.md#2.4)++- [x] 2. Implement ToReadMatcher normalise and titlesMatch <!-- id:a8q34o5 -->+  - New Packages/AsterismCore/Sources/AsterismCore/ToReadMatcher.swift with NormalisedTitle+  - Order per Q27: NFKD, locale-free fold, NFKD, drop Mn, P and S to space, collapse with M2Unicode.isWhitespace, trim+  - countedWords and countedLength skip a leading the, a or an and its space; text and words keep it+  - Empty text never matches+  - Blocked-by: a8q34o4 (Write normalisation and title-match tests for ToReadMatcher)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [2.2](requirements.md#2.2), [2.4](requirements.md#2.4)++- [x] 3. Write candidate derivation tests for pairs and candidates <!-- id:a8q34o6 -->+  - In ToReadMatcherTests, building Work, Site, Entry rows in an in-memory store as the existing DuplicateScan tests do+  - Shared site required; multi-site works match on any shared site and yield one choice, item hostname the lowest+  - Work URL arm: .work rule hit, .workAndSequence rule on a landing URL misses, no rule, no Work URL, legacyUnverified captured identity matches+  - Declined pair excluded while the same work's other pair stays+  - Excluded while either work is in any work set, including a cross-site title set, or torn; offered again once the set resolves+  - Blocked choices for a quarantined hostname of either group and for differing series IDs; an all-blocked item is still returned+  - One item per captured work with several choices; one to-read work listed on two items+  - Identical output over shuffled input; titles, statuses and series from the carrier; entry count from Entry.workID+  - Blocked-by: a8q34o5 (Implement ToReadMatcher normalise and titlesMatch)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [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)++- [x] 4. Implement ToReadMatcher pairs and candidates with ToReadMatchItem <!-- id:a8q34o7 -->+  - ToReadMatchItem, Choice and ToReadMatchBlock go in DuplicateWorkload.swift; MatchedPair in ToReadMatcher.swift+  - Bucket groups by membership hostname; site per hostname from SiteResolutionOrder.winnersByHostname+  - Equality index on text, identity index over .rule and .legacyUnverified memberships as ExactScalarString, prefix scan within the to-read title's first-word bucket+  - Work URL arm through URLRuleApplicator.apply on site.currentURLRule; skip when suppliesIdentity is false or apply throws+  - Series conflict uses the WorkMergePlanner.project test at WorkMergePlanner.swift:117; quarantine from the passed map over every membership hostname of both groups+  - No clock, no PersistentIdentifier; sort items by captured UUID and choices by to-read UUID+  - Blocked-by: a8q34o6 (Write candidate derivation tests for pairs and candidates)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [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)++- [x] 5. Write publication tests for toReadMatches on the Today workload <!-- id:a8q34o8 -->+  - DuplicatePublicationTests: a seeded pair appears in todayPresentation().duplicateWorkload.toReadMatches; reviewCount, isEmpty and allItems unchanged by it+  - A pair created by a capture, by a sync-shaped insert and by an import each appears at the next todayPresentation+  - A reconcile pass yields the same DuplicateScanResult and gate counters with and without to-read works present+  - After confirming a to-read work listed on two items, the other item no longer lists it: seed the survivor as merged with reading status reading, since the merge path lands in stream 2+  - Blocked-by: a8q34o7 (Implement ToReadMatcher pairs and candidates with ToReadMatchItem)+  - Stream: 1+  - Requirements: [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [3.1](requirements.md#3.1), [3.3](requirements.md#3.3)++- [x] 6. Wire candidate derivation into todayPresentation and DuplicateWorkload <!-- id:a8q34o9 -->+  - DuplicateWorkload gains toReadMatches, an init parameter defaulted to [] and toReadMatch for a captured work ID+  - LibraryRepository+TodayPresentation.swift: call candidates after workGroups at :80, then move the DuplicateWorkload construction at :55 and the duplicateRoutes read at :58 below it+  - Pass diagnostics.quarantineMap from inside the lock closure+  - Run make test-core+  - Blocked-by: a8q34o8 (Write publication tests for toReadMatches on the Today workload)+  - Stream: 1+  - Requirements: [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [3.1](requirements.md#3.1)++## Merge and decline++- [x] 7. Write recordDistinctPairs tests <!-- id:a8q34oa -->+  - In the existing distinct-pair tests beside LibraryRepository+DuplicateResolution coverage+  - Every pair saved in one commit; idempotent re-record; a forced save failure saves none+  - A declined pair survives a backup export and import round trip, and is re-pointed through a later merge and a later duplicate collapse+  - CrossSiteDuplicateScanTests: decline a same-site pair, remove the shared site so the site sets are disjoint with equal titles; no cross-site title set forms+  - Stream: 2+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3)++- [x] 8. Implement recordDistinctPairs <!-- id:a8q34ob -->+  - LibraryRepository+DuplicateResolution.swift:29: one exclusive lock, the existing per-pair body, one saveStrategy.save+  - recordDistinctPair becomes a one-pair call to it; add the requirement to LibraryProviding and MockLibraryProvider+  - Blocked-by: a8q34oa (Write recordDistinctPairs tests)+  - Stream: 2+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2)++- [x] 9. Write merge planner tests for the toReadMatch request <!-- id:a8q34oc -->+  - WorkMergePlannerTests: the Req 4.3 table with pristine and edited targets, pristine decided on raw columns; an unknown raw work status or release-day token on the target is not pristine+  - rawOverrides carries titles and statuses from the source carrier and lastParsedTitle from the source representative+  - retainedFields and discardedFields rebuilt as the design's table says: targetManualTitle and targetReadingStatus always discarded, sourceManualTitle never, winning sides retained, sourceDisplayTitle retained+  - Audit block always written, keeps the captured notes, discarded Work URLs and a losing verdict, with the Title before merge line after the header+  - The .merge request output is byte-for-byte unchanged over the existing planner fixtures+  - Red is a compile failure on .toReadMatch+  - Stream: 2+  - Requirements: [4.1](requirements.md#4.1), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)++- [x] 10. Implement the toReadMatch request in the merge planner and projection <!-- id:a8q34od -->+  - ProjectionContract.swift: WorkMergeRequest.toReadMatch; WorkMergeField.targetManualTitle with recordedInNotes true and sourceDisplayTitle; WorkMergeWorkBasis gains workStatusRaw, readingStatusRaw, titleProvenanceRaw and releaseDaysRaw filled in buildMergeBasis; WorkMergeOutcome gains rawOverrides+  - WorkMergeAuditFormatter.block gains titleBeforeMerge defaulted to nil+  - WorkMergePlanner.project at :107 takes request; overrides applied after the cover block at :134-157, outside WorkVariantUnion.fold+  - projectMerge at :322 and :335 gains request and stores it in the contract; LibraryProviding.swift:518 requirement without default plus an extension overload for .merge; MockLibraryProvider.swift:901+  - Blocked-by: a8q34oc (Write merge planner tests for the toReadMatch request)+  - Stream: 2+  - Requirements: [4.1](requirements.md#4.1), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)++- [x] 11. Write merge commit tests for the toReadMatch request <!-- id:a8q34oe -->+  - WorkMergeRepositoryTests: every overridden field written, survivor keeps the to-read UUID; unknown raw statuses copied verbatim+  - A split captured group writes the previewed lastParsedTitle; every row of a split target group receives the overrides+  - A later capture on a .rule site reuses the survivor+  - Invalidated with nothing changed after a decline recorded behind the preview, after the to-read title is edited out of match, and after either work joins a duplicate set; a failed save leaves the library unchanged+  - An unchanged library commits rather than returning .refreshed, and a .refreshed contract still carries .toReadMatch+  - Blocked-by: a8q34o7 (Implement ToReadMatcher pairs and candidates with ToReadMatchItem), a8q34od (Implement the toReadMatch request in the merge planner and projection)+  - Stream: 2+  - Requirements: [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6)++- [x] 12. Implement the toReadMatch commit path and isCandidate <!-- id:a8q34of -->+  - LibraryRepository+WorkMerge.swift: re-project with contract.request at :368 and build the .refreshed contract with it at :380+  - After the torn and quarantine refusals at :421-443, call ToReadMatcher.isCandidate and return .invalidated with These works no longer look like the same story. when false+  - isCandidate fetches Work and Site rows and distinct pairs, no Entry rows, computes workSets as todayPresentation does and checks the pair is in pairs+  - Target-row loop at :505-524 writes each rawOverrides value to every target row only where it differs+  - Run make test-core+  - Blocked-by: a8q34oe (Write merge commit tests for the toReadMatch request)+  - Stream: 2+  - Requirements: [4.2](requirements.md#4.2), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6)++## App++- [x] 13. Write app model tests for the to-read match flow <!-- id:a8q34og -->+  - WorkMergeModelTests: with presetTargetID, start projects that target with request .toReadMatch and never enters pickingDestination; without it behaviour is unchanged+  - New ToReadMatchModelTests: choose builds the preset merge model; decline records every listed pair including blocked ones and closes on success; a failed decline keeps the sheet with the error; an item gone from the workload reads as already resolved+  - DuplicateSurfaceTests: banner count adds toReadMatches, an all-blocked item included; one Elsewhere row per item with the text May belong to a story in To Read+  - Red is a compile failure on the new model API+  - Blocked-by: a8q34o9 (Wire candidate derivation into todayPresentation and DuplicateWorkload), a8q34ob (Implement recordDistinctPairs), a8q34of (Implement the toReadMatch commit path and isCandidate)+  - Stream: 3+  - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [4.1](requirements.md#4.1), [5.1](requirements.md#5.1)++- [x] 14. Write the to-read match UI scenario and UI tests <!-- id:a8q34oh -->+  - New UI-test scenario seeded-tolerated-to-read-match: one captured work paired with two to-read works, one of them in a conflicting series+  - DuplicateResolutionUITests: Today banner to Elsewhere row to sheet to choice to preview to merge, then the sheet is closed and the survivor's detail is shown; choice to preview to cancel returns to the card with both works present; Works row pill to None of these, pill gone+  - Accessibility journey at AccessibilityXXXL on iPhone and wide-layout test on iPad reaching every choice by identifier+  - Identifiers to-read-match-<capturedID>-confirm-<toReadID>, to-read-match-<capturedID>-none, work-to-read-match-pill, all uuidString+  - Blocked-by: a8q34og (Write app model tests for the to-read match flow)+  - Stream: 3+  - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1)++- [x] 15. Implement the to-read match sheet and wire it into Today, Works and navigation <!-- id:a8q34oi -->+  - WorkMergeModel: request and presetTargetID init parameters, start replacing the direct loadDestinations call in WorkMergeView .task at :50+  - WorkMergeView: onCancel hook, labels for targetManualTitle and sourceDisplayTitle, discardedValue at :448 shows the typed title+  - New ViewModels/ToReadMatchModel.swift and Views/ToReadMatchSheet.swift: card and merge phases in one sheet, no push; on committed close the sheet and navigate to committedTargetID as WorkDetailView does+  - AppLibraryModel: declineToReadMatch calling recordDistinctPairs then refreshDiagnosesAndSnapshots, no reconcile; duplicateBannerCount at :1850 adds toReadMatches.count+  - TodayView RecentDuplicatePlan Elsewhere row and onResolveToReadMatch; WorksView pill labelled To Read? with the design's accessibility label; AppScreens wiring at :99, :183, :214; AppNavigation presented state beside :293 and :297; ContentView.presentedContent at :602+  - Add a row for the sheet's wide layout to the manual Mac checklist in specs/ipad-and-mac-layouts/verification-run.md+  - Run make test-quick, make test-ui and make test-ui-ipad; simulator only+  - Blocked-by: a8q34oh (Write the to-read match UI scenario and UI tests)+  - Stream: 3+  - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [5.1](requirements.md#5.1)++## Performance++- [x] 16. Add the to-read match performance layer and arms <!-- id:a8q34oj -->+  - M4PerformanceFixture.swift: seedM4ToReadMatchLayer with 50 to-read works on m4FixtureHostname, 20 equal after normalising, 10 prefix matches, 20 near misses, constants beside the others+  - New M4ToReadMatchScalePerformanceTests with a private store layered as M4SeriesScalePerformanceTests does, so no other arm's input changes+  - Arms: to-read-match-derivation over ToReadMatcher.candidates at 100 ms; to-read-match-publication over todayPresentation at todayPublishBudget; to-read-match-recheck over isCandidate, reported only+  - If derivation breaches 100 ms, apply the design's fallback: sort each first-word bucket and binary-search the prefix range+  - Update the make test-performance-m4 suite and test counts in CLAUDE.md+  - Run make test-performance-m4 on the host; not a device run+  - Blocked-by: a8q34o9 (Wire candidate derivation into todayPresentation and DuplicateWorkload), a8q34of (Implement the toReadMatch commit path and isCandidate)+  - Stream: 4+  - Requirements: [6.1](requirements.md#6.1), [6.2](requirements.md#6.2)
specs/to-read-capture-match/verification-run.md Added +70 / -0
diff --git a/specs/to-read-capture-match/verification-run.md b/specs/to-read-capture-match/verification-run.mdnew file mode 100644index 00000000..43208364--- /dev/null+++ b/specs/to-read-capture-match/verification-run.md@@ -0,0 +1,70 @@+# Verification Run: To-Read Capture Match++The measurement evidence for this spec, kept here rather than in `tasks.md`,+because `rune` owns that file.++**Host only.** `make test-performance-m4` is a `swift test` run of the+`AsterismCore` package. No device target was run, nothing was installed or+launched, and `CONFIRM_DEVICE_RUN` was not set.++**Host**: the project machine, `Mac13,1` (Apple M1 Max), macOS 27.0.++## 1. Calibration (task 16), loaded host++The stream agent took these while simulator UI suites from the parallel App+stream were running on the same machine. The run was release, filtered to+`M4ToReadMatchScalePerformanceTests`, on `6225afcb`.++| Arm | Run 1 median | Run 2 median | Spread |+|---|---|---|---|+| `to-read-match-derivation` | 0.0196 s | 0.0198 s | 1.15–1.19× |+| `to-read-match-publication` | 0.910 s | 0.959 s | 1.07–1.08× |+| `to-read-match-recheck` | 0.212 s | 0.232 s | 1.11× / 1.33× |++The one-minute load average rose from about 6 to 18 over run 1, and from 16+to 149 over run 2. The derivation was far enough inside its budget that the+design's fallback, a sorted first-word bucket with a binary-searched prefix+range, was not applied.++## 2. Whole-target run++**Date**: 2026-09-23, about 23:28–23:55 AEST+**Commit**: `bf543eb2` (`T-2366/to-read-capture-match`), after all three+streams were merged. This is before the review fixes for the App and+Performance phases, which drop the derivation arm's sub-budget ceiling and+change no measured code path.+**Load**: 9.05 / 12.27 / 18.41 (1 / 5 / 15 min) at the start, falling from+the UI runs that had just finished, and 5.00 / 5.07 / 7.21 at the end. No+other test or build ran during the measurement; one agent was editing+files. This was not a quiet host by this repo's standard, so these numbers+set no band.++**Result**: `EXIT=0`. 50 tests in 9 suites passed after 1,214.4 s with+**9 known issues**, the same count the last whole-target run recorded+(`specs/launch-to-today/verification-run.md`). The release build before it+took 451.9 s.++| Arm | Median | p95 | Min–max | Spread | Budget |+|---|---|---|---|---|---|+| `to-read-match-derivation` | 0.0182 s | 0.0193 s | 0.0174–0.0195 s | 1.12× | 100 ms (Req 6.1) |+| `to-read-match-publication` | 0.9035 s | 0.9211 s | 0.8766–0.9237 s | 1.05× | 2 s, 3 s ceiling (Req 6.2) |+| `to-read-match-recheck` | 0.2179 s | 0.2295 s | 0.2072–0.2346 s | 1.13× | reported only |++The new suite, `M4 to-read match scale budgets`, took **43.4 s** of the+run. It seeds the full M4 fixture plus the to-read layer (Q46) once per+test, three times in all.++**Reading the numbers**++- **Derivation** uses about 18% of its budget, with every title in one+  first-word bucket, which is Q41's worst case on this fixture. Most of the+  time goes into normalising the 1,010 captured titles, not into comparing+  them.+- **Publication**: the full `todayPresentation`, matcher included, measures+  0.904 s. `todayPublication` alone measured 0.896 s when `launch-to-today`+  amended it, so the matcher adds nothing visible to Today.+- **Re-check**: `isCandidate` runs under the commit's exclusive lock, so the+  merge commit is ~0.22 s slower than an ordinary one on this fixture. It+  is reported, not budgeted.++A quiet-host band for the whole target is still owed, as CLAUDE.md records.
specs/to-read-capture-match/implementation.md Added +291 / -0
diff --git a/specs/to-read-capture-match/implementation.md b/specs/to-read-capture-match/implementation.mdnew file mode 100644index 00000000..02f6e404--- /dev/null+++ b/specs/to-read-capture-match/implementation.md@@ -0,0 +1,291 @@+# Implementation: To-Read Capture Match++This explains the branch `T-2366/to-read-capture-match` (`bbdcd8b6..HEAD`) at+three levels and checks it against `requirements.md`, `design.md` and+`decision_log.md` (Q1–Q56, Decisions 1–2).++---++## Beginner Level++### What Changed++Asterism keeps a list of stories to read later. When you add a story you+haven't started, it waits in To Read. Later you open the story in a browser+and share a chapter into the app. That share creates a second, separate+entry for the same story, because nothing links the chapter to the entry+already in To Read. You end up with two works that are really one.++The app now notices this. When a newly captured work looks like one of your+to-read works, Today says so in its duplicate banner. A row under+"Elsewhere" reads "May belong to a story in To Read", and the work's row in+Works gets a "To Read?" pill. Tapping either one opens a card that asks+whether this is the same story as one of your to-read works:++- **Pick one** and you see a preview of the merged result. Confirm it and+  the two works become one.+- **"None of these"** tells the app they're different stories, and it+  won't ask about that pair again.++### Why It Matters++Without this, a to-read list slowly fills with stale entries while the+story you're actually reading lives somewhere else. The merge keeps the+to-read entry's identity and takes what the capture learned: the real+title, and the fact that you're now reading it. If you had typed a title+for the to-read entry yourself, it isn't lost. It goes into the work's notes.++### Key Concepts++- **Work**: one story in your library. **Entry**: one captured chapter+  page that belongs to a Work.+- **Match**: the two works share a site, and either the site's URL rule+  reads the same story address from both, or their titles agree once+  capitals, accents and punctuation are ignored ("The Wandering Inn" and+  "the wandering inn!" match).+- **Merge**: like stapling two folders into one. Every page moves into the+  folder you keep, and the empty one is thrown away.+- **Decline**: a sticky note saying "these two are different", which syncs+  to your other devices.++---++## Intermediate Level++### Changes Overview++**Core (`AsterismCore`)**++- `ToReadMatcher.swift` (new):+  - `normalise` produces a `NormalisedTitle`.+  - `titlesMatch` checks equality, or a whole-word prefix with a length+    floor.+  - `pairs` derives every `MatchedPair` of a to-read work and a captured+    work on a shared site.+  - `candidates` turns pairs into `ToReadMatchItem`s, one per captured+    work, each listing its to-read `Choice`s.+  - `isCandidate` re-checks one pair under the commit's lock.+- `DuplicateWorkload.swift`: `toReadMatches`, `ToReadMatchItem`,+  `ToReadMatchBlock`.+- `LibraryRepository+TodayPresentation.swift`: calls `candidates` inside+  the Today read and publishes the items on the workload.+- `LibraryRepository+DuplicateResolution.swift`: `recordDistinctPairs`+  writes N declined pairs in one save. `recordDistinctPair` now delegates+  to it.+- `ProjectionContract.swift` and `WorkMergePlanner.swift`:+  - A new `WorkMergeRequest.toReadMatch`.+  - A private `toReadMatchOverlay` applied after the ordinary fold. It+    decides title, provenance, reading and work status, verdict and+    release days.+  - `WorkMergeRawOverrides` carries the raw column values to write.+  - An audit block records the typed title (`titleBeforeMerge`).+- `LibraryRepository+WorkMerge.swift`:+  - The commit re-projects with the contract's own request.+  - A stale `.toReadMatch` confirm re-checks `isCandidate` before offering+    a refreshed preview (Q53).+  - A fresh confirm re-checks it after the torn and quarantine refusals.+  - The raw overrides are written to every target row, value-guarded.+- Shared helpers:+  - `LibraryRepository.quarantinedHostnames(of:in:)`, used by both the+    commit's refusal and the matcher's blocked reasons (Q45).+  - `SeriesMembership.areInDifferentSeries`, used by the planner, the+    merge picker and the matcher.++**App**++- `ToReadMatchModel` and `ToReadMatchSheet` (new): one sheet with a card+  phase and a merge phase, with no navigation push.+  - The merge phase reuses `WorkMergeModel` and `WorkMergeView`, given a+    `presetTargetID` and `request: .toReadMatch`.+  - `phase` is derived from the model's stored state rather than stored.+- `WorkMergeView`:+  - `onCancel` covers both the X and Dismiss.+  - `dismissesOnCommit: false` lets the sheet own dismissal (Q55).+  - Cancel is disabled while the commit is submitting (Q49).+- `AppLibraryModel`:+  - `declineToReadMatch` calls `recordDistinctPairs`, then refreshes. It+    doesn't reconcile (Q25).+  - The banner count adds `toReadMatches.count`.+- `TodayView` (the Elsewhere row), `WorksView` (the pill), and+  `AppNavigation`/`ContentView` (presentation, and routing the survivor to+  the stack that opened the sheet, Q47).++**Tests and performance**++- Core suites: `ToReadMatcherTests` (normalisation table, property tests,+  candidates), `WorkMergeToReadMatchTests`, planner and publication tests.+- App: model tests.+- UI: journeys on iPhone, at AccessibilityXXXL and on iPad, driven by the+  scenario `seeded-tolerated-to-read-match`.+- `M4ToReadMatchScalePerformanceTests`: three arms.++### Implementation Approach++- **Derived, not stored.** A match is never persisted. It is recomputed in+  every Today publication from synced content, so two devices agree+  without coordinating (Req 1.1), and it never enters the duplicate scan+  or the reconcile pass (Req 1.3). The only thing stored is a decline, as+  an ordinary synced `WorkDistinctPair`.+- **Indexing:**+  - The to-read side is indexed first, and derivation returns `[]` early+    when there are no to-read works.+  - Captured works are normalised only on hostnames that hold a to-read+    work.+  - Title candidates come from a single first-word bucket plus+    `titlesMatch` (Q41).+  - The Work URL arm reads the identity through `URLRuleApplicator` on+    the site's current rule, only for rule states that supply identity+    (Q28).+- **One merge engine.** The to-read merge is the ordinary merge with a+  request flag, so preview, refresh, commit, re-pointing and audit all come+  from existing machinery. The overlay runs *after* `WorkVariantUnion.fold`+  instead of changing the fold (Q17), so an ordinary merge is untouched.+- **Blocked instead of hidden.** A choice the commit would refuse+  (quarantined hostname, conflicting series) is still listed, with its+  reason, and all-blocked items still count in the banner (Q35). Both+  sides use the same helpers, so a reason shown on the card and a refusal+  at commit cannot disagree.++### Trade-offs++- **Recomputing on every Today publication.**+  - Cost: ~18 ms on the M4 fixture; the publication measured 0.904 s+    against 0.896 s before the feature.+  - Gain: no cache invalidation and no sync of derived state.+- **Re-checking at commit.**+  - Cost: `isCandidate` fetches works, sites and pairs and rebuilds work+    sets under the exclusive lock, ~0.22 s on M4.+  - Gain: without it, a decline or title edit arriving behind an open+    preview could merge two works the reader would no longer be asked+    about. It is narrowed to the pair's two works (Q54) but keeps the+    whole-library work sets, because the exclusion depends on them.+- **Match rules.** The whole-word prefix plus a length floor is+  deliberately conservative: Req 1.1 prefers a missed match to a wrong+  one, since the reader can still merge by hand.++---++## Expert Level++### Technical Deep Dive++**Normalisation (Q27, amended by Q44).** The steps, in order:+1. NFKD.+2. A locale-free full case fold (ß becomes ss, verified in the first+   test).+3. NFKD again.+4. Drop Mn (nonspacing marks) and Cf (format characters: ZWJ, LRM/RLM,+   soft hyphen, BOM). Format characters are removed rather than turned+   into spaces, because a soft hyphen sits inside a word.+5. Turn P and S (punctuation, symbols) into spaces.+6. Collapse whitespace with `M2Unicode.isWhitespace`, and trim.++`words` are split on the U+0020 *scalar*, not on `Character`. Otherwise a+space followed by a combining scalar is one grapheme and silently joins two+words (the ZWJ-emoji case). A leading "the", "a" or "an" is skipped only+for the counted floor, never for equality or the first-word bucket.++**Exclusion (Req 3.5, Q38).** A pair is excluded while either work is in a+work set that *publishes* a review item: `members.count > 1`, or a+classification other than `.silentlyResolvable`. This covers a divergent+one-member set that is not torn (a split group where one row has no+membership). A converged single-work split stays a one-member set+indefinitely, because nothing deletes its rows, so it must not suppress+matching.++**The commit's order for `.toReadMatch`:**+1. Stale basis: run `isCandidate`, and return `.invalidated` if false;+   otherwise return `.refreshed` still carrying `.toReadMatch` (Q53).+   Earlier, a refresh built as `.merge` let the second confirm run a plain+   merge.+2. Torn refusal.+3. Quarantine refusal through the shared helper, reading the `quarantined`+   latch.+4. `isCandidate`.+5. Write-before-delete through the ordinary save strategy.+6. Raw overrides written to every target row, only where they differ.++Unknown raw status values on the captured side are copied verbatim, because+reads are tolerant and writes must not normalise away a newer build's+value. `titleBeforeMerge` is escaped into the audit block.++**Determinism.** No clock and no `PersistentIdentifier` anywhere. Every+dictionary walk ends in a sort by `uuidString` or a `min()`. The carrier and+membership pickers are the existing deterministic ones. Blocked *reasons*+depend on per-device diagnoses, which Req 1.1 permits, because it constrains+pairs, not reasons.++### Architecture Impact++- A second kind of item on `DuplicateWorkload`. Existing consumers are+  unaffected: `reviewCount`, `isEmpty` and `allItems` are unchanged (tested).+- The merge contract carries its request end to end, so any future request+  kind inherits "refresh keeps the request" for free. `WorkMergeModel`+  enforces `request == .merge || presetTargetID != nil` with a+  precondition.+- `MultiSiteReadPathTests`' allowlist gains `ToReadMatcher.swift`. Its+  precondition is that callers build work sets, which fault memberships,+  before `pairs` (Q39).+- No schema, readiness-marker or archive change.++### Potential Issues++- **Title-only matching on sites without a URL rule.** It stays+  conservative, but two genuinely different stories can match when one+  title is a whole-word prefix of the other and above the floor. The card+  asks rather than acts, and a decline is permanent.+- **Survivor routing.** The survivor opens on the stack that opened the+  sheet, and the other stack isn't cleaned. A captured work left open on+  Works while confirming from Today stays there until navigated away+  (Q47). The ordinary merge has the same gap.+- **Blocking work under the lock.** The re-check is the largest new work+  under the exclusive lock. If libraries grow well past M4, the next step+  is prefetching `siteMemberships`, which the efficiency review raised but+  did not measure.+- **Duplicated test data.** The UI tests repeat the Core fixture's UUIDs by+  hand (Q50). A change to one side shows up as a UI timeout, not a clear+  failure.++---++## Completeness Assessment++**Fully implemented**+- Req 1.1–1.3: derivation in Today's publication, deterministic, kept out+  of the scan and reconcile.+- Req 2.1–2.5: shared site, Work URL arm, normalised title equality and+  prefix, declined-pair exclusion.+- Req 3.1–3.6:+  - banner count, Elsewhere row and Works pill;+  - the card and its question;+  - a confirmed to-read work leaves every other item, now tested through+    the real merge;+  - blocked choices with reasons;+  - the exclusions;+  - iPhone at AccessibilityXXXL and the iPad wide layout.+- Req 4.1–4.6:+  - the preview with the typed title in the discarded list;+  - the survivor's fields per 4.3, with every other field as in an+    ordinary merge (tested field by field);+  - the audit block;+  - a later capture reuses the survivor;+  - the commit-time re-check, invalidating at the first stale confirm.+- Req 5.1–5.3: one-commit decline, synced and archived, and suppression of+  later cross-site title edges.+- Req 6.1–6.2: derivation 0.018 s against 100 ms; publication 0.904 s+  against 2 s.++**Partially implemented or verified**+- Req 3.6 on the Mac is covered only by the `build-mac` compile and row B15+  of the owner's manual checklist, as the design intends. Nobody has run+  that row yet.+- The performance figures come from a host that wasn't fully quiet. A+  quiet-host band for the whole target is still owed (CLAUDE.md).++**Missing**+- Nothing against the requirements. One open question is left for the+  owner: the Elsewhere row's wording is the same for every item (Q24), so+  two rows can't be told apart, even with VoiceOver.++**Divergences from the design:** every one found during implementation and+the three review rounds is recorded in the decision log, Q38–Q56.

Things to double-check

Pending-capture suites.

Drain, spool and preserve-first fail with EPERM on spool JSON files. They fail identically on bbdcd8b6, so they are environmental. Worth a re-run with the Mac unlocked before the PR's CI.

Full UI suite.

The last full make test-ui had three failures outside this feature, not checked against main. After this round only DuplicateResolutionUITests ran (11/11).

Elsewhere wording.

Every Elsewhere row reads the same, so two rows can't be told apart. Changing it needs the owner to amend Q24.