Two commits closing the six Known violations of CLAUDE.md's “Edit views save on Save, and only then” rule: every control that wrote on the tap now stages in its view model and commits once, through three new Core calls (commitLinkEdits, removeSiteMemberships, commitSeriesEdits). Reviewed as git diff origin/main...HEAD (PR #90); the branch was not modified.
commitLinkEdits(workID:operations:), removeSiteMemberships(workID:hostnames:) (the singular now delegates), commitSeriesEdits(seriesID:name:notes:members:) writing only the series pair per member.ShareCaptureFlowTests (same 20 on main). App bundle: 1,810 passed, 0 failed.specs/to-read/design.md:89.Ready to push
11 failing tests (all ShareCaptureFlowTests, the host-broken pending-capture family — the same 11 cases / 20 issues fail on main on this host) —
The six violations are closed as the report says, each with both halves tested (the tap writes nothing; Save writes once), and no correctness regression was found. AsterismCore passes apart from ShareCaptureFlowTests (20 issues), which fails identically on main on this host — the pending-capture family the memory note records; the pending-capture suites were skipped by filter. The simulator unit bundle passes 1,810/0. What remains is a short list of follow-ups worth doing before or just after merge: two stale awaits in tests, one stale sentence in specs/to-read/design.md, the new toolbars not using the Q55 label-less glyph pair, a comment and a test that over-claim a Req 2.4 conflict the redirect never provided, and commitLinkEdits duplicating the three singular link writes it calls “primitives”. None of them changes what the reader gets.
Pass rate: 100% (2998 of 3009)
New tests: 38
Diff coverage: 96% (428 of 447 added lines)
d7bbfb4f T-2328: Edit views write on Save, and only then 1f379a0f T-2328: Prefill a staged series position through SeriesPosition.next Asterism has one rule for every editing screen: nothing is written to the library until you press Save, and pressing the X throws your changes away. Six controls broke that rule — tapping them saved immediately, so pressing X afterwards did not undo them. Examples: adding a related work to a work, accepting a suggested URL, removing a work from a site or a series, choosing where to move a chapter, dragging creator roles into a new order, and the series screen's own Save, which wrote in several pieces and could stop halfway.
This change makes each of those controls behave like a normal field: the tap changes what is on screen, Save writes it, X discards it.
A reader could think they had cancelled a change that had already been saved — and on a synced library the change had already gone to iCloud. The series screen was worse: if one position in the list was mistyped, the screen could save some members and not others with no way to tell which.
Four view models grew staged state and lost their per-tap writes. WorkDetailModel holds stagedLinks / removedLinkIDs (with links computed over the read plus the staging), stagedMembershipRemovals (filtering hostnames, siteLinks, removableHostnames) and an acceptedSuggestedURL marker; commitEditing() gained two steps after the record step. SeriesDetailModel holds loadedMembers plus staged removals/additions and its save() parses every position first and makes one call. CreatorRolesModel keeps loadedRows beside rows, with saveOrder() / cancelOrder() and a toolbar pair drawn only while hasUnsavedOrder. MoveToModel gains a Destination selection and submit().
Core adds three calls on LibraryProviding and the repository: commitLinkEdits (operations applied in order under one stamp, refused whole, thrown as WorkLinkError like the singulars), removeSiteMemberships (the last-site guard measured against the whole set; one validation pass over every touched hostname), and commitSeriesEdits (name, notes, and a [SeriesMemberEdit]; each member resolved through resolveWorkWriteTarget and refused if torn; only seriesID/seriesPosition written, value-guarded).
The shape is commitRecordEdits' staged session, copied twice: the view model derives an operation list at Save (stagedLinkEdits(): removals, then retypes where the draft differs from the store, then adds), the repository applies it in one locked context and returns before commit on the first refusal, so the discarded context is the rollback. Prefilled suggestions get a marker, not a comparison: hasUnsavedWorkURLChange is now acceptedSuggestedURL || draft != baseline, because the projection pre-fills the field with the suggestion and the text alone cannot express acceptance (the red-first test).
updateWork out of the link and series paths preserves Q17 (a link edit stamps no Work) and removes the “carry every column back” hazard the old per-member updateWork loop had.removeSiteMembership stay as primitives (Q5) — but see the finding: the batch re-implements them rather than composing them.Link commit ordering. stagedLinkEdits() emits removals first so a remove-then-add on the same pair is not refused by the stored row. In commitLinkEdits that depends on link(over:and:) — a predicated FetchDescriptor — not returning a row context.deleted earlier in the same context, while the same function keeps a staged: Set<WorkPairKey> precisely because a pending insert is not reliably visible to a predicated fetch. No test exercises [.remove(x), .add(samePair)], and the picker cannot reach it either: linkCandidates is read from the store on each “Add a related work” tap and marks a staged-removed work “Already linked” (disabled), while a staged-added one is still offered and refused by the model's own alreadyLinked check. So the ordering claim is unverified but also unreachable.
Basis semantics in commitSeriesEdits. resolveWorkWriteTarget → redirectWork returns the group as soon as fetchWorkGroup(id:) succeeds; basis.matches is consulted only on the post-collapse redirect. updateWork has always worked this way (and specs/to-read/design.md says so), so a concurrent membership change on another device is last-writer-wins per row, not the Req 2.4 “edit conflict” the new doc comment and SeriesModelsTests comment claim. Not a regression — the old loop overwrote every column with the stale basis; the new call overwrites only the pair — but the words overstate the guarantee.
Validation timing in the work editor. addLink validates on staging, but a stored link's type field edited to an invalid value is emitted as .retype ((try? validate) != stored is true for nil) and refused only in commitLinkStep, after the URL, metadata and record steps have committed. Q3 accepts a late store refusal; a validation refusal is knowable before the first write, and SeriesDetailModel.save() parses first for exactly that reason.
Refusal ordering in removeSiteMemberships. The per-hostname loop now checks not-on-site and notes-on-site before the whole-set last-site guard; the old singular checked last-site before notes. A single-site work with notes on that site would now get the notes sentence. Unreachable from the editor (canRemoveMembership never offers it) and untested.
LibraryProviding seam grows three methods with throwing defaults; every extension/test double already conforms.updateSeries has no app caller left; commitSeriesEdits duplicates its row loop with a value guard updateSeries lacks, so a no-op rename stamps in one and not the other. Q5 records the kept primitives and does not mention it.reloadPresentation() is gone; no path replaces the presentation under an open editor, which simplifies the credit-baseline reasoning (Q52) and is why load()'s Q6 pruning in the work editor is defensive rather than reachable. SeriesDetailModel.load()'s equivalent is reachable via the generation bump and untested.onMutation() (a whole-library refresh) can still fire up to three times per Save (URL, metadata, tail); the branch widens the tail condition but the shape predates it.await model.addLink(...) calls on the now-synchronous method (WorkDetailModelTests.swift:1846, 1936).CreatorRolesView and MoveToView add text-labelled Button("Save")/Button("Cancel")/Button("Move") in confirmation/cancellation placements; every other editor uses Q55's label-less Button(role:) glyph pair.SeriesUITests.testTheSeriesEditorRepositionsAddsAndRemovesMembers's add→remove→X segment now never writes; no UI journey saves a staged addition (Q76's path).Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swift
Why it matters. The new write path for every link edit. Order, the staged-pair set, and the early-return rollback are the correctness story; the per-arm bodies are copies of addLink/retypeLink/removeLink.
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift
Why it matters. Fixes the data-losing one of the six: the old save() wrote the name then looped updateWork per member. Now positions are validated first, each member resolved and torn-checked, and only seriesID/seriesPosition are written, value-guarded.
What to look at. LibraryRepository+Series.swift:293-351; SeriesSupport.swift SeriesMemberEdit
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swift
Why it matters. Two removals legal alone but emptying the work together are now refused together; one validation pass over remaining ∪ doomed; predicated delete via an Array in #Predicate.
What to look at. LibraryRepository+Sites.swift:119-190
Asterism/Asterism/ViewModels/WorkDetailModel.swift
Why it matters. Most of the behaviour change: links/hostnames/siteLinks/removableHostnames now read the draft; commitEditing runs links then site removals after the record step; cancel restores all of it; reloadPresentation() is deleted.
Asterism/Asterism/ViewModels/SeriesModels.swift
Why it matters. Removal and addition are now drafts; a conflict returns without load() (Q68); the add prefill is raised past staged additions via SeriesPosition.next (second commit).
What to look at. SeriesModels.swift: members, load() pruning, save(), removeMember, addMember; the old write(_:membership:) helper deleted
Asterism/Asterism/ViewModels/CreatorRolesModels.swift
Why it matters. The two screens that had no Save at all. A read landing mid-drag carries the staged order over it (applying(_:to:)); Move To's rows choose (toggle to clear) and the toolbar's Move writes; the sheet dismisses only on .completed.
updateWork stamps every row of the work group unconditionally, so a session that only retyped a link would stamp the work and reshuffle a date-sorted works list (Q17). commitLinkEdits writes the WorkLink table and no Work row. (series-and-related-works Decision 8, superseding Q24.)
Each member is resolved through resolveWorkWriteTarget against its own basis (Q25's redirect and torn refusal), positions are validated before the lock, and only seriesID/seriesPosition are written, so a new Work column can no longer be cleared by a position edit. (Decision 9.)
The projection pre-fills the field, so text alone cannot express acceptance; one boolean can. .confirmCandidate and .replaceManual store the same address. Alternatives (send .confirmCandidate from Save; treat the prefill as accepted) rejected in polish-and-export Decision 6.
Both write their own tables, so neither joins the metadata save. Last rather than first so a refusal keeps the editor open with the staged edits still on screen, while the field edits have landed.
There is no row until the commit mints one; the id keys the type draft and draws the row. Consequence: the accessibility identifier changes at Save, and the UI journey re-reads it.
Their suites pin the refusals and a dev-only fixture path still calls addLink. Note: updateSeries is in the same position (no app caller) and is not mentioned.
A staged removal only means something while the row is still there. With reloadPresentation gone no path replaces the presentation under an open editor, so the work-editor half of the pruning is defensive.
It was the one reader action with no Save at all; a checkmark that only turns on is a control the reader cannot undo.
EditButton's Done is not a save (no discard beside it; absent on the Mac), so the pair is the screen's own and is drawn only while hasUnsavedOrder.
The ticket named only the removal, but the staged-member machinery covers an addition for free; the prefill is raised past staged additions through SeriesPosition.next.
CreatorRolesView (Save/Cancel) and MoveToView (Move, beside an existing label-less Button(role: .close)) use Button("…"). Every other editor's confirmation/cancellation pair is Button(role:) with the word on the accessibility label. No decision records the deviation.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| minor | LibraryRepository+WorkLinks.swift commitLinkEdits | The .add/.retype/.remove arms are line-for-line copies of addLink/retypeLink/removeLink's locked bodies (directory fetch, workGroups, recordNotFound loop, firstTorn, link(over:and:) → alreadyLinked, insert; requireLink → tornEnd → mutate/delete). The header and Q5 call the singulars 'primitives', but the batch does not compose them, so each refusal path now has two spellings. | Extract three context-level helpers returning WorkLinkError? and call them from both the singular writes and the batch; pass the type directory in once (also removes the per-operation workTypeDirectory fetch). Branch not modified per instructions. |
| minor | LibraryRepository+Series.swift commitSeriesEdits / SeriesModelsTests | The doc comment, the model comment and the test comment say a membership changed elsewhere is 'the edit conflict Req 2.4 asks for'. resolveWorkWriteTarget → redirectWork consults the basis only on the post-collapse redirect; when the row is present the write is last-writer-wins on the pair. updateWork has always behaved this way (specs/to-read/design.md says so), so this is inherited and the new call is strictly narrower than the old loop — but the words overstate it. | Reword the three comments to say the basis drives the redirect and torn refusal only, or add a presented-membership comparison inside the lock with a new WriteConflict case. Not a regression. |
| minor | WorkDetailModel.stagedLinkEdits / commitLinkEdits remove-then-add | The model orders removals first 'so a reader who unlinked a work and linked it again is not refused by their own stored row'. Whether link(over:and:) excludes a pending context.delete is untested ([.remove(x), .add(samePair)] has no Core case), and the path is unreachable: the picker reads linkCandidates from the store, so a staged-removed work is still 'Already linked' (disabled) and a staged-added one is still offered and refused by the model's alreadyLinked check. | Add the Core test for the exact sequence; either derive the picker's 'Already linked' from the draft links so the sequence is reachable, or drop the comment's claim. |
| minor | WorkDetailModel.commitEditing link-type validation timing | A stored link's type field edited to an invalid value is emitted as .retype ((try? validate) != stored is true for nil) and refused only in commitLinkStep, after the URL, metadata and record steps have committed. Before this branch commitLinkType refused it on submit. Q3 accepts a late store refusal; a validation refusal is knowable before the first write, as SeriesDetailModel.save() does for positions. | Validate every link-type draft at the top of commitEditing() before the URL step, with a test 'an invalid link type draft refuses the save before anything is written'. |
| minor | AsterismTests/WorkDetailModelTests.swift:1846, 1936 | Two `await model.addLink(...)` calls remain on the now-synchronous method. Swift warns 'no async operations occur within await expression' on a cold build; the run here was warm so the warning did not surface, but the report claims no new warnings. | Drop the two awaits. |
| minor | specs/to-read/design.md:89 | 'Move To commits on the tap (T-2328); promotion is part of that commit.' is now false — Move To commits on its toolbar Move. | Reword to 'Move To commits on its Move (T-2328)'. |
| minor | CreatorRolesView orderToolbarItems / MoveToView Move | Text-labelled Button("Save")/Button("Cancel")/Button("Move") in confirmation/cancellation placements. polish-and-export Q55 makes every editor's pair the label-less Button(role: .confirm/.close) glyph with the word on the accessibility label (SeriesDetailView, WorkDetailView, CreatorDetailView, NewWorkView all do). MoveToView now mixes a glyph X with a text Move in one bar. | Use the glyph pair, or record the deviation in Q99/Q1 if the text was deliberate (the roles list is not a mode). |
| minor | LibraryRepository+Series.swift updateSeries | No app caller remains (only MockLibraryProvider, SeriesRepositoryTests, BackupV15ArchiveTests). commitSeriesEdits duplicates its row loop with a value guard updateSeries lacks, so a no-op rename stamps modifiedAt in one path and not the other; the position guard is byte-identical to updateWork's. Q5 does not mention it. | Share a value-guarded writeSeriesRows helper (and a SeriesPosition storable check with updateWork), or fold updateSeries into commitSeriesEdits(members: []) and say so in Q5. |
| minor | Packages/.../MembershipRemovalTests oneRefusalRefusesTheSet | Removes both sites of twoSiteFixture(), so the last-site guard would throw even if the notes-on-site check inside a batch were broken; the test cannot tell which refusal fired. Also removeSiteMemberships now checks notes before last-site per hostname, the reverse of the old singular, while the comment says 'the two refuse alike' — unreachable from the editor, untested. | Use a three-site fixture (one holding entries, two free) or assert the reason string; keep the last-site guard first or say the order changed. |
| minor | Q6 pruning / applying(_:to:) test coverage | SeriesDetailModel.load()'s staged-set pruning is reachable via the generation bump and untested; WorkDetailModel.load()'s is unreachable mid-edit (defensive). CreatorRolesModel.applying is only tested with the same two rows — no case for a read that adds a role (lands at the end, hasUnsavedOrder stays true) or drops a staged one. MoveToModelTests has no failed-submit-then-retry case. | Add the three cheap model tests; reword Q6 to say the work-editor half is defensive. |
| minor | SeriesUITests.testTheSeriesEditorRepositionsAddsAndRemovesMembers | Its add→remove→X segment now never writes (the add is staged, the remove drops the staging), and no UI journey saves a staged addition (Q76's path). The report's verification list omits this suite. | Run it (done here — see Tests/double-check), and consider saving the addition then removing it in a second pass, as the link journey does. |
| nit | WorkDetailModel.removeMembership URL re-selection | Hand-rolls `selectedWorkURLHostname = hostnames.first ?? ""` beside the existing resetWorkURLHostnameIfNeeded(), whose fallback is work?.primaryHostname and is not staging-aware — so two rules with different fallbacks now exist. | Make resetWorkURLHostnameIfNeeded read the staged-aware hostnames and call it from removeMembership. |
| nit | WorkDetailModel.hasUnsavedLinkChanges | Public and read by nothing (no view, no test); commitEditing uses !linkOperations.isEmpty directly. | Remove it. |
| nit | MockLibraryProvider dead recorders | lastAddedLink, lastRetypedLink, lastRemovedLinkID, lastUpdatedSeries, updateSeriesResult are written and never read; removedSiteMemberships survives only for two .isEmpty checks that could read removedSiteMembershipBatches. | Drop the unread recorders. |
| nit | Efficiency: per-operation directory fetches and onMutation count | commitLinkEdits fetches workTypeDirectory (and this work's group) once per operation; commitSeriesEdits re-fetches the directory per member via resolveWorkWriteTarget (deleteSeries in the same file hoists it). WorkDetailModel.commitEditing can call onMutation() up to three times per Save (URL, metadata, tail) — pre-existing shape, tail condition widened here. Sessions are 1–3 operations, so absolute cost is small. | Hoist the directory read; optionally give save(reloading:) a publishing flag. Follow-up only. |
| nit | Small duplications | SeriesDetailModel.save() inlines parsedPositionDraft(for:) ('the one place a typed position becomes a number'); commitLinkEdits computes the sorted pair twice (WorkPairKey already has lower/higher); applying(_:to:) builds a Dictionary used only as a Set; addMember's `staged.isEmpty ? stored : max(...)` reduces to max(...); staged links carry modifiedAt: .distantFuture while the comment says 'the moment it is drawn at'; StagedLink.otherTitle is non-optional so a title-less staged link reads isResolved == true; 'removeSiteMembership' (singular) is the operation label six times inside the plural. | Tidy in a follow-up. |
| nit | Decision-log wording | Status values 'accepted, superseding Q24' / 'accepted, superseding the last clause of Q57' are not among the format's enumerated values. Q74/Q75 in series-and-related-works still describe the pre-Decision-8/9 mechanism as current. CLAUDE.md's 'Nothing runs before Save' list of prefilled-with-marker cases could now name the suggested Work URL. | Optional wording passes. |
Source: local run at 2026-09-22T19:15:41+10:00 · snapshot 1f379a0f4b327974dfb47e6f4ebbbd4bb2278979
Baseline: none
Execution: failed · JUnit: 1 file · Coverage: 1 file · Baseline: absent
Coverage scope: every test in the repository
Totals: 2998 passed · 11 failed · 50 skipped · 0 errored · 0 flaky
| Suite | Test | Job or artifact | Message |
|---|---|---|---|
| AsterismCoreTests.ShareCaptureFlowTests | escalationCountsSetAsideButNamesWaiting() | — | 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.ShareCaptureFlowTests | terminationLeavesTheRecord() | — | Expectation failed: waiting.map(\.id) == [preservedID] (error) |
| AsterismCoreTests.ShareCaptureFlowTests | aFailedOpenLeavesItsRecordDrainable() | — | Expectation failed: try await reopened.pending().first (error) |
| AsterismCoreTests.ShareCaptureFlowTests | aLiveSheetHoldsItsRecord() | — | Expectation failed: try await reopened.pending().first (error) |
| AsterismCoreTests.ShareCaptureFlowTests | theHoldLapses() | — | Expectation failed: try await reopened.pending().first (error) |
| AsterismCoreTests.ShareCaptureFlowTests | deleteIsRetriedOnceThenGivesUp() | — | Expectation failed: await spool.discardPreserved(id: Self.recordID) == false (error) |
| AsterismCoreTests.ShareCaptureFlowTests | refusalAtTheBoundIsNotSaved() | — | Expectation failed: waiting.count == 1 (error) |
| AsterismCoreTests.ShareCaptureFlowTests | everyFailedOpenArmSavesForLater(failure:) | — | Expectation failed: waiting.map(\.id) == [preservedID] (error) |
| AsterismCoreTests.ShareCaptureFlowTests | preservesBeforeOpening() | — | Expectation failed: waitingAtOpen == 1 (error) |
| AsterismCoreTests.ShareCaptureFlowTests | confirmationEscalates() | — | Expectation failed: message.contains("\(PendingCaptureBounds.escalationThreshold) captures are waiting") (error) |
| AsterismCoreTests.ShareCaptureFlowTests | theHoldIsStampedBeforeTheOpen() | — | Expectation failed: try await reopened.pending().first (error) |
Derived by declaration name, from the diff (no baseline run).
Aggregate diff coverage: 96% (428 of 447 measurable added lines).
Head 91.8% (97499 of 106226 lines)
8 of 35 changed files matched coverage data.
Asterism/Asterism/ViewModels/CreatorRolesModels.swift — no candidateAsterism/Asterism/ViewModels/MoveToModel.swift — no candidateAsterism/Asterism/ViewModels/SeriesModels.swift — no candidateAsterism/Asterism/ViewModels/WorkDetailModel.swift — no candidateAsterism/Asterism/Views/CreatorRolesView.swift — no candidateAsterism/Asterism/Views/MoveToView.swift — no candidateAsterism/Asterism/Views/RelatedWorkEditorView.swift — no candidateAsterism/Asterism/Views/SeriesDetailView.swift — no candidateAsterism/Asterism/Views/WorkDetailView.swift — no candidateAsterism/AsterismTests/AppLibraryModelTests.swift — no candidateAsterism/AsterismTests/CreatorRolesModelTests.swift — no candidateAsterism/AsterismTests/Helpers/MockLibraryProvider.swift — no candidateAsterism/AsterismTests/MoveToAndNewWorkModelTests.swift — no candidateAsterism/AsterismTests/SeriesModelsTests.swift — no candidateAsterism/AsterismTests/WorkDetailCreditsTests.swift — no candidateAsterism/AsterismTests/WorkDetailModelTests.swift — no candidateAsterism/AsterismTests/WorkURLDetailModelTests.swift — no candidateAsterism/AsterismUITests/AccessibilityJourneyUITests.swift — no candidateAsterism/AsterismUITests/CreatorRolesSettingsUITests.swift — no candidateAsterism/AsterismUITests/StatsUITests.swift — no candidateAsterism/AsterismUITests/WorkDetailConnectionsUITests.swift — no candidateCLAUDE.md — no candidatespecs/bugfixes/edit-views-write-before-save/decision_log.md — no candidatespecs/bugfixes/edit-views-write-before-save/report.md — no candidatespecs/polish-and-export/decision_log.md — no candidatespecs/series-and-related-works/decision_log.md — no candidatespecs/work-creators/decision_log.md — no candidateFiles 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 5c5fb8f6c1c832914f07dc2c19ef2dc2a3794b6d.
Click to expand.
diff --git a/Asterism/Asterism/ViewModels/CreatorRolesModels.swift b/Asterism/Asterism/ViewModels/CreatorRolesModels.swiftindex e983d4dd..6047ebce 100644--- a/Asterism/Asterism/ViewModels/CreatorRolesModels.swift+++ b/Asterism/Asterism/ViewModels/CreatorRolesModels.swift@@ -58,9 +58,13 @@ public final class CreatorRolesModel { } public private(set) var state: State = .loading- /// The active roles, in the order the read returned them — `CreatorRoleOrdering`,- /// which is the reader's own list order (Req 2.5).+ /// The active roles in the order the **screen** shows them: the read's+ /// order — `CreatorRoleOrdering`, the reader's own list order (Req 2.5) —+ /// with this session's drags applied on top of it (T-2328). public private(set) var rows: [Row] = []+ /// The active roles as the read returned them, which is what Cancel puts+ /// back and what "has the reader moved anything" is measured against.+ private var loadedRows: [Row] = [] /// Req 2.1's second list: the roles the reader removed, kept so Req 2.2 can /// restore them. public private(set) var removedRows: [Row] = []@@ -102,13 +106,18 @@ public final class CreatorRolesModel { public func load() async { state = .loading+ // What the reader has dragged, kept across the read: an add or a sync+ // arrival must not silently undo a reorder they have not saved yet.+ let staged = hasUnsavedOrder ? rows.map(\.id) : [] do { let roles = try await library.creatorRoles().map(Row.init(role:))- rows = roles.filter { !$0.isRemoved }+ loadedRows = roles.filter { !$0.isRemoved }+ rows = Self.applying(staged, to: loadedRows) removedRows = roles.filter(\.isRemoved) state = .ready } catch { rows = []+ loadedRows = [] removedRows = [] state = .error(message: error.localizedDescription) Self.logger.error(@@ -116,6 +125,22 @@ public final class CreatorRolesModel { } } + /// Whether the list on screen is an order the store has not been told about+ /// (T-2328). The Save and Cancel controls exist exactly while this is true.+ public var hasUnsavedOrder: Bool { rows.map(\.id) != loadedRows.map(\.id) }++ /// A staged order re-applied over a fresh read: the rows the drag named, in+ /// the order it left them, then anything the read brought that the drag+ /// never saw — a role another device added goes to the end, which is where+ /// this screen's own add puts one.+ static func applying(_ staged: [UUID], to fresh: [Row]) -> [Row] {+ guard !staged.isEmpty else { return fresh }+ let position = Dictionary(+ uniqueKeysWithValues: staged.enumerated().map { ($0.element, $0.offset) })+ let known = staged.compactMap { id in fresh.first { $0.id == id } }+ return known + fresh.filter { position[$0.id] == nil }+ }+ /// Adds the typed name — or restores the removed role that already holds it /// (Req 2.2). ///@@ -149,25 +174,32 @@ public final class CreatorRolesModel { } } - /// Req 2.5's reorder, from the list's `.onMove`.+ /// Req 2.5's reorder, from the list's `.onMove`. **It writes nothing**+ /// (T-2328, Q99 of `work-creators`). ///- /// The rows move **locally first** and the write follows: a list that only- /// re-ordered once the repository answered would snap back under the- /// reader's finger for the length of a save. The repository is handed the- /// full active order rather than a pair of indices — it numbers the roles it- /// is given 0…n and drops any that resolve to a removed or merged row- /// (Q58), so the list the screen draws is the list that is written.- public func move(from source: IndexSet, to destination: Int) async {+ /// The drag moves the rows and stops there; the Save the screen raises is+ /// what sends the order, and Cancel puts the read's order back. The+ /// repository is handed the full active order rather than a pair of indices+ /// — it numbers the roles it is given 0…n and drops any that resolve to a+ /// removed or merged row (Q58), so the list the screen draws is the list+ /// that is written.+ public func move(from source: IndexSet, to destination: Int) { guard !isSubmitting else { return }- let reordered = Self.reordering(rows, from: source, to: destination)- let ids = reordered.map(\.id)- // A drag that ended where it started is not a write.- guard ids != rows.map(\.id) else { return }- rows = reordered+ message = nil+ rows = Self.reordering(rows, from: source, to: destination)+ }++ /// Writes the order the reader dragged the list into (Req 2.5, T-2328).+ public func saveOrder() async {+ guard !isSubmitting, hasUnsavedOrder else { return } isSubmitting = true defer { isSubmitting = false }+ message = nil do {- try await library.reorderCreatorRoles(ids: ids)+ try await library.reorderCreatorRoles(ids: rows.map(\.id))+ // The order is the store's now, so the read below has nothing to+ // carry over it.+ loadedRows = rows await committed() } catch { message = error.localizedDescription@@ -175,10 +207,18 @@ public final class CreatorRolesModel { "Creator role reorder failed: \(String(describing: error), privacy: .public)") // The order on screen is now a claim the store did not accept, so // the read puts back what it holds.+ rows = loadedRows await load() } } + /// Puts the read's order back, discarding the drags (T-2328).+ public func cancelOrder() {+ guard !isSubmitting else { return }+ message = nil+ rows = loadedRows+ }+ /// `RangeReplaceableCollection.move(fromOffsets:toOffset:)`, restated. /// /// That method is SwiftUI's, and a view model does not import SwiftUI: the
diff --git a/Asterism/Asterism/ViewModels/MoveToModel.swift b/Asterism/Asterism/ViewModels/MoveToModel.swiftindex 90465360..1db26df4 100644--- a/Asterism/Asterism/ViewModels/MoveToModel.swift+++ b/Asterism/Asterism/ViewModels/MoveToModel.swift@@ -24,6 +24,35 @@ public final class MoveToModel { public var newWorkTitle: String = "" + /// Where the reader has said the entry should go (T-2328).+ ///+ /// The sheet used to write on the destination tap, which made it the one+ /// reader action in the app with no Save at all. It is an editor now: the+ /// tap chooses, the draft holds the choice, and `submit()` — the sheet's+ /// Move — is the one write. Nothing is written by closing the sheet.+ ///+ /// `.newWork` carries no title: the field is `newWorkTitle`, which the+ /// reader may still be typing after they have chosen the row.+ public enum Destination: Equatable, Sendable {+ case existing(UUID)+ case newWork+ case unattached+ }++ public private(set) var selection: Destination?++ /// Whether Move has something to do: a destination, and — for a new+ /// work — a title to give it.+ public var canSubmit: Bool {+ guard !isSubmitting, state != .completed else { return false }+ switch selection {+ case .none: return false+ case .newWork:+ return !newWorkTitle.trimmingCharacters(in: .whitespaces).isEmpty+ case .existing, .unattached: return true+ }+ }+ private let entryID: UUID private let library: any LibraryProviding private let onMutation: @Sendable () async -> Void@@ -56,22 +85,28 @@ public final class MoveToModel { } } - /// Moves entry to an existing Work. Suppresses duplicate submissions.- public func moveToExisting(_ workID: UUID) async {- await submit(.existing(workID))- }-- /// Moves entry to a new Work. Suppresses duplicate submissions.- public func moveToNewWork() async {- await submit(.newWork(displayTitle: newWorkTitle))+ /// Chooses a destination. **Writes nothing** (T-2328).+ ///+ /// Choosing the row already chosen clears it, so the sheet has a way back+ /// to "no destination picked" that is not closing it.+ public func select(_ destination: Destination) {+ guard !isSubmitting, state != .completed else { return }+ errorMessage = nil+ selection = selection == destination ? nil : destination } - /// Leaves entry unattached. Suppresses duplicate submissions.- public func leaveUnattached() async {- await submit(.unattached)+ /// The sheet's one write: the staged destination, committed (T-2328).+ /// Suppresses duplicate submissions.+ public func submit() async {+ guard canSubmit, let selection else { return }+ switch selection {+ case .existing(let workID): await commit(.existing(workID))+ case .newWork: await commit(.newWork(displayTitle: newWorkTitle))+ case .unattached: await commit(.unattached)+ } } - private func submit(_ destination: WorkDestination) async {+ private func commit(_ destination: WorkDestination) async { guard !isSubmitting else { return } isSubmitting = true state = .submitting
diff --git a/Asterism/Asterism/ViewModels/SeriesModels.swift b/Asterism/Asterism/ViewModels/SeriesModels.swiftindex 7b5c8c31..356eef83 100644--- a/Asterism/Asterism/ViewModels/SeriesModels.swift+++ b/Asterism/Asterism/ViewModels/SeriesModels.swift@@ -203,7 +203,23 @@ public final class SeriesDetailModel { public private(set) var state: State = .loading public private(set) var display: SeriesDisplay? public private(set) var notes: String = ""- public private(set) var members: [MemberRow] = []+ /// The members the read returned, before this session's staged edits.+ private var loadedMembers: [MemberRow] = []+ /// The members the editor staged the removal of (Req 2.6, T-2328).+ private var stagedRemovals: Set<UUID> = []+ /// The works the editor staged into the series (Req 2.5, T-2328), in the+ /// order the reader added them.+ private var stagedAdditions: [MemberRow] = []++ /// The list the screen draws: the read, **with this session's staged edits+ /// applied** (T-2328).+ ///+ /// A staged removal is gone from it and a staged addition is at the end of+ /// it, and both are claims until Save writes them — the same shape the work+ /// editor's link section takes.+ public var members: [MemberRow] {+ loadedMembers.filter { !stagedRemovals.contains($0.id) } + stagedAdditions+ } /// The add-member search's rows (Req 2.5), read on demand: the picker is a /// sheet, and a whole-library read has no business running behind a screen /// that is not showing it.@@ -275,20 +291,29 @@ public final class SeriesDetailModel { guard let detail = try await library.seriesDetail(id: seriesID) else { display = nil notes = ""- members = []+ loadedMembers = []+ stagedRemovals = []+ stagedAdditions = [] positionDrafts = [:] state = .missing return } display = detail.display notes = detail.notes- members = detail.members.map { work in+ loadedMembers = detail.members.map { work in MemberRow( work: work, positionText: work.membership .map { SeriesPosition.format($0.position, locale: locale) } ?? "", isCurrent: work.id == originWorkID) }+ // A staged edit only means something while the row it names is+ // still what the read says it is: a member another device removed+ // drops out of the staging with it, and a work that arrived in this+ // series is no longer this session's to add.+ let present = Set(loadedMembers.map(\.id))+ stagedRemovals.formIntersection(present)+ stagedAdditions.removeAll { present.contains($0.id) } seedPositionDrafts() state = .ready } catch {@@ -325,6 +350,8 @@ public final class SeriesDetailModel { guard state == .ready else { return } message = nil refusedPositionRowID = nil+ stagedRemovals = []+ stagedAdditions = [] draftName = display?.name ?? "" draftNotes = notes positionDrafts = Dictionary(uniqueKeysWithValues: members.map { ($0.id, $0.positionText) })@@ -339,6 +366,10 @@ public final class SeriesDetailModel { refusedPositionRowID = nil draftName = "" draftNotes = ""+ // T-2328: the staged removals and additions are drafts like the typed+ // fields, and the discard puts the member list back as the read left it.+ stagedRemovals = []+ stagedAdditions = [] positionDrafts = Dictionary(uniqueKeysWithValues: members.map { ($0.id, $0.positionText) }) } @@ -433,11 +464,13 @@ public final class SeriesDetailModel { /// The editor's one way out that writes (Reqs 1.2, 2.6). ///- /// The name and notes go first, because an invalid name must stop the whole- /// commit; the positions then commit **one row at a time, in list order**- /// (Q25). The first refusal stops the sequence: the rows before it stay- /// committed, the rows after it are never asked, and the screen re-reads so- /// it shows what actually landed.+ /// **One repository call, one save** (T-2328, Decision 9). It used to+ /// write the name and then loop over the members with a separate write+ /// each, so an unparseable position halfway down left the name written and+ /// some positions written and others not; and the removals did not wait for+ /// it at all. Now every position is parsed before anything is sent, the+ /// first refusal stops the commit with nothing written, and the name, the+ /// notes, the position edits, the removals and the additions land together. public func save() async { guard !isSubmitting else { return } guard canSave else {@@ -450,88 +483,143 @@ public final class SeriesDetailModel { message = nil // This tap is a fresh attempt; the last one's refusal is history. refusedPositionRowID = nil-- var wrote = false- if SeriesName.trimmed(draftName) != (display?.name ?? "")- || SeriesName.trimmed(draftNotes) != notes {- do {- try SeriesName.validate(draftName)- try await library.updateSeries(- id: seriesID, name: draftName, notes: draftNotes)- wrote = true- } catch {- message = SeriesRefusalPresentation.sentence(for: error)- Self.logger.error(- "Series update failed: \(String(describing: error), privacy: .public)")- return- }+ do {+ try SeriesName.validate(draftName)+ } catch {+ message = SeriesRefusalPresentation.sentence(for: error)+ return } + var edits: [SeriesMemberEdit] = []+ // In list order, stopping at the first refusal, which is what+ // `refusalTarget` promises: the row it marks is the first the reader+ // would meet. Nothing has been sent at this point, so a refusal here+ // leaves the whole editor exactly as it was. for row in members {- guard positionDrafts[row.id] != nil else { continue }- guard let position = parsedPositionDraft(for: row.id) else {+ guard let typed = positionDrafts[row.id] else { continue }+ guard let position = SeriesPosition.parse(typed, locale: locale) else { // Under the row's own field, not in the bottom message row: the // refusal names a position, and the reader has to be told which. refusedPositionRowID = row.id- if wrote { await committed() } return }- guard let current = row.work.membership,- SeriesPosition.rounded(current.position) != position- else { continue }- let landed = await write(- row.work, membership: SeriesMembership(seriesID: seriesID, position: position))- wrote = wrote || landed- guard landed else {- if wrote { await onMutation() }- await load()+ // A member whose position is already what the draft says contributes+ // no edit: the commit is value-guarded too, and this keeps the call+ // itself honest about what the session changed.+ if let current = row.work.membership, current.seriesID == seriesID,+ SeriesPosition.rounded(current.position) == position {+ continue+ }+ edits.append(+ SeriesMemberEdit(+ workID: row.id, basis: WorkEditBasis(work: row.work),+ membership: SeriesMembership(seriesID: seriesID, position: position)))+ }+ // Req 2.6: a staged removal is the member leaving the series, sent as+ // the nil membership the commit writes as a pair.+ for row in loadedMembers where stagedRemovals.contains(row.id) {+ edits.append(+ SeriesMemberEdit(+ workID: row.id, basis: WorkEditBasis(work: row.work), membership: nil))+ }++ // Req 5.6's dirty-only save, this screen's half of it: a confirmation+ // with nothing left to write takes no lock and publishes no mutation.+ // The commit is value-guarded too; this is the editor not asking.+ guard !edits.isEmpty+ || SeriesName.trimmed(draftName) != (display?.name ?? "")+ || SeriesName.trimmed(draftNotes) != notes+ else {+ stagedRemovals = []+ stagedAdditions = []+ isEditing = false+ return+ }++ do {+ let outcome = try await library.commitSeriesEdits(+ seriesID: seriesID, name: draftName, notes: draftNotes, members: edits)+ if case .conflict(let conflict) = outcome {+ // Req 2.4's refusal, and nothing was written: the drafts stay+ // exactly as the reader left them, as they do in the work+ // editor (Q68 — never a `load()` here, which would reassign+ // every draft on the screen).+ message = EntryDetailModel.conflictMessage(conflict) return }+ } catch {+ message = SeriesRefusalPresentation.sentence(for: error)+ Self.logger.error(+ "Series save failed: \(String(describing: error), privacy: .public)")+ return } - if wrote { await committed() }+ stagedRemovals = []+ stagedAdditions = [] isEditing = false+ await committed() } // MARK: - Membership (Reqs 2.5, 2.6, 2.8) - /// Req 2.6: the work leaves the series and stays in the library. Committed- /// on the tap rather than folded into the draft — it is a removal, not a- /// field being typed.- public func removeMember(_ workID: UUID) async {- guard let row = members.first(where: { $0.id == workID }) else { return }- guard !isSubmitting else { return }- isSubmitting = true- defer { isSubmitting = false }+ /// Req 2.6: the work leaves the series and stays in the library — **staged+ /// in the draft**, written by Save (T-2328).+ ///+ /// A work this session staged into the series is simply dropped: there is+ /// nothing in the store to remove.+ public func removeMember(_ workID: UUID) {+ guard isEditing else { return } message = nil- if await write(row.work, membership: nil) {- await committed()- } else {- await load()+ if stagedAdditions.contains(where: { $0.id == workID }) {+ stagedAdditions.removeAll { $0.id == workID }+ positionDrafts[workID] = nil+ return }+ guard loadedMembers.contains(where: { $0.id == workID }) else { return }+ stagedRemovals.insert(workID)+ positionDrafts[workID] = nil+ if refusedPositionRowID == workID { refusedPositionRowID = nil } } - /// Req 2.5: the chosen work takes the position Req 2.3 prefills — the next- /// whole number above this series' highest, which the repository computes- /// from the presented memberships.+ /// Req 2.5: the chosen work joins the list at the position Req 2.3+ /// prefills — the next whole number above this series' highest — and Save+ /// is what writes it (T-2328).+ ///+ /// The prefill is the repository's number, raised past anything this+ /// session has already staged: two works added before a save must not both+ /// land on the same position. public func addMember(_ workID: UUID) async {+ guard isEditing else { return }+ guard !isSubmitting else { return }+ message = nil+ // A member staged for removal and then chosen again is the reader+ // undoing themselves, not a second membership.+ if stagedRemovals.contains(workID) {+ stagedRemovals.remove(workID)+ if let row = loadedMembers.first(where: { $0.id == workID }) {+ positionDrafts[workID] = row.positionText+ }+ return+ }+ guard !members.contains(where: { $0.id == workID }) else { return } guard let candidate = candidates.first(where: { $0.id == workID }), candidate.unavailableReason == nil else { return }- guard !isSubmitting else { return } isSubmitting = true defer { isSubmitting = false }- message = nil do {- let position = try await library.nextSeriesPosition(seriesID: seriesID)- if await write(- candidate.work,- membership: SeriesMembership(seriesID: seriesID, position: position))- {- await committed()- } else {- await load()- }+ let stored = try await library.nextSeriesPosition(seriesID: seriesID)+ // The repository only knows the saved members, so apply its own+ // rule (`SeriesPosition.next`: next whole number above the highest)+ // to the positions staged here and take the higher of the two.+ let staged = stagedAdditions.compactMap { parsedPositionDraft(for: $0.id) }+ let position = staged.isEmpty ? stored : max(stored, SeriesPosition.next(after: staged))+ let text = SeriesPosition.format(position, locale: locale)+ stagedAdditions.append(+ MemberRow(+ work: candidate.work, positionText: text,+ isCurrent: candidate.work.id == originWorkID))+ positionDrafts[workID] = text } catch { message = error.localizedDescription Self.logger.error(@@ -582,43 +670,6 @@ public final class SeriesDetailModel { // MARK: - Writes - /// One member edit, as `updateWork` (Q25): the basis and the draft are built- /// from the member's own snapshot, so every other field goes back unchanged- /// and a field changed elsewhere is the edit conflict Req 2.4 asks for.- ///- /// Returns whether the write landed.- private func write(_ work: WorkSnapshot, membership: SeriesMembership?) async -> Bool {- do {- let outcome = try await library.updateWork(- id: work.id,- basis: WorkEditBasis(work: work),- draft: WorkMetadataDraft(- displayTitle: work.displayTitle,- typeAssignment: work.typeDisplay.assignment,- genreTags: work.genreTags,- genericNotes: work.genericNotes,- workStatus: work.workStatus,- readingStatus: work.readingStatus,- verdict: work.verdict,- // `update-schedule` Req 1.7: a position edit is a write to- // the work's whole metadata, so the schedule has to be sent- // back exactly as it was loaded or this save would clear it.- releaseDays: work.releaseDays,- membership: membership,- thumbnail: .keep))- if case .conflict(let conflict) = outcome {- message = EntryDetailModel.conflictMessage(conflict)- return false- }- return true- } catch {- message = error.localizedDescription- Self.logger.error(- "Series membership write failed: \(String(describing: error), privacy: .public)")- return false- }- }- private func committed() async { await onMutation() await load()
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel.swift b/Asterism/Asterism/ViewModels/WorkDetailModel.swiftindex 5abe2231..3d6e9b00 100644--- a/Asterism/Asterism/ViewModels/WorkDetailModel.swift+++ b/Asterism/Asterism/ViewModels/WorkDetailModel.swift@@ -299,9 +299,6 @@ public final class WorkDetailModel { /// series this device cannot show (Req 5.2). public var isSeriesResolved: Bool { work?.series?.isResolved == true } - /// Req 8.1's section, off the same read as everything else on the screen.- public var links: [WorkLinkSnapshot] { presentation?.links ?? [] }- /// Req 8.2's picker rows and Req 7.1's vocabulary, read on demand: both are /// whole-library reads that have no business running behind a screen that is /// not showing them.@@ -349,9 +346,8 @@ public final class WorkDetailModel { /// The credits **as they stood when the draft was seeded**, which is what a /// commit is measured against (Req 3.5, Q52). ///- /// Not `presentation?.credits`: a link edit re-reads the presentation from- /// inside edit mode (`reloadPresentation()`), so a credit another device- /// added between the seeding and the save would join the live read — and+ /// Not `presentation?.credits`: a read landing from inside edit mode would+ /// otherwise let a credit another device added join the live read — and /// with it `seenRowIDs`, whose whole job is to say what the editor *saw*. /// A row it never saw would then be deleted by a draft that never listed /// it, which is precisely the last-writer-wins-per-credit rule Q52 exists@@ -453,7 +449,7 @@ public final class WorkDetailModel { (presentation, chapterRowsByChapter) = (detail, Self.chapterOrder(detail.chapterRows)) let snapshot = detail.work coverFetchPages = Self.coverFetchPages(of: snapshot)- removableHostnames = Self.removableHostnames(of: snapshot)+ loadedRemovableHostnames = Self.removableHostnames(of: snapshot) draftTitle = snapshot.displayTitle draftAssignment = snapshot.typeDisplay.assignment typeOptions = await pickerOptions(carrying: snapshot.typeDisplay)@@ -476,6 +472,12 @@ public final class WorkDetailModel { seriesOptions = await seriesPickerOptions(carrying: snapshot.series) restoreCreditDraftFromPresentation() await reloadRoleOptions()+ // T-2328: a staged removal only means something while the row it+ // names is still there. A link another device removed, or a site a+ // merge took off, drops out of the staging with it.+ removedLinkIDs.formIntersection(Set(detail.links.map(\.id)))+ stagedMembershipRemovals.formIntersection(+ Set(snapshot.memberships.map(\.hostname))) seedLinkTypeDrafts(detail.links) adoptRecordDrafts(detail.characters + detail.places) // Before the projection below, which is *about* the selected site.@@ -1444,14 +1446,57 @@ public final class WorkDetailModel { } } - // MARK: - Related works (Reqs 8.1–8.4, Q24)+ // MARK: - Related works (Reqs 8.1–8.4, Decision 8)++ /// A link the editor has staged but not created (T-2328).+ ///+ /// It carries no store identity — there is no row yet — so the `id` is a+ /// draft-local UUID, minted here and never written. It is what keys the+ /// type draft, so a staged link can be retyped before it exists, and it is+ /// what the section draws the row with.+ private struct StagedLink: Equatable {+ let id: UUID+ let otherWorkID: UUID+ let otherTitle: String+ }++ /// The links the editor staged, in the order the reader added them.+ private var stagedLinks: [StagedLink] = []+ /// The stored links the editor staged a removal of.+ private var removedLinkIDs: Set<UUID> = []++ /// Req 8.1's section, off the same read as everything else on the screen —+ /// **with this session's staged edits applied** (Decision 8).+ ///+ /// A staged removal is gone from the list, a staged add is at the end of it,+ /// and both are only claims until Save. The types come from the drafts, so a+ /// retyped link reads as retyped before it is written.+ public var links: [WorkLinkSnapshot] {+ let stored = (presentation?.links ?? [])+ .filter { !removedLinkIDs.contains($0.id) }+ .map { link in+ WorkLinkSnapshot(+ id: link.id, otherWorkID: link.otherWorkID, otherTitle: link.otherTitle,+ linkType: linkTypeDraft(for: link.id), modifiedAt: link.modifiedAt)+ }+ // A staged link's `modifiedAt` is the moment it is drawn at, which is+ // the only honest answer: it has no row and so no stamp. Nothing reads+ // it — the merge basis is built by the repository from stored rows.+ return stored+ + stagedLinks.map {+ WorkLinkSnapshot(+ id: $0.id, otherWorkID: $0.otherWorkID, otherTitle: $0.otherTitle,+ linkType: linkTypeDraft(for: $0.id), modifiedAt: .distantFuture)+ }+ } private func seedLinkTypeDrafts(_ links: [WorkLinkSnapshot]) { // The drafts a reader has typed survive a re-read; only rows without one // take theirs from the store — `SeriesDetailModel.seedPositionDrafts`'- // rule, for the same reason: a link edit re-reads the section, and- // re-seeding unconditionally would clear a half-typed type.- let present = Set(links.map(\.id))+ // rule, for the same reason: a re-read from a sync arrival must not+ // clear a half-typed type. A staged link's draft is kept whatever the+ // store holds: there is no row for it to be seeded from.+ let present = Set(links.map(\.id)).union(stagedLinks.map(\.id)) linkTypeDrafts = linkTypeDrafts.filter { present.contains($0.key) } for link in links where linkTypeDrafts[link.id] == nil { linkTypeDrafts[link.id] = link.linkType@@ -1488,81 +1533,107 @@ public final class WorkDetailModel { } } - public func addLink(to otherWorkID: UUID, type: String) async {+ /// Stages a link to another work. Nothing is written until Save+ /// (Decision 8).+ ///+ /// The type is validated here so a typo is refused where it was typed, and+ /// the pair is checked against the list the reader is looking at — the+ /// picker's candidates were read before this session staged anything, so+ /// the work they just added is still offered.+ public func addLink(to otherWorkID: UUID, type: String) { errorMessage = nil+ let validated: String do {- try LinkType.validate(type)+ validated = try LinkType.validate(type) } catch { errorMessage = SeriesRefusalPresentation.sentence(for: error) return }- await commitLinkEdit("Link add") {- _ = try await self.library.addLink(between: self.workID, and: otherWorkID, type: type)+ guard otherWorkID != workID else {+ errorMessage = SeriesRefusalPresentation.sentence(for: WorkLinkError.selfLink)+ return }+ if let existing = links.first(where: { $0.otherWorkID == otherWorkID }) {+ errorMessage = SeriesRefusalPresentation.sentence(+ for: WorkLinkError.alreadyLinked(type: existing.linkType))+ return+ }+ let id = UUID()+ stagedLinks.append(+ StagedLink(+ id: id, otherWorkID: otherWorkID,+ otherTitle: linkCandidates.first { $0.id == otherWorkID }?.work.displayTitle+ ?? WorkLinkSnapshot.unresolvedTitle))+ linkTypeDrafts[id] = validated } - /// Req 6.5: the type the field holds becomes the link's, on the spot.- ///- /// A type equal to the one already stored writes nothing — a field the- /// reader tabbed through is not an edit, and a write would stamp the link's- /// modification time for nothing (Q27 reads it).- public func commitLinkType(for linkID: UUID) async {- guard let link = links.first(where: { $0.id == linkID }) else { return }+ /// Stages a link's removal. A link this session staged is simply dropped —+ /// there is nothing to remove from the store.+ public func removeLink(id: UUID) { errorMessage = nil- let typed: String- do {- typed = try LinkType.validate(linkTypeDraft(for: linkID))- } catch {- errorMessage = SeriesRefusalPresentation.sentence(for: error)+ if stagedLinks.contains(where: { $0.id == id }) {+ stagedLinks.removeAll { $0.id == id }+ linkTypeDrafts[id] = nil return }- guard typed != link.linkType else { return }- await commitLinkEdit("Link retype") {- try await self.library.retypeLink(id: linkID, type: typed)- }+ guard (presentation?.links ?? []).contains(where: { $0.id == id }) else { return }+ removedLinkIDs.insert(id) } - public func removeLink(id: UUID) async {- errorMessage = nil- await commitLinkEdit("Link removal") {- try await self.library.removeLink(id: id)+ /// Whether this session has staged anything the link commit would write.+ public var hasUnsavedLinkChanges: Bool { !stagedLinkEdits().isEmpty }++ /// The session's link edits, in one deterministic order: removals, then+ /// retypes, then adds.+ ///+ /// Removals go first so a reader who unlinked a work and linked it again+ /// under another type is not refused by their own stored row. A retype is+ /// emitted only where the draft differs from what the store holds, so a+ /// field the reader tabbed through stamps nothing (Q27 reads that stamp).+ private func stagedLinkEdits() -> [WorkLinkEditOperation] {+ let stored = presentation?.links ?? []+ var operations: [WorkLinkEditOperation] = []+ for link in stored where removedLinkIDs.contains(link.id) {+ operations.append(.remove(linkID: link.id)) }+ for link in stored where !removedLinkIDs.contains(link.id) {+ let typed = linkTypeDraft(for: link.id)+ guard (try? LinkType.validate(typed)) != link.linkType else { continue }+ operations.append(.retype(linkID: link.id, type: typed))+ }+ for staged in stagedLinks {+ operations.append(+ .add(otherWorkID: staged.otherWorkID, type: linkTypeDraft(for: staged.id)))+ }+ return operations } - /// One link write and the re-read behind it.+ /// One repository call for the whole session's link edits (Decision 8). ///- /// The re-read is `reloadPresentation()`, **not** `load()`: a link edit- /// commits outside the work's own draft (Q24), and the reader may be- /// standing in the editor with a half-typed title. Replacing the drafts here- /// would throw that away as the price of removing a link.- private func commitLinkEdit(- _ operation: String, _ write: @MainActor () async throws -> Void- ) async {+ /// Returns whether it landed. A refusal keeps the editor open with the+ /// staged edits intact — they are the only copy of themselves — and says+ /// what happened in the sentence the link refusals have always used.+ private func commitLinkStep(_ operations: [WorkLinkEditOperation]) async -> Bool {+ guard !operations.isEmpty else { return true } do {- try await write()- await onMutation()- await reloadPresentation()+ try await library.commitLinkEdits(workID: workID, operations: operations)+ stagedLinks = []+ removedLinkIDs = []+ return true } catch { errorMessage = SeriesRefusalPresentation.sentence(for: error) Self.logger.error(- "\(operation, privacy: .public) failed: \(String(describing: error), privacy: .public)")+ "Link commit failed: \(String(describing: error), privacy: .public)")+ return false } } - /// Re-reads the screen and leaves every draft where it was.- ///- /// The half of `load()` that describes the store, without the half that- /// describes the reader.- private func reloadPresentation() async {- do {- let detail = try await library.workDetail(id: workID)- (presentation, chapterRowsByChapter) = (detail, Self.chapterOrder(detail.chapterRows))- coverFetchPages = Self.coverFetchPages(of: detail.work)- seedLinkTypeDrafts(detail.links)- } catch {- Self.logger.error(- "Work re-read failed: \(String(describing: error), privacy: .public)")- }+ /// Puts the link drafts back where the load left them (the editor's cancel).+ private func restoreLinkDraftsFromPresentation() {+ stagedLinks = []+ removedLinkIDs = []+ linkTypeDrafts = [:]+ seedLinkTypeDrafts(presentation?.links ?? []) } // MARK: - Which site the URL machinery is about (Req 3.6, Q8)@@ -1587,7 +1658,22 @@ public final class WorkDetailModel { /// machinery's site picker (one entry is not a choice, and no picker is /// drawn), the review menu (Q33), what can be removed (Req 7.2), and the /// removal buttons themselves.- public var hostnames: [String] { work?.memberships.map(\.hostname) ?? [] }+ ///+ /// **After** this session's staged removals (T-2328): a site the reader has+ /// taken off is off every list that asks, which is what makes the removal+ /// visible before it is written.+ public var hostnames: [String] {+ (work?.memberships.map(\.hostname) ?? []).filter {+ !stagedMembershipRemovals.contains($0)+ }+ }++ /// The sites this edit session has staged the removal of (T-2328). Emptied+ /// by a cancel and by the commit that writes them.+ private var stagedMembershipRemovals: Set<String> = []++ /// Whether this session has staged a site removal the save would write.+ public var hasUnsavedMembershipRemovals: Bool { !stagedMembershipRemovals.isEmpty } /// Moves the URL machinery to another of the Work's sites and re-projects. ///@@ -1630,26 +1716,47 @@ public final class WorkDetailModel { } } - /// Accepts the suggested URL, which is a commit of its own.+ /// Puts the suggested URL in the field. **It writes nothing** (T-2328,+ /// Decision 6 of `polish-and-export`). ///- /// It stays an immediate write (Q57) because the request it sends —- /// `.confirmCandidate` — is the reader approving *that exact suggested- /// value*, which is not a thing a free-text draft can express.- public func confirmWorkURLCandidate() async {+ /// Q57 kept this as an immediate write because `.confirmCandidate` is the+ /// reader approving *that exact projected value*. It is: and the value it+ /// approves is a string, which the field holds perfectly well. The ordinary+ /// Save writes it as `.replaceManual`, which — the planner's two arms are+ /// one line apart — stores the same address. What the reader gets back is+ /// an editable suggestion and one Save for the whole screen, instead of a+ /// button that wrote before they had looked at the rest of their edit.+ public func confirmWorkURLCandidate() { guard case .available(let candidate) = workURLCandidate else { workURLStatusMessage = "No suggested Work URL is available to confirm." return }- await commitWorkURL(request: .confirmCandidate(candidate.value))+ draftWorkURL = candidate.value+ acceptedSuggestedURL = true+ // The suggestion is not a refusal, and the standing explanation of why+ // there is or is not one still belongs under the field.+ refreshWorkURLStatusFromCandidate() } + /// Whether the reader has **accepted** the suggestion the projection+ /// pre-filled the field with (T-2328).+ ///+ /// The field opens holding the suggestion, so the text alone cannot say+ /// whether the reader meant it — which is the whole of Q57's argument for a+ /// button that wrote on the tap. It is a marker on the draft instead: the+ /// shape the rule suggestion, the extracted record and the cropped cover+ /// already use, and the ordinary Save is what acts on it. Cleared by every+ /// projection that re-seeds the field, and by the cancel that discards it.+ private var acceptedSuggestedURL = false+ /// Whether the URL field holds something the checkmark still has to write. /// /// Compared trimmed, so typing a space into an empty field is not a reason /// to commit a clear over a Work that never had a URL. public var hasUnsavedWorkURLChange: Bool {- draftWorkURL.trimmingCharacters(in: .whitespacesAndNewlines)- != baselineWorkURL.trimmingCharacters(in: .whitespacesAndNewlines)+ acceptedSuggestedURL+ || draftWorkURL.trimmingCharacters(in: .whitespacesAndNewlines)+ != baselineWorkURL.trimmingCharacters(in: .whitespacesAndNewlines) } /// The editor's URL half: writes the field as it stands, and reports@@ -1728,7 +1835,9 @@ public final class WorkDetailModel { } public var siteLinks: [SiteLink] {- (work?.memberships ?? []).compactMap { membership in+ (work?.memberships ?? []).filter {+ !stagedMembershipRemovals.contains($0.hostname)+ }.compactMap { membership in guard let string = membership.workURLString, let url = URL(string: string) else { return nil }@@ -1755,7 +1864,16 @@ public final class WorkDetailModel { /// Derived once per load rather than per membership per body evaluation: /// the per-membership question is one pass over the Work's whole entry list /// each time it is asked, and the view asked it inside a `ForEach`.- public private(set) var removableHostnames: [String] = []+ private var loadedRemovableHostnames: [String] = []++ /// The same list **after** this session's staged removals (T-2328): a site+ /// already staged is not offered again, and the last site standing is never+ /// removable however many of the others are staged — Req 1.3 is about what+ /// the save would leave, not about what the load found.+ public var removableHostnames: [String] {+ guard hostnames.count > 1 else { return [] }+ return loadedRemovableHostnames.filter { !stagedMembershipRemovals.contains($0) }+ } /// Whether edit mode offers "Remove from site" for this membership. public func canRemoveMembership(hostname: String) -> Bool {@@ -1771,27 +1889,40 @@ public final class WorkDetailModel { return work.memberships.map(\.hostname).filter { entryCounts[$0, default: 0] == 0 } } - /// Drops one site from this Work and re-reads the screen.+ /// Stages one site's removal. **Nothing is written until Save** (T-2328).+ ///+ /// The confirmation stays where it was — a removal is still destructive+ /// enough to be meant — but what it confirms is now the draft, so a cancel+ /// of the edit puts the site back and a refused save leaves it staged. ///- /// A refusal lands in `errorMessage` like a refused save: the removal is a- /// write, and the screen says what happened rather than closing over it.+ /// The URL machinery moves off a site the reader has just staged away: the+ /// field would otherwise be editing an address on a membership this save is+ /// about to delete. public func removeMembership(hostname: String) async {- guard !isSubmitting else { return }- isSubmitting = true- state = .submitting+ guard canRemoveMembership(hostname: hostname) else { return } errorMessage = nil- defer { isSubmitting = false }+ stagedMembershipRemovals.insert(hostname)+ guard hostname == selectedWorkURLHostname else { return }+ selectedWorkURLHostname = hostnames.first ?? ""+ await loadWorkURL()+ }++ /// Commits every staged site removal in one call, and reports whether it+ /// landed. A refusal reads like a refused save: the editor stays open, the+ /// removals stay staged, and the repository's reason is on the screen.+ private func commitMembershipRemovals() async -> Bool {+ guard !stagedMembershipRemovals.isEmpty else { return true } do {- try await library.removeSiteMembership(workID: workID, hostname: hostname)- await onMutation()- // The reload re-defaults the URL selection when the site the reader- // was editing is the one that just went.- await load()+ try await library.removeSiteMemberships(+ workID: workID, hostnames: Array(stagedMembershipRemovals).sorted())+ stagedMembershipRemovals = []+ return true } catch { errorMessage = error.localizedDescription state = .error(message: error.localizedDescription) Self.logger.error( "Site membership removal failed: \(String(describing: error), privacy: .public)")+ return false } } @@ -1918,6 +2049,7 @@ public final class WorkDetailModel { isEditing = false restoreDraftsFromSnapshot() draftWorkURL = baselineWorkURL+ acceptedSuggestedURL = false clearLastRefusal() // Req 4.11: leaving edit mode stops every fetch still in flight. The // draft restore above has already retired the session token, so a@@ -1963,18 +2095,29 @@ public final class WorkDetailModel { // the metadata save below skips its reload when a record step follows. let recordOperations = stagedRecordEdits() let hasRecordChanges = !recordOperations.isEmpty+ // T-2328's two steps, derived here beside the record operations and for+ // their reason: what the tail reloads on must be decided before the+ // commits that clear them.+ let linkOperations = stagedLinkEdits()+ let hasConnectionChanges = !linkOperations.isEmpty || hasUnsavedMembershipRemovals let hadMetadataChanges = hasUnsavedChanges if hadMetadataChanges {- // One reload, not two: the record step is the last write, so when- // one follows, its reload is the one that publishes everything.- await save(reloading: !hasRecordChanges)+ // One reload, not two: a later step's reload is the one that+ // publishes everything.+ await save(reloading: !hasRecordChanges && !hasConnectionChanges) // Both halves of a refusal keep the editor open: the sentence that // has no field to sit under, and the one that sits under the // position field. guard errorMessage == nil, positionRefusal == nil else { return } } guard await commitRecordStep(recordOperations) else { return }+ // T-2328: the two staged-connection steps, last and in this order —+ // both write their own tables, so neither can be folded into the+ // metadata save, and a refusal in either keeps the editor open with its+ // staged edits intact.+ guard await commitLinkStep(linkOperations) else { return }+ guard await commitMembershipRemovals() else { return } // Dropped before the reload, so the re-adopt below is allowed to replace // the drafts with what the store now holds.@@ -1986,7 +2129,7 @@ public final class WorkDetailModel { // candidate sheet over view mode, on a work the reader has already // saved. cancelCoverFetch()- if hasRecordChanges {+ if hasRecordChanges || hasConnectionChanges { // `place-extraction` Q55: the app is told **before** the reload. The // coordinator's `reconcile()` is reached only through // `refreshDiagnosesAndSnapshots`, and a held bundle targeting a@@ -1995,7 +2138,8 @@ public final class WorkDetailModel { // the commit gate refuses it, but visible. await onMutation() }- if hasRecordChanges || (committedURL && !hadMetadataChanges) {+ if hasRecordChanges || hasConnectionChanges+ || (committedURL && !hadMetadataChanges) { await load() } }@@ -2005,6 +2149,11 @@ public final class WorkDetailModel { // screen whose read has gone still discards the crop the reader made // rather than leaving it standing in a closed editor. restoreThumbnailDraft(from: work)+ // T-2328: the staged link edits and the staged site removals are drafts+ // like any other and go back with the rest — and before the guard, for+ // the cover's reason.+ restoreLinkDraftsFromPresentation()+ stagedMembershipRemovals = [] guard let work else { return } draftTitle = work.displayTitle draftAssignment = work.typeDisplay.assignment@@ -2912,8 +3061,10 @@ public final class WorkDetailModel { ?? contract.outcome.candidate.availableValue ?? "" // What the field was given is what a cancel restores and what the- // dirty check measures against.+ // dirty check measures against — and what it was given is not+ // something the reader has accepted yet (T-2328). baselineWorkURL = draftWorkURL+ acceptedSuggestedURL = false } refreshWorkURLStatusFromCandidate() }
diff --git a/Asterism/Asterism/Views/CreatorRolesView.swift b/Asterism/Asterism/Views/CreatorRolesView.swiftindex e2290257..a49be183 100644--- a/Asterism/Asterism/Views/CreatorRolesView.swift+++ b/Asterism/Asterism/Views/CreatorRolesView.swift@@ -27,11 +27,38 @@ struct CreatorRolesListView: View { .accessibilityIdentifier("settings-creator-roles-list") // The seam, not an `#if` here (Req 4.5 of `ipad-and-mac-layouts`): // `EditButton` does not exist on macOS, where a row with `.onMove` is- // dragged without entering a mode first.+ // dragged without entering a mode first. It turns dragging on and off+ // and writes nothing — the pair below is what commits (T-2328, Q99 of `work-creators`). .listEditToolbarButton(identifier: "settings-creator-roles-edit-button")+ .toolbar { orderToolbarItems } .task { await model.load() } } + // MARK: - The order's two ways out (Req 2.5, T-2328)++ /// Save and Cancel, drawn exactly while the list on screen is an order the+ /// store has not been told about.+ ///+ /// The list is an editor like any other: the drag is the draft and this is+ /// the one write. They are absent rather than disabled while there is+ /// nothing to save, so the screen does not read as a form with a pending+ /// commit on it.+ @ToolbarContentBuilder+ private var orderToolbarItems: some ToolbarContent {+ if model.hasUnsavedOrder {+ ToolbarItem(placement: .cancellationAction) {+ Button("Cancel") { model.cancelOrder() }+ .accessibilityIdentifier("settings-creator-roles-order-cancel")+ .accessibilityLabel("Discard the new order")+ }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") { Task { await model.saveOrder() } }+ .accessibilityIdentifier("settings-creator-roles-order-save")+ .accessibilityLabel("Save the new order")+ }+ }+ }+ // MARK: - Adding (Req 2.2) /// The work-types screen's shape: a field and the button that commits it, on@@ -98,11 +125,12 @@ struct CreatorRolesListView: View { ForEach(model.rows) { row in roleRow(row) }- // Req 2.5. The model reorders its rows and sends the whole- // active order, because the repository numbers what it is given+ // Req 2.5. The drag stages the order and writes nothing+ // (T-2328, Q99 of `work-creators`); the toolbar's Save sends the whole active+ // order, because the repository numbers what it is given // rather than applying a pair of indices (Q58). .onMove { source, destination in- Task { await model.move(from: source, to: destination) }+ model.move(from: source, to: destination) } } }
diff --git a/Asterism/Asterism/Views/MoveToView.swift b/Asterism/Asterism/Views/MoveToView.swiftindex cb2c78b1..4b4d7314 100644--- a/Asterism/Asterism/Views/MoveToView.swift+++ b/Asterism/Asterism/Views/MoveToView.swift@@ -33,6 +33,14 @@ struct MoveToView: View { .accessibilityIdentifier("move-to-cancel-button") .accessibilityLabel("Cancel") }+ // T-2328: the destination rows choose, and this writes. The+ // sheet is an editor like every other screen in the app.+ ToolbarItem(placement: .confirmationAction) {+ Button("Move") { Task { await model.submit() } }+ .disabled(!model.canSubmit)+ .accessibilityIdentifier("move-to-submit-button")+ .accessibilityLabel("Move")+ } } .task { await model.load() } .onChange(of: model.state) { _, newState in@@ -47,21 +55,10 @@ struct MoveToView: View { if !model.destinations.isEmpty { Section { ForEach(model.destinations, id: \.id) { work in- Button {- Task { await model.moveToExisting(work.id) }- } label: {- Text(work.displayTitle)- .font(AsterismTypography.serifRowTitle)- .lineLimit(1)- .truncationMode(.tail)- }- .disabled(model.state == .submitting)- .frame(- minWidth: AsterismLayout.minHitTarget,- minHeight: AsterismLayout.minHitTarget- )- .accessibilityIdentifier("move-to-work-destination")- .accessibilityLabel("Move to \(work.displayTitle)")+ destinationRow(+ .existing(work.id), title: work.displayTitle,+ label: "Move to \(work.displayTitle)",+ identifier: "move-to-work-destination") } } header: { ConstellationSectionHeader("Same-host Works")@@ -72,29 +69,18 @@ struct MoveToView: View { HStack { TextField("New Work title", text: $model.newWorkTitle) .accessibilityIdentifier("move-to-new-work-title")- Button {- Task { await model.moveToNewWork() }- } label: {- Text("New Work")- .frame(- minWidth: AsterismLayout.minHitTarget,- minHeight: AsterismLayout.minHitTarget- )- .contentShape(Rectangle())- }- .disabled(model.state == .submitting || model.newWorkTitle.trimmingCharacters(in: .whitespaces).isEmpty)- .accessibilityIdentifier("move-to-new-work-button")+ destinationRow(+ .newWork, title: "New Work", label: "Move to a new Work",+ identifier: "move-to-new-work-button", fillsRow: false) } .frame(minHeight: AsterismLayout.minHitTarget) } Section {- Button("Leave unattached") {- Task { await model.leaveUnattached() }- }- .disabled(model.state == .submitting)- .frame(minHeight: AsterismLayout.minHitTarget)- .accessibilityIdentifier("move-to-leave-unattached-button")+ destinationRow(+ .unattached, title: "Leave unattached",+ label: "Leave unattached",+ identifier: "move-to-leave-unattached-button") } if let errorMessage = model.errorMessage {@@ -106,4 +92,43 @@ struct MoveToView: View { } } }++ /// One destination, chosen rather than committed (T-2328).+ ///+ /// The checkmark is the whole of the state: the row the reader picked is+ /// the one Move will write, and picking it again unpicks it. Chosen state+ /// joins the accessibility label rather than the value, as every other+ /// marked control on these screens does.+ ///+ /// `fillsRow` is false for the New Work row alone: it shares its line with+ /// the title field, so a greedy spacer inside it would squeeze the field.+ private func destinationRow(+ _ destination: MoveToModel.Destination, title: String, label: String,+ identifier: String, fillsRow: Bool = true+ ) -> some View {+ let isSelected = model.selection == destination+ return Button {+ model.select(destination)+ } label: {+ HStack(spacing: 8) {+ Text(title)+ .font(AsterismTypography.serifRowTitle)+ .lineLimit(1)+ .truncationMode(.tail)+ if fillsRow { Spacer(minLength: 8) }+ if isSelected {+ Image(systemName: "checkmark")+ .foregroundStyle(AsterismColors.violet)+ }+ }+ .frame(+ minWidth: AsterismLayout.minHitTarget,+ minHeight: AsterismLayout.minHitTarget+ )+ .contentShape(Rectangle())+ }+ .disabled(model.state == .submitting)+ .accessibilityIdentifier(identifier)+ .accessibilityLabel(isSelected ? "\(label), chosen" : label)+ } }
diff --git a/Asterism/Asterism/Views/RelatedWorkEditorView.swift b/Asterism/Asterism/Views/RelatedWorkEditorView.swiftindex 05071d8b..1e39bbcd 100644--- a/Asterism/Asterism/Views/RelatedWorkEditorView.swift+++ b/Asterism/Asterism/Views/RelatedWorkEditorView.swift@@ -10,11 +10,10 @@ import SwiftUI /// used to be a card per link inside the section, which is what made three /// links taller than everything above them. ///-/// **Everything here still commits on the spot** (Q24): a link is its own row-/// with its own timestamps, so folding it into the work's draft would make a-/// retype wait on — and conflict with — a title being typed beside it. The-/// sheet's Done closes the sheet; it does not write, because the writing has-/// already happened.+/// **Nothing here writes** (T-2328, Decision 8): the type field and the remove+/// row are drafts of the work's edit session, and the work editor's Save is+/// what commits them — in one call, with the rest of the session's link edits.+/// The sheet's Done closes the sheet, as it always did. struct RelatedWorkEditorView: View { let model: WorkDetailModel let link: WorkLinkSnapshot@@ -39,10 +38,10 @@ struct RelatedWorkEditorView: View { .frame(minHeight: AsterismLayout.minHitTarget) .accessibilityLabel("Link type for \(link.displayTitle)") .accessibilityIdentifier("work-detail-link-type-\(link.id.uuidString)")- // The field commits what it holds when the reader is done with- // it, rather than on every keystroke: a retype stamps the link's- // modification time, which is the survivor key (Q27).- .onSubmit { Task { await model.commitLinkType(for: link.id) } }+ // No `onSubmit` commit: the field *is* the draft, and Save is+ // what writes it (Decision 8). A type equal to the stored one+ // still stamps nothing — the commit emits no retype for it,+ // which is what Q27's survivor key needs. } header: { ConstellationSectionHeader("Type", accent: .violet) } footer: {@@ -56,7 +55,6 @@ struct RelatedWorkEditorView: View { selected: model.linkTypeDraft(for: link.id) ) { suggestion in model.setLinkTypeDraft(suggestion, for: link.id)- Task { await model.commitLinkType(for: link.id) } } .constellationListRow() }@@ -65,13 +63,15 @@ struct RelatedWorkEditorView: View { Section { ConstellationDestructiveRow(title: "Remove link") { dismiss()- Task { await model.removeLink(id: link.id) }+ model.removeLink(id: link.id) } .disabled(model.isReadOnly) .accessibilityIdentifier("work-detail-link-remove-\(link.id.uuidString)") .accessibilityLabel("Remove the link to \(link.displayTitle)") } footer: {- Text("Unlinks the two works. \(link.displayTitle) stays in your library.")+ Text(+ "Unlinks the two works when you save. \(link.displayTitle) stays in "+ + "your library.") } } }
diff --git a/Asterism/Asterism/Views/SeriesDetailView.swift b/Asterism/Asterism/Views/SeriesDetailView.swiftindex 7f3e3c32..298427b9 100644--- a/Asterism/Asterism/Views/SeriesDetailView.swift+++ b/Asterism/Asterism/Views/SeriesDetailView.swift@@ -339,8 +339,9 @@ struct SeriesDetailView: View { .accessibilityIdentifier("series-member-position-refusal-\(row.id.uuidString)") } + // T-2328: staged in the draft, written by the screen's Save. Button("Remove from series", role: .destructive) {- Task { await model.removeMember(row.id) }+ model.removeMember(row.id) } .font(.caption) .disabled(model.isSubmitting)
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex 983852ea..c7aff4c4 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -466,8 +466,9 @@ struct WorkDetailView: View { .accessibilityIdentifier("work-detail-remove-site-cancel") } message: { hostname in Text(- "This work stops being on \(hostname). Nothing else changes — it "- + "has no notes from there, and its other sites keep theirs.")+ "This work stops being on \(hostname) when you save. Nothing else "+ + "changes — it has no notes from there, and its other sites keep "+ + "theirs.") } // Req 3.1's three actions, in a modifier of their own: the `List` above // already carries five presentations, and one more inline put the@@ -856,8 +857,10 @@ struct WorkDetailView: View { .font(.footnote) // Req 9.1: accepting a suggestion is an action, not this // screen's commit, so it keeps the gradient.+ // T-2328: this fills the field. The screen's own Save writes+ // it, with everything else the reader changed. Button(WorkURLDetailPresentation.confirmLabel) {- Task { await model.confirmWorkURLCandidate() }+ model.confirmWorkURLCandidate() } .buttonStyle(.constellationPrimary) .disabled(model.isWorkURLSubmitting || model.isReadOnly)@@ -1227,8 +1230,8 @@ struct WorkDetailView: View { /// "TITLE: link type" on one compact line, opening that link's editor. /// /// The link card it replaces held a type field, a chip row and a red- /// "Remove link"; all three are in the sheet this opens, and the per-link- /// commit-on-the-spot rule (Q24) is unchanged by the move.+ /// "Remove link"; all three are in the sheet this opens, and since T-2328+ /// none of them writes — the work's Save commits the session's link edits. private func editLinkLine(_ link: WorkLinkSnapshot) -> some View { ConstellationLineRow( name: link.displayTitle,@@ -2591,7 +2594,7 @@ private struct WorkConnectionPresentations: ViewModifier { suggestions: model.linkTypeSuggestions, onSubmit: { type in pendingLinkTarget = nil- Task { await model.addLink(to: target.id, type: type) }+ model.addLink(to: target.id, type: type) }) } // Req 2.3's "New series": one field, and the series exists the
diff --git a/Asterism/AsterismTests/AppLibraryModelTests.swift b/Asterism/AsterismTests/AppLibraryModelTests.swiftindex fb7efafb..830478bf 100644--- a/Asterism/AsterismTests/AppLibraryModelTests.swift+++ b/Asterism/AsterismTests/AppLibraryModelTests.swift@@ -342,7 +342,8 @@ struct AppLibraryModelDiagnosisRefreshTests { await moveTo.load() mock.callLog.removeAll() - await moveTo.moveToExisting(UUID())+ moveTo.select(.existing(UUID()))+ await moveTo.submit() #expect(mock.moveEntryCallCount == 1) #expect(mock.refreshDiagnosticsCallCount == 1)
diff --git a/Asterism/AsterismTests/CreatorRolesModelTests.swift b/Asterism/AsterismTests/CreatorRolesModelTests.swiftindex 62bb6469..f6533bd1 100644--- a/Asterism/AsterismTests/CreatorRolesModelTests.swift+++ b/Asterism/AsterismTests/CreatorRolesModelTests.swift@@ -223,7 +223,9 @@ struct CreatorRolesModelTests { /// Req 2.5, and Q58's contract: the repository is handed the **full active /// order**, not a pair of indices — it numbers what it is given 0…n and /// drops anything that resolves to a removed or merged row.- @Test("A move sends the whole active order in its new sequence")+ ///+ /// T-2328: the drag stages that order and Save sends it.+ @Test("A move stages the order, and Save sends the whole active list") @MainActor func moveSendsTheFullOrder() async { let author = UUID() let artist = UUID()@@ -236,9 +238,17 @@ struct CreatorRolesModelTests { await model.load() // Drag "translator" to the front.- await model.move(from: IndexSet(integer: 2), to: 0)+ model.move(from: IndexSet(integer: 2), to: 0)++ #expect(model.rows.map(\.name) == ["translator", "author", "artist"])+ #expect(model.hasUnsavedOrder)+ #expect(mock.reorderedCreatorRoleIDs.isEmpty)+ #expect(mutations.count == 0)++ await model.saveOrder() #expect(mock.reorderedCreatorRoleIDs == [[translator, author, artist]])+ #expect(!model.hasUnsavedOrder) #expect(mutations.count == 1) } @@ -258,12 +268,13 @@ struct CreatorRolesModelTests { ]) await model.load() - await model.move(from: IndexSet(integer: 1), to: 0)+ model.move(from: IndexSet(integer: 1), to: 0)+ await model.saveOrder() #expect(mock.reorderedCreatorRoleIDs == [[artist, author]]) } - @Test("A drag that ends where it started writes nothing")+ @Test("A drag that ends where it started offers no save") @MainActor func moveToTheSamePlaceIsANoOp() async { let (model, mock, mutations) = makeSUT([ snapshot("author", position: 0),@@ -273,12 +284,51 @@ struct CreatorRolesModelTests { // `move(fromOffsets:toOffset:)` treats a destination equal to the source // index as "stay put".- await model.move(from: IndexSet(integer: 0), to: 0)+ model.move(from: IndexSet(integer: 0), to: 0) + #expect(!model.hasUnsavedOrder)+ await model.saveOrder() #expect(mock.reorderedCreatorRoleIDs.isEmpty) #expect(mutations.count == 0) } + /// T-2328: the drag is a draft, and Cancel is what a draft owes the reader.+ @Test("Cancel puts the read's order back and writes nothing")+ @MainActor func cancelRestoresTheReadOrder() async {+ let (model, mock, mutations) = makeSUT([+ snapshot("author", position: 0),+ snapshot("artist", position: 1),+ ])+ await model.load()++ model.move(from: IndexSet(integer: 1), to: 0)+ #expect(model.rows.map(\.name) == ["artist", "author"])++ model.cancelOrder()++ #expect(model.rows.map(\.name) == ["author", "artist"])+ #expect(!model.hasUnsavedOrder)+ #expect(mock.reorderedCreatorRoleIDs.isEmpty)+ #expect(mutations.count == 0)+ }++ /// An add re-reads the list; a drag the reader has not saved yet must not+ /// be quietly undone by it.+ @Test("A read carries an unsaved order over it")+ @MainActor func aReadKeepsTheStagedOrder() async {+ let (model, _, _) = makeSUT([+ snapshot("author", position: 0),+ snapshot("artist", position: 1),+ ])+ await model.load()+ model.move(from: IndexSet(integer: 1), to: 0)++ await model.load()++ #expect(model.rows.map(\.name) == ["artist", "author"])+ #expect(model.hasUnsavedOrder)+ }+ /// The order on screen would otherwise be a claim the store did not accept. @Test("A failed reorder is reported and the list goes back to the store's order") @MainActor func moveFailureRestoresTheReadOrder() async {@@ -289,10 +339,12 @@ struct CreatorRolesModelTests { await model.load() mock.reorderCreatorRolesError = MockLibraryProvider.MockError.simulatedFailure("nope") - await model.move(from: IndexSet(integer: 1), to: 0)+ model.move(from: IndexSet(integer: 1), to: 0)+ await model.saveOrder() #expect(model.message != nil) #expect(model.rows.map(\.name) == ["author", "artist"])+ #expect(!model.hasUnsavedOrder) #expect(mutations.count == 0) } }
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex 4c012d6d..69d30e3d 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -266,6 +266,18 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { try removeSiteMembershipResult.get() } + /// Every staged set of hostnames the editor's Save sent, in order (T-2328).+ var removedSiteMembershipBatches: [(workID: UUID, hostnames: [String])] = []++ func removeSiteMemberships(workID: UUID, hostnames: [String]) async throws {+ callLog.append("removeSiteMemberships")+ removedSiteMembershipBatches.append((workID, hostnames))+ // Recorded per hostname as well, so the assertions that predate the+ // batch keep reading one list of pairs.+ for hostname in hostnames { removedSiteMemberships.append((workID, hostname)) }+ try removeSiteMembershipResult.get()+ }+ // MARK: - Rule suggestion candidates var ruleSuggestionCandidatesResult: Result<[RuleSuggestionCandidate], Error> = .success([])@@ -959,6 +971,19 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { try updateSeriesResult.get() } + /// Every series editor Save, in order (T-2328).+ var committedSeriesEdits:+ [(seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit])] = []+ var commitSeriesEditsResult: Result<LibraryWriteOutcome, Error> = .success(.committed)++ func commitSeriesEdits(+ seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit]+ ) async throws -> LibraryWriteOutcome {+ committedSeriesEdits.append((seriesID, name, notes, members))+ callLog.append("commitSeriesEdits")+ return try commitSeriesEditsResult.get()+ }+ func deleteSeries(id: UUID) async throws -> SeriesDeletionOutcome { lastDeletedSeriesID = id callLog.append("deleteSeries")@@ -1152,6 +1177,17 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { try removeLinkResult.get() } + /// Every batch of staged link edits the editor's Save sent, in order+ /// (T-2328), and the result the next one answers with.+ var committedLinkEdits: [(workID: UUID, operations: [WorkLinkEditOperation])] = []+ var commitLinkEditsResult: Result<Void, Error> = .success(())++ func commitLinkEdits(workID: UUID, operations: [WorkLinkEditOperation]) async throws {+ committedLinkEdits.append((workID, operations))+ callLog.append("commitLinkEdits")+ try commitLinkEditsResult.get()+ }+ func linkCandidates(for workID: UUID) async throws -> [WorkPickerCandidate] { linkCandidatesCallCount += 1 lastLinkCandidatesWorkID = workID
diff --git a/Asterism/AsterismTests/MoveToAndNewWorkModelTests.swift b/Asterism/AsterismTests/MoveToAndNewWorkModelTests.swiftindex b758b299..e06eae39 100644--- a/Asterism/AsterismTests/MoveToAndNewWorkModelTests.swift+++ b/Asterism/AsterismTests/MoveToAndNewWorkModelTests.swift@@ -31,7 +31,8 @@ struct MoveToModelTests { let workID = UUID() let model = MoveToModel(entryID: entryID, library: mock, onMutation: { tracker.mutationCount += 1 }) await model.load()- await model.moveToExisting(workID)+ model.select(.existing(workID))+ await model.submit() #expect(mock.moveEntryCallCount == 1) #expect(mock.lastMoveEntryID == entryID) #expect(mock.lastMoveDestination == .existing(workID))@@ -47,7 +48,8 @@ struct MoveToModelTests { let model = MoveToModel(entryID: entryID, library: mock, onMutation: {}) await model.load() model.newWorkTitle = "Brand New Work"- await model.moveToNewWork()+ model.select(.newWork)+ await model.submit() #expect(mock.lastMoveDestination == .newWork(displayTitle: "Brand New Work")) #expect(model.state == .completed) }@@ -59,11 +61,69 @@ struct MoveToModelTests { let entryID = UUID() let model = MoveToModel(entryID: entryID, library: mock, onMutation: {}) await model.load()- await model.leaveUnattached()+ model.select(.unattached)+ await model.submit() #expect(mock.lastMoveDestination == .unattached) #expect(model.state == .completed) } + /// T-2328: the sheet is an editor, so the destination tap is a choice and+ /// the toolbar's Move is the write. A sheet closed after tapping a row+ /// leaves the entry exactly where it was.+ @Test("Choosing a destination writes nothing until Move")+ @MainActor func choosingADestinationWritesNothing() async {+ let mock = MockLibraryProvider()+ mock.workDestinationsResult = .success([])+ let workID = UUID()+ let model = MoveToModel(entryID: UUID(), library: mock, onMutation: {})+ await model.load()++ model.select(.existing(workID))++ #expect(mock.moveEntryCallCount == 0)+ #expect(model.selection == .existing(workID))+ #expect(model.state == .ready)+ #expect(model.canSubmit)+ }++ /// Tapping the chosen row again is the way back to "nothing picked".+ @Test("Choosing the chosen destination again clears the choice")+ @MainActor func choosingTwiceClearsTheChoice() async {+ let mock = MockLibraryProvider()+ mock.workDestinationsResult = .success([])+ let model = MoveToModel(entryID: UUID(), library: mock, onMutation: {})+ await model.load()+ let workID = UUID()++ model.select(.existing(workID))+ model.select(.existing(workID))++ #expect(model.selection == nil)+ #expect(!model.canSubmit)+ }++ /// A new Work needs a title before Move means anything, and Move with no+ /// destination chosen writes nothing.+ @Test("Move is offered only for a destination it can write")+ @MainActor func moveIsOfferedOnlyWhereItCanWrite() async {+ let mock = MockLibraryProvider()+ mock.workDestinationsResult = .success([])+ let model = MoveToModel(entryID: UUID(), library: mock, onMutation: {})+ await model.load()++ #expect(!model.canSubmit)+ await model.submit()+ #expect(mock.moveEntryCallCount == 0)++ model.select(.newWork)+ #expect(!model.canSubmit)+ await model.submit()+ #expect(mock.moveEntryCallCount == 0)++ model.newWorkTitle = "Brand New Work"+ #expect(model.canSubmit)+ }+ @Test("Move failure preserves state and shows error") @MainActor func moveFailure() async { let mock = MockLibraryProvider()@@ -72,7 +132,8 @@ struct MoveToModelTests { let entryID = UUID() let model = MoveToModel(entryID: entryID, library: mock, onMutation: {}) await model.load()- await model.moveToExisting(UUID())+ model.select(.existing(UUID()))+ await model.submit() guard case .error = model.state else { Issue.record("Expected error state"); return }@@ -93,7 +154,8 @@ struct MoveToModelTests { entryID: UUID(), library: mock, onMutation: { tracker.mutationCount += 1 }) await model.load() - await model.moveToExisting(UUID())+ model.select(.existing(UUID()))+ await model.submit() guard case .error = model.state else { Issue.record("Expected error state, got \(model.state)"); return@@ -114,7 +176,8 @@ struct MoveToModelTests { let model = MoveToModel(entryID: entry.id, library: mock, onMutation: {}) await model.load() - await model.moveToExisting(UUID())+ model.select(.existing(UUID()))+ await model.submit() #expect(mock.lastMoveEntryBasis?.workID == priorWork) #expect(mock.lastMoveEntryBasis?.hostname == entry.hostname)@@ -129,8 +192,9 @@ struct MoveToModelTests { let entryID = UUID() let model = MoveToModel(entryID: entryID, library: mock, onMutation: {}) await model.load()- async let first: () = model.moveToExisting(UUID())- async let second: () = model.moveToExisting(UUID())+ model.select(.existing(UUID()))+ async let first: () = model.submit()+ async let second: () = model.submit() _ = await (first, second) #expect(mock.moveEntryCallCount == 1) }
diff --git a/Asterism/AsterismTests/SeriesModelsTests.swift b/Asterism/AsterismTests/SeriesModelsTests.swiftindex 36d5fb3c..535de1dc 100644--- a/Asterism/AsterismTests/SeriesModelsTests.swift+++ b/Asterism/AsterismTests/SeriesModelsTests.swift@@ -352,9 +352,10 @@ struct SeriesDetailModelTests { model.draftNotes = "Read 2.5 first" await model.save() - #expect(mock.lastUpdatedSeries?.id == Self.seriesID)- #expect(mock.lastUpdatedSeries?.name == "Ashfall Saga")- #expect(mock.lastUpdatedSeries?.notes == "Read 2.5 first")+ #expect(mock.committedSeriesEdits.count == 1)+ #expect(mock.committedSeriesEdits.first?.seriesID == Self.seriesID)+ #expect(mock.committedSeriesEdits.first?.name == "Ashfall Saga")+ #expect(mock.committedSeriesEdits.first?.notes == "Read 2.5 first") #expect(!model.isEditing) #expect(mutations.count == 1) }@@ -370,7 +371,7 @@ struct SeriesDetailModelTests { #expect(model.message?.isEmpty == false) #expect(model.isEditing)- #expect(mock.lastUpdatedSeries == nil)+ #expect(mock.committedSeriesEdits.isEmpty) #expect(mutations.count == 0) } @@ -384,18 +385,20 @@ struct SeriesDetailModelTests { model.cancelEditing() #expect(!model.isEditing)- #expect(mock.lastUpdatedSeries == nil)+ #expect(mock.committedSeriesEdits.isEmpty) model.beginEditing() #expect(model.draftName == "Ashfall Cycle") } // MARK: - Positions (Reqs 2.2, 2.6, 2.8) - /// Q25: a member's position is an edit **of the work**, so the draft carries- /// every one of the work's other fields back unchanged. A draft that dropped- /// the reading status or the notes would reset them with no error.- @Test("A changed position writes a draft carrying the member's other fields")- @MainActor func positionCommitCarriesTheWholeDraft() async throws {+ /// Q25 as T-2328 leaves it: a member edit still carries the member's **own+ /// basis**, so the redirect and the torn refusal are the work editor's. What+ /// it no longer carries is the rest of the work's metadata — the commit+ /// writes the two series columns and nothing else, so there is no field for+ /// a forgotten draft to reset.+ @Test("A changed position sends the member's own basis and the new membership")+ @MainActor func positionCommitCarriesTheBasis() async throws { let work = member("Ashfall", position: 1) let (model, mock, mutations) = makeSUT(detail(members: [work])) await model.load()@@ -404,27 +407,26 @@ struct SeriesDetailModelTests { model.setPositionDraft("2.5", for: work.id) await model.save() - let call = try #require(mock.updateWorkCalls.first)- #expect(call.id == work.id)- #expect(call.draft.membership == SeriesMembership(seriesID: Self.seriesID, position: 2.5))- #expect(call.draft.displayTitle == "Ashfall")- #expect(call.draft.genreTags == ["shonen"])- #expect(call.draft.genericNotes == "kept")- #expect(call.draft.readingStatus == .abandoned)- #expect(call.draft.verdict == "put down")+ let call = try #require(mock.committedSeriesEdits.first)+ let edit = try #require(call.members.first)+ #expect(call.members.count == 1)+ #expect(edit.workID == work.id)+ #expect(edit.membership == SeriesMembership(seriesID: Self.seriesID, position: 2.5)) // The basis is the member's own, so a membership changed elsewhere // between the read and this write is the edit conflict Req 2.4 asks for.- #expect(call.basis.membership == SeriesMembership(seriesID: Self.seriesID, position: 1))+ #expect(edit.basis.membership == SeriesMembership(seriesID: Self.seriesID, position: 1))+ #expect(edit.basis.displayTitle == "Ashfall")+ // Nothing goes through `updateWork` from this screen any more.+ #expect(mock.updateWorkCalls.isEmpty) #expect(mutations.count == 1) } - /// Task 5 of `update-schedule`, the same point one field further on: the- /// draft carries the member's schedule back unchanged, because `updateWork`- /// writes `releaseDays` to every row of the group whatever the caller sent.- /// A position edit that dropped it would clear the work's release days with- /// no error and no way for the reader to tell.- @Test("A changed position carries the member's release days back unchanged")- @MainActor func positionCommitPreservesReleaseDays() async throws {+ /// `update-schedule`'s point, one step further on: a position edit that+ /// rewrote the member's whole metadata could clear its release days. This+ /// one sends no metadata at all, which is the stronger version of the same+ /// guarantee.+ @Test("A position edit sends no metadata, so it cannot clear a member's schedule")+ @MainActor func positionCommitTouchesNoMetadata() async throws { let work = member("Ashfall", position: 1, releaseDays: [.thursday, .monday]) let (model, mock, _) = makeSUT(detail(members: [work])) await model.load()@@ -433,8 +435,8 @@ struct SeriesDetailModelTests { model.setPositionDraft("2.5", for: work.id) await model.save() - let call = try #require(mock.updateWorkCalls.first)- #expect(call.draft.releaseDays == [.monday, .thursday])+ #expect(mock.updateWorkCalls.isEmpty)+ #expect(mock.committedSeriesEdits.first?.members.count == 1) } @Test("An unchanged position writes nothing")@@ -448,6 +450,8 @@ struct SeriesDetailModelTests { await model.save() #expect(mock.updateWorkCalls.isEmpty)+ // T-2328: a confirmation with nothing to write takes no lock at all.+ #expect(mock.committedSeriesEdits.isEmpty) } /// Req 2.2: the refusal is the model's, before any repository call, and the@@ -468,6 +472,7 @@ struct SeriesDetailModelTests { #expect(model.isEditing) #expect(model.positionDraft(for: work.id) == "1,000.5") #expect(mock.updateWorkCalls.isEmpty)+ #expect(mock.committedSeriesEdits.isEmpty) } /// The border on the row's field comes from the same parse the save refuses@@ -611,58 +616,92 @@ struct SeriesDetailModelTests { #expect(model.positionRefusal(for: work.id) == nil) #expect(model.message == nil) #expect(mock.updateWorkCalls.isEmpty)+ #expect(mock.committedSeriesEdits.isEmpty) } - /// Req 2.6 and Q25: the rows commit one at a time, in list order. The first- /// refusal stops the sequence — the rows before it stay committed, the ones- /// after it are never asked — and the screen re-reads so it shows what- /// actually landed.- @Test("Position commits stop at the first conflict, keeping what landed")- @MainActor func positionCommitsStopAtTheFirstConflict() async {+ /// T-2328, Decision 9: one call, one save. A conflict on any member+ /// refuses the whole thing, so a save that is refused halfway cannot leave+ /// the name written and some positions written and others not.+ @Test("A conflict refuses the whole save and writes nothing")+ @MainActor func aConflictRefusesTheWholeSave() async throws { let first = member("Ashfall", position: 1) let second = member("Emberfall", position: 2) let third = member("Duskfall", position: 3)- let (model, mock, _) = makeSUT(detail(members: [first, second, third]))+ let (model, mock, mutations) = makeSUT(detail(members: [first, second, third])) await model.load() model.beginEditing()- mock.updateWorkResultsByWorkID[second.id] = .success(+ mock.commitSeriesEditsResult = .success( .conflict(.torn(recordID: second.id, variants: []))) + model.draftName = "Ashfall Saga" model.setPositionDraft("1.5", for: first.id) model.setPositionDraft("2.5", for: second.id) model.setPositionDraft("3.5", for: third.id) await model.save() - #expect(mock.updateWorkCalls.map(\.id) == [first.id, second.id])+ let call = try #require(mock.committedSeriesEdits.first)+ #expect(mock.committedSeriesEdits.count == 1)+ #expect(call.name == "Ashfall Saga")+ #expect(call.members.map(\.workID) == [first.id, second.id, third.id]) #expect(model.message == EntryDetailModel.conflictMessage( .torn(recordID: second.id, variants: [])))- // The re-read that shows what landed: one load, and one more here.- #expect(mock.seriesDetailCallCount == 2)+ // Q68: no `load()` on a refusal — it would reassign every draft on the+ // screen. The one read is the load the test opened with.+ #expect(mock.seriesDetailCallCount == 1)+ #expect(model.draftName == "Ashfall Saga")+ #expect(model.positionDraft(for: first.id) == "1.5") #expect(model.isEditing)+ #expect(mutations.count == 0) } // MARK: - Membership (Reqs 2.5, 2.6) - @Test("Removing a member sends a draft with no membership and leaves the work alone")- @MainActor func removeMember() async throws {+ /// T-2328: the removal is staged in the draft and written by Save, like+ /// every other field on the screen.+ @Test("Removing a member stages it and writes nothing until Save")+ @MainActor func removeMemberIsStaged() async throws { let work = member("Ashfall", position: 1) let (model, mock, mutations) = makeSUT(detail(members: [work])) await model.load()+ model.beginEditing() - await model.removeMember(work.id)+ model.removeMember(work.id) - let call = try #require(mock.updateWorkCalls.first)- #expect(call.id == work.id)- #expect(call.draft.membership == nil)- #expect(call.draft.displayTitle == "Ashfall")+ #expect(model.members.isEmpty)+ #expect(mock.committedSeriesEdits.isEmpty)+ #expect(mutations.count == 0)++ await model.save()++ let call = try #require(mock.committedSeriesEdits.first)+ let edit = try #require(call.members.first)+ #expect(edit.workID == work.id)+ #expect(edit.membership == nil)+ #expect(edit.basis.displayTitle == "Ashfall") #expect(mutations.count == 1)- // The screen re-reads: the row it removed has to leave the list.+ // The screen re-reads once the save has landed. #expect(mock.seriesDetailCallCount == 2) } + /// The editor's discard covers the member list like the typed fields.+ @Test("Cancelling puts a staged removal back")+ @MainActor func cancellingRestoresTheMemberList() async {+ let work = member("Ashfall", position: 1)+ let (model, mock, _) = makeSUT(detail(members: [work]))+ await model.load()+ model.beginEditing()+ model.removeMember(work.id)++ model.cancelEditing()++ #expect(model.members.map(\.id) == [work.id])+ #expect(mock.committedSeriesEdits.isEmpty)+ }+ /// Req 2.5: an added work takes the position Req 2.3 prefills — the next- /// whole number above the series' highest, which the repository computes.- @Test("Adding a member writes the prefilled position for this series")+ /// whole number above the series' highest, which the repository computes —+ /// and Save is what writes it (T-2328).+ @Test("Adding a member stages the prefilled position and saves it") @MainActor func addMemberTakesThePrefill() async throws { let candidate = TestFixtures.makeWork(displayTitle: "Duskfall") let (model, mock, mutations) = makeSUT(detail())@@ -672,27 +711,64 @@ struct SeriesDetailModelTests { mock.nextSeriesPositionResult = .success(3) await model.load() await model.loadCandidates()+ model.beginEditing() #expect(model.candidates.map(\.id) == [candidate.id]) await model.addMember(candidate.id) - let call = try #require(mock.updateWorkCalls.first) #expect(mock.lastNextSeriesPositionID == Self.seriesID)- #expect(call.id == candidate.id)- #expect(call.draft.membership == SeriesMembership(seriesID: Self.seriesID, position: 3))+ #expect(model.members.map(\.id) == [candidate.id])+ #expect(model.positionDraft(for: candidate.id) == "3")+ #expect(mock.committedSeriesEdits.isEmpty)+ #expect(mutations.count == 0)++ await model.save()++ let call = try #require(mock.committedSeriesEdits.first)+ let edit = try #require(call.members.first)+ #expect(edit.workID == candidate.id)+ #expect(edit.membership == SeriesMembership(seriesID: Self.seriesID, position: 3)) #expect(mutations.count == 1) } + /// Two works added before one save must not land on the same position.+ @Test("A second staged addition takes the position after the first")+ @MainActor func stagedAdditionsDoNotCollide() async {+ let first = TestFixtures.makeWork(displayTitle: "Duskfall")+ let second = TestFixtures.makeWork(displayTitle: "Nightfall")+ let (model, mock, _) = makeSUT(detail())+ mock.seriesMemberCandidatesResult = .success([+ WorkPickerCandidate(work: first, unavailableReason: nil),+ WorkPickerCandidate(work: second, unavailableReason: nil),+ ])+ mock.nextSeriesPositionResult = .success(3)+ await model.load()+ await model.loadCandidates()+ model.beginEditing()++ await model.addMember(first.id)+ await model.addMember(second.id)++ #expect(model.positionDraft(for: first.id) == "3")+ #expect(model.positionDraft(for: second.id) == "4")+ }+ @Test("A refused membership write is reported and nothing is claimed") @MainActor func refusedMembershipWrite() async { let work = member("Ashfall", position: 1) let (model, mock, mutations) = makeSUT(detail(members: [work]))- mock.updateWorkResult = .success(.conflict(.torn(recordID: work.id, variants: [])))+ mock.commitSeriesEditsResult = .success(+ .conflict(.torn(recordID: work.id, variants: []))) await model.load()+ model.beginEditing() - await model.removeMember(work.id)+ model.removeMember(work.id)+ await model.save() #expect(model.message?.isEmpty == false)+ #expect(model.isEditing)+ // The removal is still staged: it is the only copy of itself.+ #expect(model.members.isEmpty) #expect(mutations.count == 0) }
diff --git a/Asterism/AsterismTests/WorkDetailCreditsTests.swift b/Asterism/AsterismTests/WorkDetailCreditsTests.swiftindex b99c97f8..c286a3db 100644--- a/Asterism/AsterismTests/WorkDetailCreditsTests.swift+++ b/Asterism/AsterismTests/WorkDetailCreditsTests.swift@@ -119,11 +119,15 @@ struct WorkDetailCreditsTests { /// loaded, so the commit is measured against the baseline the draft was /// seeded from and never against a later read. ///- /// A link edit re-reads the presentation from inside edit mode (Q24), so- /// without the baseline a credit another device added in that window would- /// join `seenRowIDs` — and be deleted by a draft that never listed it.- @Test("A credit arriving mid-edit is neither seen by the save nor deleted by it")- @MainActor func presentationReloadDoesNotEnrolUnseenRows() async throws {+ /// This used to be driven through a link edit, which re-read the+ /// presentation from inside edit mode (Q24). T-2328 took that re-read away+ /// with the commit-on-the-tap it belonged to: no path now replaces+ /// `presentation` while the editor is open, so what this asserts is the+ /// half that is still reachable — the save sends the rows the editor was+ /// seeded with, whatever the library answers afterwards. `creditBaseline`+ /// stays in the model as the guard for any re-read added later.+ @Test("The save sends the credit rows this editing session was seeded with")+ @MainActor func theSaveSendsTheSeededRows() async throws { let mori = TestFixtures.makeCreator(name: "Mori Ayane") let studio = TestFixtures.makeCreator(name: "Studio Lantern") let seenRow = UUID()@@ -134,8 +138,9 @@ struct WorkDetailCreditsTests { await model.load() model.beginEditing() - // Another device credits a second creator while the reader is editing,- // and a link edit brings the new read in.+ // Another device credits a second creator while the reader is editing.+ // Nothing on this screen re-reads while the editor is open, so the+ // draft and its baseline are the reader's until they save. let work = try #require(model.work) mock.workDetailResult = .success( TestFixtures.makeWorkDetail(@@ -144,9 +149,7 @@ struct WorkDetailCreditsTests { credit(creator: mori, roles: [], rowIDs: [seenRow]), credit(creator: studio, roles: [], rowIDs: [arrivedRow]), ]))- await model.removeLink(id: UUID()) - #expect(model.credits.count == 2, "the live read holds both credits") #expect( model.draftCredits.map(\.creator.id) == [mori.id], "the draft is the reader's and is not replaced by a re-read")
diff --git a/Asterism/AsterismTests/WorkDetailModelTests.swift b/Asterism/AsterismTests/WorkDetailModelTests.swiftindex 24297db7..9663316c 100644--- a/Asterism/AsterismTests/WorkDetailModelTests.swift+++ b/Asterism/AsterismTests/WorkDetailModelTests.swift@@ -1483,11 +1483,38 @@ struct WorkDetailMultiSiteTests { #expect(model.entryCount(onHostname: "a.example") == 1) #expect(model.entryCount(onHostname: "b.example") == 0) + model.beginEditing() await model.removeMembership(hostname: "b.example") - #expect(mock.removedSiteMemberships.count == 1)- #expect(mock.removedSiteMemberships[0].workID == workID)- #expect(mock.removedSiteMemberships[0].hostname == "b.example")+ // T-2328: staged, not written. The site is off the screen's lists and+ // the removal waits for Save.+ #expect(model.hostnames == ["a.example"])+ #expect(model.hasUnsavedMembershipRemovals)+ #expect(mock.removedSiteMemberships.isEmpty)+ // The one site left is never removable, whatever the load found.+ #expect(!model.canRemoveMembership(hostname: "a.example"))++ await model.commitEditing()++ #expect(mock.removedSiteMembershipBatches.count == 1)+ #expect(mock.removedSiteMembershipBatches[0].workID == workID)+ #expect(mock.removedSiteMembershipBatches[0].hostnames == ["b.example"])+ }++ /// The removal is a draft like any other, so the editor's X puts the site+ /// back (T-2328).+ @Test("Cancelling the editor puts a staged site removal back")+ @MainActor func cancellingRestoresTheStagedSite() async {+ let (model, mock) = makeSUT(work: TestFixtures.makeWork(memberships: Self.twoSites))+ await model.load()+ model.beginEditing()++ await model.removeMembership(hostname: "b.example")+ model.cancelEditing()++ #expect(model.hostnames == ["a.example", "b.example"])+ #expect(!model.hasUnsavedMembershipRemovals)+ #expect(mock.removedSiteMemberships.isEmpty) } /// Req 1.3: a Work always holds at least one membership, so its only site is@@ -1507,10 +1534,15 @@ struct WorkDetailMultiSiteTests { mock.removeSiteMembershipResult = .failure( MockLibraryProvider.MockError.simulatedFailure( "A Work must stay on at least one site."))+ model.beginEditing() await model.removeMembership(hostname: "b.example")+ await model.commitEditing() #expect(model.errorMessage == "A Work must stay on at least one site.")+ // The editor stays open with the removal still staged.+ #expect(model.isEditing)+ #expect(model.hasUnsavedMembershipRemovals) } // MARK: - Links (Req 6.3)@@ -2069,93 +2101,198 @@ struct WorkDetailConnectionsTests { #expect(model.links == [link]) } - @Test("Adding a link commits it and re-reads the section")- @MainActor func addingALinkReloadsTheSection() async {- let other = UUID()+ /// T-2328, Decision 8: the add stages a link the section draws, and the+ /// store hears nothing until Save.+ @Test("Adding a link stages it and writes nothing")+ @MainActor func addingALinkStagesIt() async {+ let other = TestFixtures.makeWork(displayTitle: "The Toon")+ let (model, mock, tracker) = makeSUT(work: TestFixtures.makeWork())+ mock.linkCandidatesResult = .success([+ WorkPickerCandidate(work: other, unavailableReason: nil)+ ])+ await model.load()+ await model.loadLinkOptions()+ model.beginEditing()+ let readsAfterLoad = mock.workDetailCallCount++ model.addLink(to: other.id, type: "adaptation")++ #expect(model.links.map(\.otherWorkID) == [other.id])+ #expect(model.links.map(\.linkType) == ["adaptation"])+ #expect(model.links.map(\.otherTitle) == ["The Toon"])+ #expect(mock.addLinkCallCount == 0)+ #expect(mock.committedLinkEdits.isEmpty)+ #expect(mock.workDetailCallCount == readsAfterLoad)+ #expect(tracker.mutationCount == 0)+ }++ @Test("Saving the editor commits the staged link in one call")+ @MainActor func savingCommitsTheStagedLink() async {+ let other = TestFixtures.makeWork(displayTitle: "The Toon") let work = TestFixtures.makeWork() let (model, mock, tracker) = makeSUT(work: work)+ mock.linkCandidatesResult = .success([+ WorkPickerCandidate(work: other, unavailableReason: nil)+ ]) await model.load()- let readsAfterLoad = mock.workDetailCallCount+ await model.loadLinkOptions()+ model.beginEditing()+ model.addLink(to: other.id, type: "adaptation") - await model.addLink(to: other, type: "adaptation")+ await model.commitEditing() - #expect(mock.lastAddedLink?.a == work.id)- #expect(mock.lastAddedLink?.b == other)- #expect(mock.lastAddedLink?.type == "adaptation")- #expect(mock.workDetailCallCount == readsAfterLoad + 1)+ #expect(mock.committedLinkEdits.count == 1)+ #expect(mock.committedLinkEdits.first?.workID == work.id)+ #expect(+ mock.committedLinkEdits.first?.operations+ == [.add(otherWorkID: other.id, type: "adaptation")])+ #expect(mock.addLinkCallCount == 0)+ #expect(!model.isEditing) #expect(tracker.mutationCount == 1) } - @Test("A link type the validator refuses is reported and nothing is written")+ @Test("A link type the validator refuses is reported and nothing is staged") @MainActor func anInvalidLinkTypeIsRefused() async { let (model, mock, _) = makeSUT(work: TestFixtures.makeWork()) await model.load()+ model.beginEditing() - await model.addLink(to: UUID(), type: " ")+ model.addLink(to: UUID(), type: " ") #expect(mock.addLinkCallCount == 0)+ #expect(model.links.isEmpty) #expect(model.errorMessage == "A link needs a type.") } - @Test("Retyping a link commits it and re-reads the section")- @MainActor func retypingALinkReloadsTheSection() async {+ /// Req 6.2 through the draft: the picker's candidates were read before this+ /// session staged anything, so the model checks the list it is showing.+ @Test("Linking a work the draft already links is refused")+ @MainActor func aStagedPairIsRefusedTwice() async {+ let other = TestFixtures.makeWork(displayTitle: "The Toon")+ let (model, _, _) = makeSUT(work: TestFixtures.makeWork())+ await model.load()+ model.beginEditing()+ model.addLink(to: other.id, type: "adaptation")++ model.addLink(to: other.id, type: "sequel")++ #expect(model.links.count == 1)+ #expect(model.errorMessage == "These works are already linked as “adaptation”.")+ }++ @Test("Retyping a link stages the type and commits it at Save")+ @MainActor func retypingALinkIsStaged() async { let link = TestFixtures.makeLink(linkType: "adaptation") let (model, mock, tracker) = makeSUT(work: TestFixtures.makeWork(), links: [link]) await model.load()- let readsAfterLoad = mock.workDetailCallCount+ model.beginEditing() #expect(model.linkTypeDraft(for: link.id) == "adaptation") model.setLinkTypeDraft("spin-off", for: link.id)- await model.commitLinkType(for: link.id) - #expect(mock.lastRetypedLink?.id == link.id)- #expect(mock.lastRetypedLink?.type == "spin-off")- #expect(mock.workDetailCallCount == readsAfterLoad + 1)+ #expect(model.links.map(\.linkType) == ["spin-off"])+ #expect(mock.retypeLinkCallCount == 0)+ #expect(mock.committedLinkEdits.isEmpty)++ await model.commitEditing()++ #expect(+ mock.committedLinkEdits.first?.operations+ == [.retype(linkID: link.id, type: "spin-off")]) #expect(tracker.mutationCount == 1) } - @Test("Committing an unchanged link type writes nothing")+ /// Q27 reads the link's stamp, so a field the reader only tabbed through+ /// must not produce a retype.+ @Test("An unchanged link type sends no operation") @MainActor func anUnchangedLinkTypeWritesNothing() async { let link = TestFixtures.makeLink(linkType: "adaptation") let (model, mock, _) = makeSUT(work: TestFixtures.makeWork(), links: [link]) await model.load()+ model.beginEditing() model.setLinkTypeDraft(" adaptation ", for: link.id)- await model.commitLinkType(for: link.id)+ await model.commitEditing() + #expect(mock.committedLinkEdits.isEmpty) #expect(mock.retypeLinkCallCount == 0) } - @Test("Removing a link commits it and re-reads the section")- @MainActor func removingALinkReloadsTheSection() async {+ @Test("Removing a link stages it and commits it at Save")+ @MainActor func removingALinkIsStaged() async { let link = TestFixtures.makeLink() let (model, mock, tracker) = makeSUT(work: TestFixtures.makeWork(), links: [link]) await model.load()- let readsAfterLoad = mock.workDetailCallCount+ model.beginEditing() - await model.removeLink(id: link.id)+ model.removeLink(id: link.id) - #expect(mock.lastRemovedLinkID == link.id)- #expect(mock.workDetailCallCount == readsAfterLoad + 1)+ #expect(model.links.isEmpty)+ #expect(mock.removeLinkCallCount == 0)+ #expect(tracker.mutationCount == 0)++ await model.commitEditing()++ #expect(mock.committedLinkEdits.first?.operations == [.remove(linkID: link.id)])+ #expect(mock.removeLinkCallCount == 0) #expect(tracker.mutationCount == 1) } - /// Q24 in one assertion: a link edit lands outside the work's draft, so the- /// re-read behind it must not put the reader's half-typed fields back.- @Test("A link edit leaves the metadata drafts where the reader left them")- @MainActor func aLinkEditLeavesTheDraftsAlone() async {+ /// The editor's discard covers the link section like every other draft.+ @Test("Cancelling the editor puts the link section back")+ @MainActor func cancellingRestoresTheLinkSection() async {+ let link = TestFixtures.makeLink(linkType: "adaptation")+ let other = TestFixtures.makeWork(displayTitle: "The Toon")+ let (model, mock, _) = makeSUT(work: TestFixtures.makeWork(), links: [link])+ await model.load()+ model.beginEditing()+ model.removeLink(id: link.id)+ model.addLink(to: other.id, type: "sequel")+ model.setLinkTypeDraft("spin-off", for: link.id)++ model.cancelEditing()++ #expect(model.links.map(\.id) == [link.id])+ #expect(model.links.map(\.linkType) == ["adaptation"])+ #expect(mock.committedLinkEdits.isEmpty)+ }++ /// A staged add the reader thought better of is dropped, not written and+ /// then removed.+ @Test("Removing a staged link drops it with no operation")+ @MainActor func removingAStagedLinkDropsIt() async {+ let other = TestFixtures.makeWork(displayTitle: "The Toon")+ let (model, mock, _) = makeSUT(work: TestFixtures.makeWork())+ await model.load()+ model.beginEditing()+ model.addLink(to: other.id, type: "adaptation")+ let staged = model.links.first?.id++ model.removeLink(id: staged ?? UUID())+ await model.commitEditing()++ #expect(model.links.isEmpty)+ #expect(mock.committedLinkEdits.isEmpty)+ }++ /// A refused link commit keeps the editor open with the staged edits on+ /// screen — they are the only copy of themselves.+ @Test("A refused link commit keeps the editor and the staged edits")+ @MainActor func aRefusedLinkCommitKeepsTheEditor() async { let link = TestFixtures.makeLink()- let (model, _, _) = makeSUT(work: member(), links: [link])+ let (model, mock, _) = makeSUT(work: TestFixtures.makeWork(), links: [link])+ mock.commitLinkEditsResult = .failure(WorkLinkError.torn(workID: UUID())) await model.load() model.beginEditing()- model.draftTitle = "Half typed"- model.draftPositionText = "7"+ model.removeLink(id: link.id) - await model.removeLink(id: link.id)+ await model.commitEditing() - #expect(model.draftTitle == "Half typed")- #expect(model.draftPositionText == "7") #expect(model.isEditing)+ #expect(model.links.isEmpty)+ #expect(+ model.errorMessage+ == "This work exists in differing copies. Resolve them before linking it.") } /// Req 8.2: the picker is read on demand, over works other than this one,
diff --git a/Asterism/AsterismTests/WorkURLDetailModelTests.swift b/Asterism/AsterismTests/WorkURLDetailModelTests.swiftindex 1e932adb..e720e6a3 100644--- a/Asterism/AsterismTests/WorkURLDetailModelTests.swift+++ b/Asterism/AsterismTests/WorkURLDetailModelTests.swift@@ -41,25 +41,70 @@ struct WorkURLDetailModelTests { #expect(Set(messages).count == WorkURLUnavailableReason.allCases.count) } - @Test("Candidate confirmation projects the exact displayed value and commits")- @MainActor func confirmCandidate() async throws {+ /// T-2328, Decision 6 of `polish-and-export`: "Use Suggested URL" fills the field and writes+ /// nothing. Q57 kept it as a commit of its own; the value it approves is a+ /// string, and a string is what the draft holds.+ @Test("Use Suggested URL fills the field and writes nothing")+ @MainActor func confirmCandidateFillsTheDraft() async throws { let candidate = ExactScalarString("https://example.com/series/42") let contract = try makeContract(- request: .confirmCandidate(candidate.value),+ request: .clear, candidate: .available(candidate), resultingURL: nil)+ let (model, mock) = makeSUT(contract: contract)+ await model.loadWorkURL()++ model.confirmWorkURLCandidate()++ #expect(model.draftWorkURL == candidate.value)+ #expect(model.hasUnsavedWorkURLChange)+ #expect(mock.commitWorkURLCallCount == 0)+ #expect(model.workURLStatusMessage == nil)+ }++ /// And the ordinary Save writes it, as `.replaceManual` — the planner's two+ /// arms store the same address.+ @Test("The suggestion the field was filled with is written by Save")+ @MainActor func theFilledSuggestionIsSavedWithTheRest() async throws {+ let candidate = ExactScalarString("https://example.com/series/42")+ let loaded = try makeContract(+ request: .clear, candidate: .available(candidate), resultingURL: nil)+ let (model, mock) = makeSUT(contract: loaded)+ await model.load()+ model.beginEditing()++ model.confirmWorkURLCandidate()++ let manual = try makeContract(+ request: .replaceManual(candidate.value), candidate: .available(candidate), resultingURL: candidate.value )- let (model, mock) = makeSUT(contract: contract)- mock.commitWorkURLResult = .success(.committed(workID: contract.basis.workID))- await model.loadWorkURL()+ mock.projectWorkURLResult = .success(manual)+ mock.commitWorkURLResult = .success(.committed(workID: manual.basis.workID)) - await model.confirmWorkURLCandidate()+ await model.commitEditing() - #expect(mock.lastProjectedWorkURLRequest == .confirmCandidate(candidate.value))- #expect(mock.lastWorkURLContract == contract)+ #expect(mock.lastWorkURLContract?.request == .replaceManual(candidate.value)) #expect(mock.commitWorkURLCallCount == 1)- #expect(model.workURLStatusMessage == nil)- #expect(!model.hasUnsavedWorkURLChange)+ #expect(!model.isEditing)+ }++ /// A cancel discards the filled suggestion with every other draft (Q57's+ /// rule, now that the button no longer writes).+ @Test("Cancelling discards a suggestion the reader only filled in")+ @MainActor func cancellingDiscardsTheFilledSuggestion() async throws {+ let candidate = ExactScalarString("https://example.com/series/42")+ let loaded = try makeContract(+ request: .clear, candidate: .available(candidate), resultingURL: nil)+ let (model, mock) = makeSUT(contract: loaded)+ await model.load()+ let opened = model.draftWorkURL+ model.beginEditing()++ model.confirmWorkURLCandidate()+ model.cancelEditing()++ #expect(model.draftWorkURL == opened)+ #expect(mock.commitWorkURLCallCount == 0) } /// Q57: the checkmark is the URL's save. A typed URL lands through the same
diff --git a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swiftindex b5d69dec..963b1d00 100644--- a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift+++ b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift@@ -39,7 +39,13 @@ final class AccessibilityJourneyUITests: XCTestCase { let existingWork = app.buttons.matching(identifier: "move-to-work-destination").firstMatch XCTAssertTrue(existingWork.waitForExistence(timeout: 10), "A same-host Work destination should be exposed") assertContentControl(existingWork, named: "Same-host Work destination")+ // T-2328: the row chooses and the toolbar's Move writes. The sheet is an+ // editor like every other screen. existingWork.tap()+ let move = app.buttons["move-to-submit-button"]+ XCTAssertTrue(move.waitForExistence(timeout: 10), "Move should be offered once a destination is chosen")+ assertSystemControl(move, named: "Move")+ move.tap() XCTAssertTrue( app.navigationBars["Move to"].waitForNonExistence(timeout: 10), "Move-to sheet should dismiss after assignment"
diff --git a/Asterism/AsterismUITests/CreatorRolesSettingsUITests.swift b/Asterism/AsterismUITests/CreatorRolesSettingsUITests.swiftindex 194be56e..57b2947b 100644--- a/Asterism/AsterismUITests/CreatorRolesSettingsUITests.swift+++ b/Asterism/AsterismUITests/CreatorRolesSettingsUITests.swift@@ -254,6 +254,8 @@ final class CreatorRolesSettingsUITests: XCTestCase { /// The one new pattern on this screen: the active rows carry `.onMove` and /// the bar carries the toggle that turns dragging on (Q81, iPhone only).+ /// Since T-2328 (Q99) the drag is a **draft**: it raises the screen's own+ /// Save and Cancel, and only Save writes. /// /// The reorder is asserted **after leaving the screen and coming back**, /// because the model reorders its own rows locally before the write — so an@@ -295,6 +297,19 @@ final class CreatorRolesSettingsUITests: XCTestCase { XCTWaiter().wait(for: [reordered], timeout: 15), .completed, "Req 2.5: the drag moves the role — was \(listedRoles())") + // T-2328: the drag wrote nothing; the screen now offers the two ways+ // out of an unsaved order, and Save is what sends it.+ waitFor(+ app.buttons["settings-creator-roles-order-cancel"],+ "Q99: an unsaved order offers a discard")+ waitFor(+ app.buttons["settings-creator-roles-order-save"],+ "Q99: …and the Save that writes it"+ ).tap()+ waitUntilGone(+ app.buttons["settings-creator-roles-order-save"],+ "…which goes once the order is the store's")+ // Off the screen and back on, so what is asserted is the stored order // rather than the model's local one. app.goBack()
diff --git a/Asterism/AsterismUITests/StatsUITests.swift b/Asterism/AsterismUITests/StatsUITests.swiftindex e05a570a..0b973394 100644--- a/Asterism/AsterismUITests/StatsUITests.swift+++ b/Asterism/AsterismUITests/StatsUITests.swift@@ -467,7 +467,11 @@ final class StatsUITests: XCTestCase { app.buttons["entry-detail-move-to-button"], in: app, "Move to should be reachable") let destination = app.buttons.matching(identifier: "move-to-work-destination").firstMatch XCTAssertTrue(destination.waitForExistence(timeout: 10), "A same-host Work destination should be offered")+ // T-2328: choose, then Move — the sheet writes on its own confirmation. destination.tap()+ let move = app.buttons["move-to-submit-button"]+ XCTAssertTrue(move.waitForExistence(timeout: 10), "Move should be offered once a destination is chosen")+ move.tap() waitUntilGone( app.navigationBars["Move to"], "Move-to sheet should dismiss after assignment", timeout: 15) }
diff --git a/Asterism/AsterismUITests/WorkDetailConnectionsUITests.swift b/Asterism/AsterismUITests/WorkDetailConnectionsUITests.swiftindex f7336068..6b460e04 100644--- a/Asterism/AsterismUITests/WorkDetailConnectionsUITests.swift+++ b/Asterism/AsterismUITests/WorkDetailConnectionsUITests.swift@@ -267,9 +267,9 @@ final class WorkDetailConnectionsUITests: XCTestCase { addedLine.label, "Cold Harbour, sequel", "Req 8.1: the link landed with the type the chip filled in") - // Req 6.5, 7.2: a retype is a free-text edit that commits on the spot.- // Every control that edits the link is in the sheet its line opens- // (Decision 7): the type field, the suggestions and the way off it.+ // Req 6.5, 7.2: a retype is a free-text edit of the draft. Every control+ // that edits the link is in the sheet its line opens (Decision 7): the+ // type field, the suggestions and the way off it. openLinkEditor(to: "Cold Harbour") let typeField = app.textFields["work-detail-link-type-\(identifier)"] waitFor(typeField, "Req 8.1: the editor holds the link's type to edit")@@ -285,31 +285,61 @@ final class WorkDetailConnectionsUITests: XCTestCase { }, object: nil) XCTAssertEqual( XCTWaiter().wait(for: [retyped], timeout: 15), .completed,- "Req 6.5: the retype commits on the tap")+ "Req 6.5: the retype lands in the draft the field holds") closeLinkEditor() waitFor( app.buttons.matching( NSPredicate( format: "identifier == %@ AND label == %@", "work-detail-link-line-\(identifier)", "Cold Harbour, adaptation")).firstMatch,- "Req 6.5: and the line says the type the link now holds")+ "Req 6.5: and the line says the type the draft now holds") - // Req 6.6: and the removal too, which is the sheet's own way off the- // link — so it closes the editor of the link it just unlinked.+ // T-2328, Decision 8: the add and the retype are staged, and the+ // editor's checkmark is what writes them.+ waitFor(app.buttons["work-detail-save-button"], "The checkmark commits the editor").tap()+ waitFor(+ linkRow(typed: "adaptation", to: "Cold Harbour"),+ "…and view mode shows the link the save wrote")++ // Req 6.6: the removal is the sheet's own way off the link — so it+ // closes the editor of the link it just unlinked. It is a draft too, so+ // the X puts the link back.+ //+ // The identifier is re-read here: a staged link is drawn under a+ // draft-local id, and the row the save wrote carries the one the store+ // minted (Q4 of the bugfix log).+ enterEditMode()+ let savedLine = editLinkLine(to: "Cold Harbour")+ scrollUntilPresent(savedLine, in: app, "The saved link is on the page")+ let savedID = String(savedLine.identifier.dropFirst(linePrefix.count))+ XCTAssertFalse(savedID.isEmpty, "The saved line is identified by its stored link") openLinkEditor(to: "Cold Harbour") scrollUntilTappableAndTap(- app.buttons["work-detail-link-remove-\(identifier)"], in: app,+ app.buttons["work-detail-link-remove-\(savedID)"], in: app, "The link editor offers the removal") waitUntilGone( app.anyElement("link-editor"), "…and taking it closes the editor of the link that is gone") waitUntilGone(- app.anyElement("work-detail-link-line-\(identifier)"),+ app.anyElement("work-detail-link-line-\(savedID)"), "Req 6.6: the link is gone from the page") waitFor(app.buttons["work-detail-edit-cancel-button"], "The X leaves the editor").tap()+ waitFor(+ linkRow(typed: "adaptation", to: "Cold Harbour"),+ "T-2328: the X discarded the removal with every other draft")++ // And again, confirmed this time: the checkmark writes it.+ enterEditMode()+ openLinkEditor(to: "Cold Harbour")+ scrollUntilTappableAndTap(+ app.buttons["work-detail-link-remove-\(savedID)"], in: app,+ "The link editor offers the removal a second time")+ waitUntilGone(+ app.anyElement("link-editor"), "…and taking it closes that link's editor")+ waitFor(app.buttons["work-detail-save-button"], "The checkmark commits the removal").tap() waitUntilGone( linkRow(typed: "adaptation", to: "Cold Harbour"),- "…and the removal stands: it was never part of the draft the X discarded (Q24)")+ "Req 6.6: and the link is gone") XCTAssertFalse( app.buttons["work-detail-add-link"].exists, "…and view mode is back to offering nothing: the work has no links again")
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8cd661af..81396f9e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -492,18 +492,23 @@ only the assignment goes back into the draft, and the row survives a cancelled edit (`series-and-related-works` Q16, `work-creators` Req 3.4). Nothing else inside an editor writes before Save. -**Known violations, ticketed as T-2328.** These currently commit on the tap,-outside the draft, and are the reason this rule exists. Do not add to the-list, and do not cite them as precedent:--- adding, retyping or removing a related-work link- (`series-and-related-works` Q24);-- `Use Suggested URL` on the work editor (`polish-and-export` Q57);-- removing a work from a site or from a series;-- the Move To destination tap on an entry;-- drag-reordering creator roles;-- the series editor's Save, which writes the series and then each member- position in separate calls, so a refusal mid-way leaves a partial save.+**There are no standing exceptions beyond the one above.** T-2328 closed the+six that were: related-work links stage in the work editor's draft and commit+through `commitLinkEdits` (`series-and-related-works` Decision 8, superseding+Q24); `Use Suggested URL` fills the draft with a marker and the checkmark+writes it (`polish-and-export` Decision 6, superseding the last clause of+Q57); removing a work from a site stages and commits through+`removeSiteMemberships`; removing one from a series, adding one to it and+every position edit commit together through `commitSeriesEdits`+(`series-and-related-works` Decision 9, Q76); Move To stages a destination and+its toolbar Move writes it; and the creator-roles drag stages the order behind+the screen's own Save and Cancel (`work-creators` Q99). A new write on a tap+inside an editor is a bug, not a precedent — `specs/bugfixes/edit-views-write-before-save/`+has what each of them cost.++One nearby gap is **not** a premature write and is not covered here: on iPad+and Mac the column back button pops an open editor and discards the draft+silently (`work-creators` Q78). Sort order lives in `@AppStorage`; filters, the stats period and chapter sort are per-visit `@State`; none of
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex 735022f9..dd7b2c11 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift@@ -52,6 +52,13 @@ public protocol LibraryProviding: Sendable { /// where neither is true, and the repository is what enforces it. func removeSiteMembership(workID: UUID, hostname: String) async throws + /// Every site removal the work editor staged, in one commit (T-2328).+ ///+ /// The editor holds its removals in the draft until Save, so the seam takes+ /// the whole set: either every staged site goes or none does. Refused by the+ /// same reasons, each naming the site it is about.+ func removeSiteMemberships(workID: UUID, hostnames: [String]) async throws+ /// Sets a site's display name from its own settings screen. /// /// Trimmed; empty after trimming resets the site to its hostname (Q4); a@@ -400,6 +407,13 @@ public protocol LibraryProviding: Sendable { /// series and no member work (Req 1.2). func updateSeries(id: UUID, name: String, notes: String) async throws + /// The series editor's one commit: the name, the notes and every staged+ /// member edit, in one transaction (T-2328). A refused member returns a+ /// conflict with nothing written; an invalid name throws before the lock.+ func commitSeriesEdits(+ seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit]+ ) async throws -> LibraryWriteOutcome+ /// Deletes a series and clears every local member's membership in one /// commit, or refuses (Req 1.4, 2.9, 10.2). func deleteSeries(id: UUID) async throws -> SeriesDeletionOutcome@@ -483,6 +497,11 @@ public protocol LibraryProviding: Sendable { /// link is removable (Req 6.5, 8.3). func removeLink(id: UUID) async throws + /// The work editor's whole session of link edits, applied in the order the+ /// reader performed them and committed once (T-2328). Refuses as the+ /// singular writes above refuse, with nothing written.+ func commitLinkEdits(workID: UUID, operations: [WorkLinkEditOperation]) async throws+ /// Every work but this one, with the reason it cannot be linked where there /// is one (Req 8.2). func linkCandidates(for workID: UUID) async throws -> [WorkPickerCandidate]@@ -569,6 +588,12 @@ public extension LibraryProviding { throw Self.seriesUnsupported } + func commitSeriesEdits(+ seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit]+ ) async throws -> LibraryWriteOutcome {+ throw Self.seriesUnsupported+ }+ func deleteSeries(id: UUID) async throws -> SeriesDeletionOutcome { throw Self.seriesUnsupported }@@ -655,6 +680,10 @@ public extension LibraryProviding { func removeLink(id: UUID) async throws { throw Self.linksUnsupported } + func commitLinkEdits(workID: UUID, operations: [WorkLinkEditOperation]) async throws {+ throw Self.linksUnsupported+ }+ func linkCandidates(for workID: UUID) async throws -> [WorkPickerCandidate] { throw Self.linksUnsupported }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swiftindex 5e05a4a3..08fa19db 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift@@ -3,13 +3,16 @@ import SwiftData // The series surface (Requirements 1, 2 and 3). //-// Seven operations, and only one of them writes to a `Work` row: `deleteSeries`,-// which has to clear the membership of every member in the same commit that-// removes the series (Req 1.4). Everything else the reader does to a membership-// goes through `updateWork` (Q25) — the series screen builds a `WorkEditBasis`-// and a `WorkMetadataDraft` from the member's own snapshot — so the redirect,-// the torn refusal and the conflict machinery are the ones the work editor-// already uses rather than a second write path onto the same two columns.+// Eight operations, and two of them write to a `Work` row: `deleteSeries`, which+// has to clear the membership of every member in the same commit that removes+// the series (Req 1.4), and `commitSeriesEdits`, which is the series screen's+// one Save (Decision 9, T-2328). Both resolve each member through+// `resolveWorkWriteTarget` against the member's own basis, so the redirect, the+// torn refusal and the conflict machinery are the ones the work editor already+// uses (Q25) rather than a second write path onto the same two columns. What+// `commitSeriesEdits` does not do is rewrite the member's other columns: a+// series edit is about the series pair, and the rest was only `updateWork`'s+// shape showing through. // // One helper decides where a work *is*: `presentedMembership(of:)` reads the // carrier's pair, so a torn group whose rows name two series is counted, placed@@ -269,6 +272,84 @@ extension LibraryRepository { } } + /// The series editor's **one** commit: the name, the notes and every member+ /// edit the session staged, in one transaction (T-2328, Decision 9).+ ///+ /// `SeriesDetailModel.save()` used to call `updateSeries` and then one+ /// `updateWork` per member, so an unparseable position halfway down the list+ /// left the name written and some positions written and others not. Every+ /// other editor in the app commits once; this is that, for this screen.+ ///+ /// The conflict machinery is the work editor's, as Q25 asked: each member is+ /// resolved through `resolveWorkWriteTarget` against its own basis, and a+ /// torn member refuses. What this does **not** do is rewrite each member's+ /// whole metadata — the series pair is what a series edit is about, and+ /// writing the other columns back was only ever `updateWork`'s shape+ /// showing through. The first refusal returns before the save, so nothing+ /// lands.+ ///+ /// Value-guarded throughout: a save that changed nothing writes nothing and+ /// so stamps nothing, which is what keeps a re-save off the sync wire.+ public func commitSeriesEdits(+ seriesID: UUID, name: String, notes: String, members: [SeriesMemberEdit]+ ) async throws -> LibraryWriteOutcome {+ let trimmedName = try SeriesName.validate(name)+ let trimmedNotes = notes.trimmingCharacters(in: .whitespacesAndNewlines)+ for member in members {+ guard let membership = member.membership else { continue }+ guard membership.seriesID == seriesID else {+ throw LibraryRepositoryError.invalidInput(+ operation: "committing series edits",+ reason: "a member edit names another series")+ }+ // `updateWork`'s rule (Req 2.2, Q15), restated for the path that no+ // longer goes through it: a position is finite and carries at most+ // one fraction digit.+ guard membership.position.isFinite,+ membership.position == SeriesPosition.rounded(membership.position)+ else {+ throw LibraryRepositoryError.invalidInput(+ operation: "committing series edits",+ reason: "series position must be finite with at most one fraction digit")+ }+ }+ return try await withLockedContext(+ mode: .exclusive, operation: "committing series edits"+ ) { context in+ let rows = try context.fetch(+ FetchDescriptor<Series>(predicate: #Predicate { $0.id == seriesID }))+ guard !rows.isEmpty else {+ throw LibraryRepositoryError.recordNotFound(type: "Series", id: seriesID)+ }+ let timestamp = MillisecondInstant.quantize(self.clock.now())+ for row in rows where row.name != trimmedName || row.notes != trimmedNotes {+ row.name = trimmedName+ row.notes = trimmedNotes+ row.modifiedAt = timestamp+ }+ for member in members {+ let group: WorkGroup+ switch try self.resolveWorkWriteTarget(+ id: member.workID, basis: member.basis, context: context) {+ case .refused(let conflict): return .conflict(conflict)+ case .resolved(let resolved): group = resolved+ }+ if let refusal = Self.tornRefusal(group) { return refusal }+ for work in group.rows+ where work.seriesID != member.membership?.seriesID+ || work.seriesPosition != member.membership?.position {+ // Req 2.8's pair, written as a pair to every row of the+ // group: both set, or both nil.+ work.seriesID = member.membership?.seriesID+ work.seriesPosition = member.membership?.position+ work.modifiedAt = timestamp+ }+ }+ try self.commit(context, operation: "committing series edits")+ return .committed+ }+ }+ /// Req 1.4: the series goes and every member's membership is cleared, in one /// commit, with every member staying in the library. ///
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swiftindex 29e57b0d..dfe09dca 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swift@@ -117,50 +117,73 @@ extension LibraryRepository { /// Work: leaving the site on the twin would put it straight back on the next /// read. public func removeSiteMembership(workID: UUID, hostname: String) async throws {+ try await removeSiteMemberships(workID: workID, hostnames: [hostname])+ }++ /// The same removal over **every site the editor staged**, in one+ /// transaction (T-2328).+ ///+ /// The work editor holds its removals in the draft and sends them at Save,+ /// so a reader who took a work off two sites gets one commit: either both+ /// rows go or neither does, and the library is validated once, over every+ /// hostname the step touched. An empty set writes nothing.+ ///+ /// The singular entry point above is this call with one hostname; the two+ /// refuse alike, and each refusal still names the site it is about.+ public func removeSiteMemberships(workID: UUID, hostnames removed: [String]) async throws {+ let doomed = Set(removed)+ guard !doomed.isEmpty else { return } try await withLockedContext( mode: .exclusive, operation: "removing a site membership" ) { context in let group = try Self.fetchWorkGroup(id: workID, context: context)- guard group.rows.contains(where: { $0.membership(for: hostname) != nil }) else {- throw LibraryRepositoryError.invalidInput(- operation: "removeSiteMembership",- reason: "This Work is not on \(hostname).")+ for hostname in doomed.sorted() {+ guard group.rows.contains(where: { $0.membership(for: hostname) != nil }) else {+ throw LibraryRepositoryError.invalidInput(+ operation: "removeSiteMembership",+ reason: "This Work is not on \(hostname).")+ }+ guard !group.rows.contains(where: { row in+ row.entryValues.contains { $0.hostname == hostname }+ }) else {+ throw LibraryRepositoryError.invalidInput(+ operation: "removeSiteMembership",+ reason: "This Work still has notes on \(hostname).")+ } } // Every row's memberships, because the group is one Work: a row that- // still holds another hostname is what keeps Req 1.3 true.+ // still holds another hostname is what keeps Req 1.3 true. Measured+ // against the **whole** staged set, so two removals that would each+ // be legal alone but empty the work between them are refused+ // together. let remaining = Set(group.rows.flatMap { $0.membershipValues.map(\.hostname) })- .subtracting([hostname])+ .subtracting(doomed) guard !remaining.isEmpty else { throw LibraryRepositoryError.invalidInput( operation: "removeSiteMembership", reason: "A Work must stay on at least one site.") }- guard !group.rows.contains(where: { row in- row.entryValues.contains { $0.hostname == hostname }- }) else {- throw LibraryRepositoryError.invalidInput(- operation: "removeSiteMembership",- reason: "This Work still has notes on \(hostname).")- } // Q55: by predicate, never through `work.siteMemberships` — an // inverse array hands back future-backed rows, and deleting one and // then rolling back (which the validation below does) crashes // SwiftData in snapshot creation. let rowIDs = Set(group.rows.map(\.id))- var removed: Set<UUID> = []+ // An `Array` rather than the `Set`: `#Predicate` lowers+ // `Array.contains` to a store expression, which is the shape every+ // other predicated fetch here takes.+ let doomedHostnames = doomed.sorted() for row in try context.fetch(FetchDescriptor<WorkSiteMembership>(- predicate: #Predicate { $0.hostname == hostname }))+ predicate: #Predicate { doomedHostnames.contains($0.hostname) })) where row.workID.map(rowIDs.contains) == true {- removed.insert(row.id) context.delete(row) } - // Task 8 review: **every** hostname of the Work, not just the one+ // Task 8 review: **every** hostname of the Work, not just the ones // being removed. A removal on a two-site Work changes what the other // site's graph looks like too — the Work is still on it — and // validating one site would leave the other unchecked.- let hostnames = Set(remaining).union([hostname])+ let hostnames = Set(remaining).union(doomed) let diagnoses: [String: LibraryValidationError] do { diagnoses = try LibraryValidator.validate(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swiftindex 08f78aca..0ab9e6be 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swift@@ -3,12 +3,17 @@ import SwiftData // The related-work link surface (Requirements 6, 7 and 8). //-// Five operations, and **none of them writes to a `Work` row**. That is Q17's+// Six operations, and **none of them writes to a `Work` row**. That is Q17's // rule rather than an accident of implementation: a link is its own row with its // own timestamps (Decision 5), so a retype must not stamp either work and-// reshuffle the works list under a date sort. It is also why link edits commit-// immediately rather than joining the work's edit draft (Q24) — folding them in-// would make a link edit wait on, and conflict with, unrelated field edits.+// reshuffle the works list under a date sort. It is also why the reader's whole+// session of link edits commits through `commitLinkEdits` rather than riding+// `updateWork`: a session that only retyped a link must not stamp the work.+//+// The three singular writes below are the primitives, and since Decision 8+// (T-2328) **no editor calls them**. The work editor stages its adds, retypes+// and removals in the draft and hands the sequence to `commitLinkEdits`, which+// applies them in one transaction — Q24's commit-on-the-tap is superseded. // // A link is **undirected** (Decision 4): the pair is spelled through // `WorkDistinctPair.sortedIDs`, exactly as the dismissal table spells one, so@@ -69,6 +74,21 @@ public struct WorkLinkSnapshot: Equatable, Sendable, Identifiable { extension WorkLinkSnapshot: LinkSurvivorCandidate {} +/// One staged related-work edit, as the work editor holds it until Save+/// (T-2328).+///+/// `RecordEditOperation`'s shape and its contract: the reader's session is a+/// **sequence**, applied in the order they performed it and committed once.+/// The three cases are the three writes the editor used to make on the tap.+public enum WorkLinkEditOperation: Sendable, Equatable {+ /// A link the editor staged but has not created yet, so it names the other+ /// end rather than a link id — a staged add has no row and no identity in+ /// the store until this commit mints one.+ case add(otherWorkID: UUID, type: String)+ case retype(linkID: UUID, type: String)+ case remove(linkID: UUID)+}+ extension LibraryRepository { // MARK: - Writing@@ -152,6 +172,105 @@ extension LibraryRepository { if let refusal { throw refusal } } + /// One work editor's whole session of link edits, in one transaction+ /// (T-2328, Decision 8 of `series-and-related-works`).+ ///+ /// The three writes above, applied **in the order the reader performed+ /// them** and committed once — `commitRecordEdits`' contract, for its+ /// reason: a session that added a link, retyped it and removed another is+ /// one intention, and a partial commit would be unreviewable. The first+ /// refusal ends the step with **nothing written**: the context is this+ /// call's own and is discarded unsaved, so an early return is the rollback.+ ///+ /// A refusal is thrown rather than returned, exactly as the singular writes+ /// throw theirs, so the models keep wording it through+ /// `SeriesRefusalPresentation`.+ ///+ /// Only links **this work is an end of** are named: a staged add carries the+ /// other end, and a retype or a removal carries a stored link's id. A link+ /// added in this same step is never retyped or removed by it — the editor+ /// folds both into the add it has not sent yet — so nothing here has to see+ /// its own pending inserts through a fetch.+ public func commitLinkEdits(+ workID: UUID, operations: [WorkLinkEditOperation]+ ) async throws {+ guard !operations.isEmpty else { return }+ // Validated outside the lock, as the singular writes validate theirs: a+ // type the vocabulary refuses is the reader's typo, and it should not+ // cost a write lock to say so.+ var validated: [WorkLinkEditOperation] = []+ for operation in operations {+ switch operation {+ case .add(let otherWorkID, let type):+ guard otherWorkID != workID else { throw WorkLinkError.selfLink }+ validated.append(+ .add(otherWorkID: otherWorkID, type: try LinkType.validate(type)))+ case .retype(let linkID, let type):+ validated.append(.retype(linkID: linkID, type: try LinkType.validate(type)))+ case .remove:+ validated.append(operation)+ }+ }+ let refusal: WorkLinkError? = try await withLockedContext(+ mode: .exclusive, operation: "committing related-work links"+ ) { context in+ let timestamp = MillisecondInstant.quantize(self.clock.now())+ // The pairs this step has already staged, so a session that added+ // the same work twice is refused by the same sentence a stored+ // duplicate earns — a pending insert is not reliably visible to a+ // predicated fetch.+ var staged: Set<WorkPairKey> = []+ for operation in validated {+ switch operation {+ case .add(let otherWorkID, let type):+ let types = try Self.workTypeDirectory(context: context)+ let groups = try Self.workGroups(+ ofIDs: [workID, otherWorkID], context: context, types: types)+ for id in [workID, otherWorkID] where groups[id] == nil {+ throw LibraryRepositoryError.recordNotFound(type: "Work", id: id)+ }+ if let torn = Self.firstTorn(groups, isTorn: \.isTorn) {+ return .torn(workID: torn)+ }+ let sorted = WorkDistinctPair.sortedIDs(workID, otherWorkID)+ let pair = WorkPairKey(workID, otherWorkID)+ if staged.contains(pair) {+ return .alreadyLinked(type: type)+ }+ if let existing = try Self.link(+ over: workID, and: otherWorkID, context: context) {+ return .alreadyLinked(type: existing.linkType)+ }+ staged.insert(pair)+ context.insert(+ WorkLink(+ lowerWorkID: sorted.lower, higherWorkID: sorted.higher,+ linkType: type, createdAt: timestamp, modifiedAt: timestamp))+ case .retype(let linkID, let type):+ let link = try Self.requireLink(id: linkID, context: context)+ if let torn = try Self.tornEnd(of: link, context: context) {+ return .torn(workID: torn)+ }+ // Q17 through the batch: a type equal to the stored one+ // stamps nothing. The editor already drops an untouched+ // field; this is the repository saying the same thing.+ guard link.linkType != type else { continue }+ link.linkType = type+ link.modifiedAt = timestamp+ case .remove(let linkID):+ let link = try Self.requireLink(id: linkID, context: context)+ if let torn = try Self.tornEnd(of: link, context: context) {+ return .torn(workID: torn)+ }+ context.delete(link)+ }+ }+ try self.commit(context, operation: "committing related-work links")+ return nil+ }+ if let refusal { throw refusal }+ }+ // MARK: - Reading /// Req 8.2's picker: every work **other than this one**, with the reason it
diff --git a/Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift b/Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swiftindex 160b9c9b..8e772d42 100644--- a/Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift@@ -32,6 +32,24 @@ public struct SeriesMembership: Equatable, Hashable, Sendable { } } +/// One member as the series editor's draft holds it, for the one commit that+/// writes the whole editor (T-2328).+///+/// The basis is the member's own loaded snapshot, so the redirect and the torn+/// refusal are the work editor's (Q25). A `nil` membership is the member+/// leaving the series — the removal the screen used to commit on the tap.+public struct SeriesMemberEdit: Equatable, Sendable {+ public let workID: UUID+ public let basis: WorkEditBasis+ public let membership: SeriesMembership?++ public init(workID: UUID, basis: WorkEditBasis, membership: SeriesMembership?) {+ self.workID = workID+ self.basis = basis+ self.membership = membership+ }+}+ // MARK: - Display /// A series as a reader sees it, composed by Core so no surface builds a label
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipRemovalTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipRemovalTests.swiftindex be0ddf66..21010501 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipRemovalTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipRemovalTests.swift@@ -60,6 +60,81 @@ struct MembershipRemovalTests { // membership after every write this test made. } + /// T-2328: the work editor stages its removals and sends them at Save, so+ /// the seam takes the whole set and either all of them go or none do.+ @Test("removeSiteMemberships drops every staged site in one commit")+ func removesAStagedSet() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.seedM5Rows(+ sites: [+ M5SeedSite(hostname: "first.example"),+ M5SeedSite(hostname: "second.example"),+ M5SeedSite(hostname: "third.example"),+ ],+ works: [+ M5SeedWork(id: Self.workID, displayTitle: "A Serial", hostname: "first.example")+ ])+ try await fixture.repository.seedMembership(+ workID: Self.workID, hostname: "second.example",+ createdAt: M5Fixture.epoch.addingTimeInterval(120))+ try await fixture.repository.seedMembership(+ workID: Self.workID, hostname: "third.example",+ createdAt: M5Fixture.epoch.addingTimeInterval(180))++ try await fixture.repository.removeSiteMemberships(+ workID: Self.workID, hostnames: ["second.example", "third.example"])++ #expect(+ try await fixture.repository.membershipRows(of: Self.workID).map(\.hostname)+ == ["first.example"])+ }++ /// Two removals that would each be legal alone but empty the Work between+ /// them are refused together (Req 1.3), and nothing is deleted.+ @Test("A staged set that would empty the Work is refused whole")+ func refusesASetThatEmptiesTheWork() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.seedM5Rows(+ sites: [+ M5SeedSite(hostname: "first.example"),+ M5SeedSite(hostname: "second.example"),+ ],+ works: [+ M5SeedWork(id: Self.workID, displayTitle: "A Serial", hostname: "first.example")+ ])+ try await fixture.repository.seedMembership(+ workID: Self.workID, hostname: "second.example",+ createdAt: M5Fixture.epoch.addingTimeInterval(120))++ await #expect(throws: LibraryRepositoryError.self) {+ try await fixture.repository.removeSiteMemberships(+ workID: Self.workID, hostnames: ["first.example", "second.example"])+ }+ #expect(try await fixture.repository.membershipRows(of: Self.workID).count == 2)+ }++ /// One bad site in the set refuses the set: the other removal does not+ /// land on its own.+ @Test("A refused site in the set leaves the rest alone")+ func oneRefusalRefusesTheSet() async throws {+ let fixture = try await twoSiteFixture()++ await #expect(throws: LibraryRepositoryError.self) {+ try await fixture.repository.removeSiteMemberships(+ workID: Self.workID, hostnames: ["first.example", "second.example"])+ }+ #expect(try await fixture.repository.membershipRows(of: Self.workID).count == 2)+ }++ @Test("An empty staged set writes nothing")+ func anEmptySetWritesNothing() async throws {+ let fixture = try await twoSiteFixture()++ try await fixture.repository.removeSiteMemberships(workID: Self.workID, hostnames: [])++ #expect(try await fixture.repository.membershipRows(of: Self.workID).count == 2)+ }+ @Test("A membership holding Entries is refused") func refusesAMembershipWithEntries() async throws { let fixture = try await twoSiteFixture()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swiftindex 90c7ca51..17f5ccea 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/SeriesRepositoryTests.swift@@ -131,6 +131,134 @@ struct SeriesRepositoryTests { #expect(try await fixture.repository.workRowModifiedAt(of: work.id) == before) } + // MARK: - The series editor's one commit (T-2328, Decision 9)++ /// The name, the notes, a position edit and a removal in one transaction,+ /// under one stamp.+ @Test("commitSeriesEdits writes the name, the notes and every member at once")+ func commitSeriesEditsWritesTheWholeEditor() async throws {+ let clock = SeriesMutableClock(M5Fixture.epoch)+ let fixture = try await M5Fixture(clock: clock)+ let seriesID = try await fixture.repository.createSeries(name: "Ashfall", notes: "")+ let moved = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Book One", hostname: Self.hostname))+ let leaving = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Book Two", hostname: Self.hostname))+ try await fixture.repository.forceMembership(+ of: moved.id, seriesID: seriesID, position: 1)+ try await fixture.repository.forceMembership(+ of: leaving.id, seriesID: seriesID, position: 2)++ clock.set(M5Fixture.epoch.addingTimeInterval(900))+ let outcome = try await fixture.repository.commitSeriesEdits(+ seriesID: seriesID, name: " Ashfall Cycle ", notes: " read in order ",+ members: [+ SeriesMemberEdit(+ workID: moved.id,+ basis: WorkEditBasis(work: try await fixture.repository.work(id: moved.id)),+ membership: SeriesMembership(seriesID: seriesID, position: 2.5)),+ SeriesMemberEdit(+ workID: leaving.id,+ basis: WorkEditBasis(work: try await fixture.repository.work(id: leaving.id)),+ membership: nil),+ ])++ #expect(outcome == .committed)+ let row = try #require(try await fixture.repository.seriesRowValues().first)+ #expect(row.name == "Ashfall Cycle")+ #expect(row.notes == "read in order")+ #expect(try await fixture.repository.work(id: moved.id).membership+ == SeriesMembership(seriesID: seriesID, position: 2.5))+ #expect(try await fixture.repository.work(id: leaving.id).membership == nil)+ // The member's other fields are untouched: this commit writes the two+ // series columns and nothing else.+ #expect(try await fixture.repository.work(id: leaving.id).displayTitle == "Book Two")+ }++ /// A torn member refuses the whole save, and the name it was going to+ /// change goes with it — which is the defect Decision 9 exists to fix.+ @Test("A refused member leaves the name and every other member unwritten")+ func commitSeriesEditsRefusesWholesale() async throws {+ let fixture = try await M5Fixture()+ let seriesID = try await fixture.repository.createSeries(name: "Ashfall", notes: "")+ let whole = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Book One", hostname: Self.hostname))+ try await fixture.repository.forceMembership(+ of: whole.id, seriesID: seriesID, position: 1)+ let tornID = UUID()+ try await fixture.repository.seedM5Rows(+ works: [+ M5SeedWork(+ id: tornID, displayTitle: "Torn", hostname: Self.hostname,+ genericNotes: "one reader's notes"),+ M5SeedWork(+ id: tornID, displayTitle: "Torn", hostname: Self.hostname,+ genericNotes: "the other's"),+ ])+ let wholeBasis = WorkEditBasis(work: try await fixture.repository.work(id: whole.id))+ let tornBasis = WorkEditBasis(work: try await fixture.repository.work(id: tornID))++ let outcome = try await fixture.repository.commitSeriesEdits(+ seriesID: seriesID, name: "Ashfall Cycle", notes: "",+ members: [+ SeriesMemberEdit(+ workID: whole.id, basis: wholeBasis,+ membership: SeriesMembership(seriesID: seriesID, position: 5)),+ SeriesMemberEdit(+ workID: tornID, basis: tornBasis,+ membership: SeriesMembership(seriesID: seriesID, position: 6)),+ ])++ guard case .conflict = outcome else {+ Issue.record("expected a conflict, got \(outcome)")+ return+ }+ #expect(try await fixture.repository.seriesRowValues().first?.name == "Ashfall")+ #expect(try await fixture.repository.work(id: whole.id).membership+ == SeriesMembership(seriesID: seriesID, position: 1))+ }++ /// Value-guarded: a save that changes nothing stamps nothing, so a re-save+ /// puts nothing on the sync wire.+ @Test("A commit that changes nothing stamps nothing")+ func commitSeriesEditsIsValueGuarded() async throws {+ let clock = SeriesMutableClock(M5Fixture.epoch)+ let fixture = try await M5Fixture(clock: clock)+ let seriesID = try await fixture.repository.createSeries(+ name: "Ashfall", notes: "read in order")+ let work = try await fixture.repository.createWork(+ NewWorkDraft(displayTitle: "Book One", hostname: Self.hostname))+ try await fixture.repository.forceMembership(+ of: work.id, seriesID: seriesID, position: 1)+ let seriesBefore = try #require(try await fixture.repository.seriesRowValues().first)+ let workBefore = try await fixture.repository.workRowModifiedAt(of: work.id)++ clock.set(M5Fixture.epoch.addingTimeInterval(900))+ _ = try await fixture.repository.commitSeriesEdits(+ seriesID: seriesID, name: "Ashfall", notes: "read in order",+ members: [+ SeriesMemberEdit(+ workID: work.id,+ basis: WorkEditBasis(work: try await fixture.repository.work(id: work.id)),+ membership: SeriesMembership(seriesID: seriesID, position: 1)),+ ])++ #expect(try await fixture.repository.seriesRowValues().first == seriesBefore)+ #expect(try await fixture.repository.workRowModifiedAt(of: work.id) == workBefore)+ }++ @Test("commitSeriesEdits refuses an invalid name before the lock")+ func commitSeriesEditsRefusesAnInvalidName() async throws {+ let fixture = try await M5Fixture()+ let seriesID = try await fixture.repository.createSeries(name: "Ashfall", notes: "")++ await #expect(throws: SeriesError.self) {+ _ = try await fixture.repository.commitSeriesEdits(+ seriesID: seriesID, name: " ", notes: "", members: [])+ }+ #expect(try await fixture.repository.seriesRowValues().first?.name == "Ashfall")+ }+ // MARK: - Counting through the presented membership (Reqs 3.4, 9.7) @Test("A torn group whose rows name two series counts in exactly one")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkLinkTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkLinkTests.swiftindex d335a837..de2e7a30 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkLinkTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkLinkTests.swift@@ -216,6 +216,129 @@ struct WorkLinkTests { == ["adaptation"]) } + // MARK: - The editor's one commit (T-2328, Decision 8)++ /// The work editor stages its whole session and hands it over once: adds,+ /// retypes and removals apply in the order the reader performed them, under+ /// one stamp, in one transaction.+ @Test("commitLinkEdits applies a whole session in order, in one commit")+ func commitLinkEditsAppliesTheSession() async throws {+ let clock = SeriesMutableClock(M5Fixture.epoch.addingTimeInterval(300))+ let fixture = try await M5Fixture(clock: clock)+ let works = try await Self.seedPair(+ fixture, titles: ["Novel", "Webtoon", "Drama", "Radio"])+ let doomed = UUID()+ let retyped = UUID()+ try await fixture.repository.seedWorkLinks([+ SeedWorkLink(id: doomed, a: works[0], b: works[1], type: "adaptation"),+ SeedWorkLink(id: retyped, a: works[0], b: works[2], type: "sequel"),+ ])++ try await fixture.repository.commitLinkEdits(+ workID: works[0],+ operations: [+ .remove(linkID: doomed),+ .retype(linkID: retyped, type: " spin-off "),+ .add(otherWorkID: works[3], type: "adaptation"),+ ])++ let rows = try await fixture.repository.workLinkRowValues()+ #expect(Set(rows.map(\.linkType)) == ["spin-off", "adaptation"])+ #expect(rows.count == 2)+ #expect(!rows.contains { $0.id == doomed })+ let stamp = MillisecondInstant.quantize(M5Fixture.epoch.addingTimeInterval(300))+ #expect(rows.allSatisfy { $0.modifiedAt == stamp })+ }++ /// A retype whose type is what the row already holds stamps nothing: Q27+ /// reads that stamp to decide a duplicated pair's survivor.+ @Test("commitLinkEdits leaves an unchanged type unstamped")+ func commitLinkEditsSkipsAnUnchangedType() async throws {+ let clock = SeriesMutableClock(M5Fixture.epoch.addingTimeInterval(120))+ let fixture = try await M5Fixture(clock: clock)+ let works = try await Self.seedPair(fixture)+ let id = UUID()+ try await fixture.repository.seedWorkLinks([+ SeedWorkLink(id: id, a: works[0], b: works[1], type: "adaptation")+ ])+ let before = try await fixture.repository.workLinkRowValues()++ clock.set(M5Fixture.epoch.addingTimeInterval(900))+ try await fixture.repository.commitLinkEdits(+ workID: works[0], operations: [.retype(linkID: id, type: "adaptation")])++ #expect(try await fixture.repository.workLinkRowValues() == before)+ }++ /// The first refusal ends the step with **nothing** written — the whole+ /// point of one commit over three.+ @Test("A refused operation rolls the whole session back")+ func commitLinkEditsRefusesWholesale() async throws {+ let fixture = try await M5Fixture()+ let works = try await Self.seedPair(fixture, titles: ["Novel", "Webtoon", "Drama"])+ let existing = UUID()+ try await fixture.repository.seedWorkLinks([+ SeedWorkLink(id: existing, a: works[0], b: works[1], type: "adaptation")+ ])++ // The removal would land; the add is refused because the pair is+ // already linked. Neither happens.+ await #expect(throws: WorkLinkError.alreadyLinked(type: "adaptation")) {+ try await fixture.repository.commitLinkEdits(+ workID: works[0],+ operations: [+ .add(otherWorkID: works[2], type: "sequel"),+ .add(otherWorkID: works[1], type: "spin-off"),+ ])+ }+ #expect(try await fixture.repository.workLinkIDs() == [existing])+ }++ /// The same pair staged twice in one session is refused like a stored+ /// duplicate: a pending insert is not reliably visible to a fetch, so the+ /// step remembers what it has staged.+ @Test("The same pair staged twice in one session is refused")+ func commitLinkEditsRefusesADoubleStagedPair() async throws {+ let fixture = try await M5Fixture()+ let works = try await Self.seedPair(fixture)++ await #expect(throws: WorkLinkError.alreadyLinked(type: "sequel")) {+ try await fixture.repository.commitLinkEdits(+ workID: works[0],+ operations: [+ .add(otherWorkID: works[1], type: "adaptation"),+ .add(otherWorkID: works[1], type: "sequel"),+ ])+ }+ #expect(try await fixture.repository.workLinkIDs().isEmpty)+ }++ @Test("commitLinkEdits validates every type before it takes the lock")+ func commitLinkEditsValidatesTypesFirst() async throws {+ let fixture = try await M5Fixture()+ let works = try await Self.seedPair(fixture, titles: ["Novel", "Webtoon", "Drama"])++ await #expect(throws: WorkLinkError.self) {+ try await fixture.repository.commitLinkEdits(+ workID: works[0],+ operations: [+ .add(otherWorkID: works[1], type: "adaptation"),+ .add(otherWorkID: works[2], type: " "),+ ])+ }+ #expect(try await fixture.repository.workLinkIDs().isEmpty)+ }++ @Test("An empty session writes nothing")+ func commitLinkEditsWithNothingStagedWritesNothing() async throws {+ let fixture = try await M5Fixture()+ let works = try await Self.seedPair(fixture)++ try await fixture.repository.commitLinkEdits(workID: works[0], operations: [])++ #expect(try await fixture.repository.workLinkIDs().isEmpty)+ }+ // MARK: - Type suggestions (Req 7.1) /// The seeded five lead, then every distinct type in the library folded
diff --git a/specs/bugfixes/edit-views-write-before-save/decision_log.md b/specs/bugfixes/edit-views-write-before-save/decision_log.mdnew file mode 100644index 00000000..25ebe539--- /dev/null+++ b/specs/bugfixes/edit-views-write-before-save/decision_log.md@@ -0,0 +1,18 @@+# Decision Log: Edit views write before Save++The decisions that change a *feature's* recorded position live in that feature's+log, not here: `series-and-related-works` Decisions 8 and 9 and Q76,+`polish-and-export` Decision 6, and `work-creators` Q99. What follows is what this+bugfix settled that no feature owns.++## Quick Decisions++| ID | Date | Decision | Rationale |+|----|------|----------|-----------|+| Q1 | 2026-09-22 | The Move To sheet gains a Save: the destination rows choose (with a checkmark), the toolbar's Move writes, and closing the sheet writes nothing | It was the one reader action in the app with no Save at all — a single tap that moved an entry, with the sheet's X reading as a cancel that was not one. No decision had ever been recorded for it |+| Q2 | 2026-09-22 | Tapping the chosen destination again clears the choice | The sheet needs a way back to "nothing picked" that is not closing it, and a checkmark that only ever turns on is a control the reader cannot undo |+| Q3 | 2026-09-22 | The work editor's new steps run **last** in `commitEditing`, after the record step: links, then site removals | Both write their own tables, so neither can join the metadata save. Last rather than first because a refusal there keeps the editor open with the staged edits still on screen and still the reader's to correct, while the field edits the reader also asked for have landed |+| Q4 | 2026-09-22 | A staged link carries a draft-local UUID, never a row identifier | There is no row until the commit mints one. The id keys its type draft and draws its row; nothing outside the model reads it, and the commit names the *other end* rather than the id. The consequence is that the row's accessibility identifier **changes at Save** — the journey re-reads it after the commit rather than carrying the staged one across |+| Q5 | 2026-09-22 | The three singular link writes and the singular `removeSiteMembership` stay in Core as primitives | Their suites are the ones that pin the refusals, and a dev-only fixture path still calls `addLink`. What changed is that no editor calls them |+| Q6 | 2026-09-22 | `WorkDetailModel.load()` prunes the staged link removals and site removals against what the read returned | A staged removal only means something while the row it names is still there. A link another device removed, or a site a merge took off, drops out of the staging with it rather than refusing the next save |+| Q7 | 2026-09-22 | `reloadPresentation()` is deleted rather than kept for a future caller | It existed for the link commit alone. With it goes the only path that replaced the presentation under an open editor — which is why `work-creators` Q52's credit-baseline test now asserts the half that is still reachable rather than the mid-edit re-read |
diff --git a/specs/bugfixes/edit-views-write-before-save/report.md b/specs/bugfixes/edit-views-write-before-save/report.mdnew file mode 100644index 00000000..ea84e0d1--- /dev/null+++ b/specs/bugfixes/edit-views-write-before-save/report.md@@ -0,0 +1,263 @@+# Bugfix Report: Edit views write to the store before Save is pressed++**Date:** 2026-09-22+**Status:** Fixed++## Description of the Issue++CLAUDE.md carries the rule "Edit views save on Save, and only then": an edit view+holds value-type drafts, the store is written once by one repository call when the+reader presses Save, and Cancel restores the drafts. Six controls broke it — they+wrote on the tap, outside the draft — and the rule's own text listed them as known+violations. T-2328 is the owner closing that list.++**Reproduction steps (the shape they all share):**++1. Open a work, a series or the Move To sheet and enter its editor.+2. Tap one of the six controls below.+3. Tap the editor's X (or close the sheet). The change is already in the store,+ and on a synced device it has already left for CloudKit.++The six:++| # | Control | Recorded as |+|---|---|---|+| 1 | Adding, retyping or removing a related-work link | `series-and-related-works` Q24 |+| 2 | `Use Suggested URL` on the work editor | `polish-and-export` Q57 |+| 3 | Remove from site, and Remove from series | — |+| 4 | The Move To destination tap on an entry | — |+| 5 | Drag-reordering creator roles | — |+| 6 | The series editor's Save, which was not atomic | — |++**Impact:** Reader-visible and, for #6, data-losing in a narrow way. A cancelled+edit kept changes the reader had discarded; a refused save left the library+half-edited. #6 is the worst of the six: `SeriesDetailModel.save()` wrote the+series name, then looped over the members writing each position with a separate+call, so an unparseable position — or a conflict — halfway down the list returned+with the name written and some positions written and others not, and no way for+the reader to tell which.++## Investigation Summary++This is a rule-conformance ticket rather than a mystery: the ticket enumerates the+six, and the defect in each is the same shape. The work was in establishing what+each one needs in order to become a draft, and what the repository has to grow so+one Save can write it.++- **Symptoms examined:** each control's write path from the view down to+ `LibraryRepository`, and what a cancel or a refusal left behind.+- **Code inspected:** `WorkDetailModel` (links, work URL, memberships,+ `commitEditing`), `SeriesModels` (`save`, `removeMember`, `addMember`, `write`),+ `CreatorRolesModels.move`, `MoveToModel`, and the repository files behind them —+ `LibraryRepository+WorkLinks`, `+Sites`, `+Series`, plus `+RecordEditing` as the+ model for a staged-operations commit.+- **Hypotheses tested and ruled out:**+ - *Fold the link edits into `updateWork`.* Rejected: `updateWork` stamps every+ row of the work group unconditionally, so a session that only retyped a link+ would stamp the work and reshuffle the works list under a date sort — exactly+ what Q17 forbids.+ - *Fill the URL field from the suggestion and rely on the existing dirty check.*+ Ruled out by a red test: the projection **pre-fills** the field with the+ suggestion and the dirty check is against the value the projection gave, so+ filling it changed nothing and Save wrote nothing. The draft needed the+ acceptance, not the text — one marker, the shape the rule already names for a+ prefilled suggestion.+ - *Parse every series position first and keep the per-member loop.* Fixes the+ reported symptom only: a conflict on the third member still leaves the first+ two written.++## Discovered Root Cause++Each of the six was a control that owned its own write, because at the time it was+written there was no draft state that could express what it did and no repository+call that could commit it with the rest of the screen.++**Defect type:** design-rule violation (premature commit), plus one non-atomic+write sequence (#6).++**Why it occurred:** the two recorded ones were deliberate. Q24 kept link edits+immediate because a link is its own row with its own timestamps and folding it into+`updateWork` would have made a retype stamp the work. Q57 kept `Use Suggested URL`+immediate because `.confirmCandidate` approves one exact projected value, "which is+not a thing a free-text draft can express". Both arguments are about the *write*,+and both are answered by giving the draft somewhere to put the intent and the+repository a call that commits it: a staged operation list for the links, one+boolean marker for the URL. The four unrecorded ones had no decision behind them at+all.++**Contributing factors:** the work editor already committed in several steps (URL,+metadata, records), so "one more step" was an easy thing to add; and the series+screen's per-member `updateWork` (Q25) was chosen for its conflict machinery, which+came bundled with writing the member's whole metadata — a width that has twice+needed new columns threaded through it to avoid silently clearing them.++## Resolution for the Issue++Every one of the six now stages in the view model and commits at Save, and three+new repository calls exist to commit a whole draft in one transaction.++**Core:**++- `LibraryRepository+WorkLinks.swift` — `WorkLinkEditOperation` (`add`, `retype`,+ `remove`) and `commitLinkEdits(workID:operations:)`: the session's operations in+ the order the reader performed them, one stamp, one save. The first refusal+ returns before the save, so nothing lands. A retype to the stored type stamps+ nothing (Q27 reads that stamp). The three singular writes stay as primitives; no+ editor calls them.+- `LibraryRepository+Sites.swift` — `removeSiteMemberships(workID:hostnames:)`:+ every staged site in one commit, with the last-site guard measured against the+ whole set and one validation pass over every hostname touched.+ `removeSiteMembership` is now that call with one hostname.+- `LibraryRepository+Series.swift` — `commitSeriesEdits(seriesID:name:notes:members:)`+ and `SeriesMemberEdit`: the name, the notes and every member edit in one+ transaction. Each member is resolved through `resolveWorkWriteTarget` against its+ own basis and refused if torn (Q25's machinery), but only the two series columns+ are written. Value-guarded throughout.++**App:**++- `WorkDetailModel` — staged links (`stagedLinks`, `removedLinkIDs`, a `links`+ computed over the read plus the staging), staged site removals+ (`stagedMembershipRemovals`, with `hostnames`, `siteLinks` and+ `canRemoveMembership` reading the draft), and `confirmWorkURLCandidate()` filling+ the field and setting `acceptedSuggestedURL`. `commitEditing()` gained two steps+ after the record step — `commitLinkStep` then `commitMembershipRemovals` — and+ `cancelEditing()` restores all of it. `reloadPresentation()` is gone: the link+ commit was its only caller.+- `SeriesDetailModel` — `members` is now the read plus the session's staged+ removals and additions; `save()` parses every position first, builds one+ `[SeriesMemberEdit]` and makes one call; `removeMember` is synchronous staging;+ `addMember` stages with a prefill raised past anything already staged; the old+ per-member `write` helper is gone.+- `CreatorRolesModel` — `move` stages the order, `saveOrder()` writes it,+ `cancelOrder()` puts the read's order back, and a read landing mid-drag carries+ the staged order over it.+- `MoveToModel` — `Destination`, `select(_:)` and `submit()`; the sheet's rows+ choose and its toolbar Move writes.+- Views: `RelatedWorkEditorView` (no `onSubmit` commit), `WorkDetailView` (the+ suggestion button, the add-link sheet, the removal confirmation's wording),+ `SeriesDetailView`, `CreatorRolesView` (the order's Save/Cancel pair),+ `MoveToView` (selectable rows plus Move).++**Approach rationale:** `commitRecordEdits` had already established the shape for a+staged session — operations applied in order, refused whole — so two of the three+new calls are that shape for another table, and the third is the same idea for a+whole editor. Keeping `updateWork` out of the link and series paths is what+preserves Q17 (a link edit stamps no work) and removes the "carry every column+back" hazard from the series screen.++**Alternatives considered:** recorded in full in the superseding decisions —+`series-and-related-works` Decisions 8 and 9, `polish-and-export` Decision 6 — and+in the quick decisions `series-and-related-works` Q76, `work-creators` Q99 and this+directory's own log.++## Regression Test++Red-first on one of the six: the URL suggestion. "Use Suggested URL fills the field+and writes nothing" failed on `model.hasUnsavedWorkURLChange` against the first+implementation, which proved the pre-filled field could not express acceptance —+the marker is what makes it pass. The rest are covered by the suites below, each+asserting both halves: the tap writes nothing, and Save writes it in one call.++**Core** (`swift test --no-parallel`, via `make test-core`):++| File | Tests |+|---|---|+| `Packages/AsterismCore/Tests/AsterismCoreTests/WorkLinkTests.swift` | `commitLinkEdits` applies a session in order; leaves an unchanged type unstamped; refuses wholesale; refuses a pair staged twice; validates types before the lock; an empty session writes nothing |+| `.../MembershipRemovalTests.swift` | drops every staged site in one commit; refuses a set that would empty the Work; one refusal refuses the set; an empty set writes nothing |+| `.../SeriesRepositoryTests.swift` | writes the name, notes and every member at once; a refused member leaves the name unwritten; value-guarded; refuses an invalid name before the lock |++**App** (`make test-only TEST=AsterismTests/<Suite>`):++| File | Tests |+|---|---|+| `Asterism/AsterismTests/WorkDetailModelTests.swift` | adding/retyping/removing a link stages and commits at Save; a staged pair is refused twice; an unchanged type sends no operation; cancel restores the link section; removing a staged link drops it; a refused link commit keeps the editor; a site removal stages, commits as a batch and restores on cancel |+| `.../WorkURLDetailModelTests.swift` | the suggestion fills the field and writes nothing; Save writes it as `.replaceManual`; cancel discards it |+| `.../SeriesModelsTests.swift` | a conflict refuses the whole save; a removal stages and commits at Save; cancel restores the member list; an addition stages its prefill; two additions do not collide; nothing-to-write takes no lock |+| `.../CreatorRolesModelTests.swift` | a move stages and Save sends the order; cancel restores; a read carries an unsaved order; a failed save restores the store's order |+| `.../MoveToAndNewWorkModelTests.swift` | choosing writes nothing; choosing twice clears; Move is offered only where it can write |++## Affected Files++| File | Change |+|------|--------|+| `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkLinks.swift` | `WorkLinkEditOperation`, `commitLinkEdits` |+| `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Sites.swift` | `removeSiteMemberships`, singular call delegates to it |+| `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Series.swift` | `commitSeriesEdits`, header comment |+| `Packages/AsterismCore/Sources/AsterismCore/SeriesSupport.swift` | `SeriesMemberEdit` |+| `Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift` | three seam methods and their defaults |+| `Asterism/Asterism/ViewModels/WorkDetailModel.swift` | staged links, staged site removals, URL acceptance marker, two commit steps, `reloadPresentation` removed |+| `Asterism/Asterism/ViewModels/SeriesModels.swift` | staged members, one-call `save()`, `write` helper removed |+| `Asterism/Asterism/ViewModels/CreatorRolesModels.swift` | staged order, `saveOrder`, `cancelOrder`, `hasUnsavedOrder` |+| `Asterism/Asterism/ViewModels/MoveToModel.swift` | `Destination`, `select`, `submit` |+| `Asterism/Asterism/Views/RelatedWorkEditorView.swift` | no writes; wording |+| `Asterism/Asterism/Views/WorkDetailView.swift` | suggestion button, add-link, removal wording |+| `Asterism/Asterism/Views/SeriesDetailView.swift` | remove button stages |+| `Asterism/Asterism/Views/CreatorRolesView.swift` | order Save/Cancel toolbar |+| `Asterism/Asterism/Views/MoveToView.swift` | selectable rows, Move |+| `Asterism/AsterismTests/*`, `Packages/.../Tests/*` | the suites above, plus `MockLibraryProvider` |+| `Asterism/AsterismUITests/*` | the Move To journeys now tap Move; the link journey saves, cancels and saves again; the reorder journey taps the order's Save |+| `CLAUDE.md` | known-violations list replaced by what closed it |+| `specs/series-and-related-works/decision_log.md` | Decisions 8 and 9, Q76, Q24 marked superseded |+| `specs/polish-and-export/decision_log.md` | Decision 6, Q57's last clause marked superseded |+| `specs/work-creators/decision_log.md` | Q99 |++## Verification++**Automated:**++- [x] `make test-core` — AsterismCore on the host. Clean apart from+ `PendingCaptureDrainTests`, which fails the same way on `main` on this+ host (57 issues there, unrelated to this change: a keychain/file-protection+ condition the memory note records).+- [x] `make test-quick` — `build-mac` plus the unit bundle on the simulator,+ `Test Succeeded`.+- [x] `make test-only TEST=AsterismTests` — the whole unit bundle, `MAKE EXIT: 0`,+ no issues recorded.+- [x] The four UI journeys these screens changed, each run on its own:+ `WorkDetailConnectionsUITests/testALinkIsAddedRetypedAndRemovedFromTheWorkPage`,+ `AccessibilityJourneyUITests/testSeededRecentEntryAssignmentAndWorkJourney`+ (Move To), `CreatorRolesSettingsUITests/testReorderingTheActiveRolesCommitsAndSurvivesLeavingTheScreen`,+ and `StatsUITests/testSelectingADayBreaksItDownAndRoutesToWorks` (Move To).+ All four pass. `WorkDetailConnectionsUITests` as a whole is green (4/4).+- [x] No new compiler warnings. There is no style linter in this repo;+ `make verify-identity` runs as a `test-core` prerequisite.++One flake seen and dismissed: `AppLibraryModelEmptyLibraryTests`'+`emptyingSettlesEverySurface` failed on two bundle runs and passed on its own+twice and on two later bundle runs. It does real store I/O in a temp root, the+failing runs carried SQLite `disk I/O error` logs, and nothing in this change+touches the empty-library pass or the Today read. It belongs to the family+T-2327 has been working through.++**Manual verification:** none. No `Personal` target, device install or Mac launch+was run — simulator and host only, per the rule at the top of CLAUDE.md. The UI+journeys that touch these screens run on the simulator.++## Prevention++- **The pattern to copy is the staged session.** `commitRecordEdits`,+ `commitLinkEdits` and `commitSeriesEdits` are the same shape: value-type+ operations held in the view model, applied in the order the reader performed+ them, committed once, refused whole. A new control inside an editor should stage+ into that rather than grow a write of its own.+- **A prefilled suggestion needs a marker, not a comparison.** Where the draft is+ seeded with something the reader has not accepted, the acceptance is its own+ piece of draft state. Comparing the text to the seed cannot express it, and the+ next control that tries will reach for an immediate write for the same reason+ `Use Suggested URL` did.+- **A write that loops is a write that can stop halfway.** Any commit that iterates+ over rows belongs in one repository call with one save.+- **CLAUDE.md's rule now has no standing exceptions beyond creating a related+ item.** A control that writes on a tap inside an editor is a bug to be fixed, not+ a precedent to be cited.++## Related++- Transit T-2328+- `specs/bugfixes/edit-views-write-before-save/decision_log.md`+- `specs/series-and-related-works/decision_log.md` — Decisions 8, 9; Q24, Q25, Q27, Q68, Q76+- `specs/polish-and-export/decision_log.md` — Decision 6; Q57+- `specs/work-creators/decision_log.md` — Q52, Q58, Q81, Q99+- Out of scope, its own ticket: the column back button on iPad and Mac pops an open+ editor and discards the draft silently (`work-creators` Q78).
diff --git a/specs/polish-and-export/decision_log.md b/specs/polish-and-export/decision_log.mdindex ad075025..43489468 100644--- a/specs/polish-and-export/decision_log.md+++ b/specs/polish-and-export/decision_log.md@@ -60,7 +60,7 @@ | Q54 | 2026-08-04 | The rating capsules move into the title card, and the capture's date moves out of "Capture details" to a caption directly under the note editor | User feedback after device install: two capsules do not need a section header and a full row of vertical space above the note, and the date is when the note was written — it reads with the note, not with the capture evidence. `entry-detail-rating-*` and `entry-detail-shared` are unchanged; `entry-detail-shared` is now always on screen instead of behind the disclosure | | Q55 | 2026-08-04 | Toolbar confirmations and closes render as glyphs only, everywhere in the app **and** the share extension, via the *label-less* `Button(role:action:)`; the wording moves to `.accessibilityLabel`. Confirmation dialogs and alerts keep their text buttons | Measured on the iOS 26.5 SDK: `Button("Update", role: .confirm)` renders **82.3 pt** wide — the word is drawn beside the checkmark — against 36.0 pt for the icon-only Export item next to it. The label-less `Button(role:)` (iOS 26's `DefaultButtonLabel`) measures 36.0 pt for both `.confirm` and `.close` and keeps the overridden accessibility label. Sheets take `.close` in `.cancellationAction`; pushed screens rely on the back chevron. A dialog is not a bar, so its buttons keep their words | | Q56 | 2026-08-04 | Work detail's chapter rows push entry detail, through the Works stack's existing entry route (and the Merge sheet's own stack where the screen is presented) | User feedback after device install: it was the one list in the app that could not be tapped through to what it listed. Navigation stays `ContentView`'s — the screen reports the tap through `onSelectEntry` — so the destination gets its export model exactly as every other entry-detail route does |-| Q57 | 2026-08-05 | The Work URL section loses its own `Save Work URL` and `Clear Work URL` buttons. The editor's checkmark writes the URL field with everything else, emptying the field *is* the clear, and the X restores it; `work-detail-url-save` and `work-detail-url-clear` are retired. `Use Suggested URL` stays | User feedback after device install: one screen, one save. Two commit buttons inside a form whose toolbar already carries a checkmark taught the reader that some fields save themselves and others do not. The URL still commits through its own contract — the checkmark calls it *before* the metadata save, because a metadata save reloads the screen and a reload re-projects the URL field. The dirty check is against the value the last projection *gave* the field, not against the stored URL, so a pre-filled suggestion is never written by a checkmark that was pressed for the title; accepting a suggestion stays its own button for that reason (`.confirmCandidate` approves one projected value, which free text cannot express). A refused or unusable URL keeps the editor open holding the draft, exactly as a refused title save does |+| Q57 | 2026-08-05 | The Work URL section loses its own `Save Work URL` and `Clear Work URL` buttons. The editor's checkmark writes the URL field with everything else, emptying the field *is* the clear, and the X restores it; `work-detail-url-save` and `work-detail-url-clear` are retired. `Use Suggested URL` stays | User feedback after device install: one screen, one save. Two commit buttons inside a form whose toolbar already carries a checkmark taught the reader that some fields save themselves and others do not. The URL still commits through its own contract — the checkmark calls it *before* the metadata save, because a metadata save reloads the screen and a reload re-projects the URL field. The dirty check is against the value the last projection *gave* the field, not against the stored URL, so a pre-filled suggestion is never written by a checkmark that was pressed for the title; accepting a suggestion stayed its own button for that reason (`.confirmCandidate` approves one projected value, which free text cannot express) — superseded by Decision 6, which keeps the button and makes it fill the draft. A refused or unusable URL keeps the editor open holding the draft, exactly as a refused title save does | | Q58 | 2026-08-05 | Work detail's title renders twice: as a wrapping serif heading (`work-detail-title`, no `lineLimit`) at the head of the view-mode header card, and as the navigation bar's `.inline` collapsed form | User feedback after device install: long serial names were truncated with nowhere to read them in full. A navigation large title is one line whatever its length — the platform gives no way to wrap it — so the full title moves into content, where it can wrap, and the bar keeps the short form it is good at. `.inline` rather than `.large` because a large title would be a second, *truncated* copy of the heading directly above it; a bar title that truncates is standard iOS. Style-guide §10's "truncate rather than wrap" is scoped to rows and stays true of them | | Q59 | 2026-08-05 | Edit mode hides the system back chevron (`.navigationBarBackButtonHidden(model.isEditing)`); the X is the only dismiss control and it returns to *view mode*, never popping the screen | User feedback after device install: the bar offered two ways out that did different things — one discarding the draft into view mode, the other leaving the work entirely with the draft's fate unstated. Q55 left pushed screens relying on the back chevron for closes, which holds for a screen with one mode; a mode has to be left before the screen is. Hiding the button also disables the interactive back-swipe, so the mode has exactly one exit per direction | | Q60 | 2026-08-05 | The share extension's capture sheets commit from the bar too: `CaptureView`'s Save and `ReShareCaptureView`'s Update become the Q47/Q55 label-less `Button(role: .confirm)` in `.confirmationAction`, beside the X those sheets already carry. `capture.save`, `capture.retry` and `reshare.update` keep their identifiers and accessibility labels; `capture.retry` is now the same checkmark under the failed state's identity rather than a second control in the content | User feedback after device install: the extension was the last place a gradient Save survived, so the one sheet a reader sees most often was the one that did not follow the app's convention. Q47's reasoning applies unchanged. Nothing had to move with it — both sheets already replace their whole content with a "Saving…" / "Updating…" spinner while the write is in flight, so the busy indication was never on the button; the checkmark is offered in exactly the states that carried a bottom button and carries those buttons' disabled conditions verbatim |@@ -255,3 +255,43 @@ Keeping the mode in the model rather than the view is what makes the entry and e `WorkDetailView` (rewritten around the two modes; `WorkEditDetailsView` deleted), `WorkDetailModel` (mode state and its three transitions), `ContentView` (the chapter-row route on both the Works stack and the Merge sheet's own stack), and four UI journey suites. Requirement 5.5 and design doc §6. ---++## Decision 6: `Use Suggested URL` fills the draft; the editor's Save writes it++**Date**: 2026-09-22+**Status**: accepted, superseding the last clause of Q57++### Context++Q57 took the Work URL section's own `Save Work URL` and `Clear Work URL` buttons away — one screen, one save — but kept `Use Suggested URL` as an immediate write, on the argument that the request it sends, `.confirmCandidate`, is the reader approving *that exact projected value*, which a free-text draft cannot express.++The draft cannot express it for a specific reason: the projection **pre-fills** the field with the suggestion, and the dirty check is against the value the projection gave the field. So the text alone cannot say whether the reader meant the suggestion or merely opened the editor on a work that has one.++CLAUDE.md's rule now states the general form of the answer: "A rule suggestion, an extracted character or place, or a cropped cover is prefilled into the draft — with a marker where the draft has one — and accepted by the ordinary Save; nothing is written without acceptance." The Work URL is the same situation, and it was the only prefilled suggestion still writing on the tap.++### Decision++`Use Suggested URL` puts the suggested value in the field and sets an accepted-suggestion marker on the draft. The marker makes the URL half dirty, so the editor's checkmark writes it as `.replaceManual` with everything else the reader changed, and the X discards it with everything else. The marker is cleared by every projection that re-seeds the field and by the cancel that discards it. `.confirmCandidate` stays in Core for the post-teaching handoff, which is not an editor.++### Rationale++The value being approved is a string, and a string is exactly what the draft holds; what the draft lacked was the *acceptance*, which is one boolean. `WorkURLPlanner.project` stores the same address for `.confirmCandidate` and `.replaceManual` — the two arms differ only in what they validate — so nothing about the stored result changes.++Q57's own sentence, "one screen, one save", is the reason: a reader who accepted a suggestion and then cancelled the edit had already written the URL, which is the behaviour the rest of that decision removed.++### Alternatives Considered++- **Keep the immediate write**: Q57's answer - Rejected by the rule: it is the last control inside an editor that writes on the tap, and it is why the section still needed explaining.+- **Send `.confirmCandidate` from the editor's Save instead of `.replaceManual`**: Keeps the exact-value approval at the commit - Rejected: the commit would have to re-project to find the candidate and then refuse the save if the suggestion had moved, which turns a suggestion the reader accepted into a failed save of their title.+- **Drop the button and treat the pre-filled field as accepted**: The smallest surface - Rejected: it writes a suggestion nobody approved on any save of any other field, which is the thing Q57's dirty check exists to prevent.++### Consequences++**Positive:**+- The work editor has no control that writes before Save.+- Cancel discards an accepted suggestion, as it discards every other draft.++**Negative:**+- `hasUnsavedWorkURLChange` is no longer a pure function of the two strings; it reads the marker too. The marker's lifetime is stated in one place, beside the projection that clears it.++---
diff --git a/specs/series-and-related-works/decision_log.md b/specs/series-and-related-works/decision_log.mdindex 989c109e..7bca9958 100644--- a/specs/series-and-related-works/decision_log.md+++ b/specs/series-and-related-works/decision_log.md@@ -22,7 +22,7 @@ | Q16 | 2026-09-05 | "New series" from edit mode commits immediately and survives a cancelled edit | Consistent with Q6: an empty series is a legitimate thing to keep; the work's assignment stays in the draft (round 1, M8) | | Q17 | 2026-09-05 | Link edits never change a work's modification time; a membership edit is a work edit and stamps it | Links are their own rows, so a retype must not reshuffle the works list under a date sort. Membership lives on the work row (Decision 6), so its edit goes through `updateWork` and stamps like any other field; the works list sorts by newest entry date first, so the stamp only reorders works that tie on that | | Q23 | 2026-09-05 | A series has no unresolved members | With membership on the work row, a work that has not arrived brings its membership with it; the only unresolved states are a work naming an absent series and a link naming an absent work |-| Q24 | 2026-09-05 | Link add, retype and remove commit immediately, outside the work's edit draft | Links are their own rows with their own timestamps (Decision 5); folding them into the draft would make a link edit wait on, and conflict with, unrelated field edits |+| Q24 | 2026-09-05 | Link add, retype and remove commit immediately, outside the work's edit draft | promoted to Decision 8, which supersedes it (T-2328) | | Q25 | 2026-09-05 | The series screen's member edits go through `updateWork` with a basis and draft built from the member's snapshot | Reuses the redirect, torn-refusal and conflict machinery instead of a second write path for the same columns | | Q26 | 2026-09-05 | Equal series names are qualified with the creation date in the short style, plus an ordinal by identifier order where the date still collides, only where a collision exists; Core composes the label | Req 1.3 asks for a distinguishing qualifier without fixing its form; the date is stable and readable, the ordinal is convergent and always distinct (design review round 1, C3); Core owns the composition because the Markdown renderer is locale-free and takes pre-formatted labels (M7) | | Q27 | 2026-09-05 | One comparator, latest modification then lowest id, decides duplicate links everywhere: the reconcile phase, a collapse or merge, and the archive projection | Req 9.4's "target's type wins" would be undone by the next reconcile pass, which sorts by modification time; one comparator is the property Decision 5 bought (design review round 1, M5) |@@ -79,6 +79,7 @@ | Q73 | 2026-09-06 | View mode's related-works section draws only the links a work already has: with none it renders nothing at all, and adding is edit mode's | The section previously offered an add button in both modes, on the argument that the affordance is the section's whole content until there is a link. Adding a related work is a structural change, and every other structural control on these screens already lives behind the pencil (Q53), so view mode offering a second way in was the odd one out (device testing) | | Q74 | 2026-09-06 | A refusal is cleared on every entry to and every exit from an editor, not only inside `save()` | `commitEditing` reaches `save()` only when something is left to write, so confirming an editor with nothing to save closed it without clearing the standing refusal — and the message renders in both modes, so it followed the reader into view mode. Two everyday routes hit it: correcting a refused position by hand and confirming, and any link edit, which commits on the spot and leaves the save nothing to do (device testing) | | Q75 | 2026-09-06 | A refused save scrolls to wherever the refusal is said, with the model naming the target | The position field's card on the work detail, the refused member row on the series screen (the first in list order, which is where the commit loop stops), and the bottom message row for a refusal with no field. One scroll with a named target rather than a second mechanism per place a refusal can appear, and putting the choice on the model keeps it from drifting from where the sentence is drawn (device testing) |+| Q76 | 2026-09-22 | Adding a work to a series from the series screen is staged in the draft too, with the prefilled position raised past anything the session has already staged | The ticket named only the removal, but leaving the add as an immediate write would keep half the screen writing on the tap — and the staged-member machinery Decision 9 needs for a removal covers an addition for free. Two works added before one save must not land on the same position, so the repository's prefill is raised by the staged drafts | ## Decision 1: Two tables, not sequel edges @@ -312,3 +313,87 @@ A path is the only shape that terminates for a cycle, and it carries provenance - Mac state restoration and restore pruning read `selectedWorkID` today and move to the path; the chapter-replaces-work rule (Q57 of `ipad-and-mac-layouts`) is re-expressed on routes. Both are verified by existing suites before any series UI lands. ---++## Decision 8: Link edits are staged in the work's draft and committed by its Save++**Date**: 2026-09-22+**Status**: accepted, superseding Q24++### Context++Q24 had a link's add, retype and removal commit on the tap, outside the work's edit draft, on the argument that a link is its own row with its own timestamps (Decision 5) and that folding it into the draft would make a link edit wait on — and conflict with — unrelated field edits.++CLAUDE.md now carries the standing rule "Edit views save on Save, and only then": an edit view holds value-type drafts, the store is written once by one repository call when the reader presses Save, and Cancel restores the drafts. The link section is inside the work editor, reachable only in edit mode, and its type field is a draft that already existed (`linkTypeDrafts`). Q24 is the exception that taught a reader that some fields in that editor save themselves and others do not — the same lesson Q57 of `polish-and-export` removed from the URL section.++The write path made that visible in a second way: `commitLinkEdit` re-read the presentation from inside edit mode precisely because it could not call `load()` without reassigning every draft (Q68's hazard), and `work-creators` Q52 had to add a credit baseline so that re-read could not enrol rows the editor had never seen.++### Decision++The work editor stages its link edits — adds, retypes and removals — in the draft, and its Save commits them through one repository call, `commitLinkEdits(workID:operations:)`, which applies the session's operations in the order the reader performed them and saves once. The three singular repository writes stay as primitives; no editor calls them. The mid-edit presentation re-read goes with the commit-on-the-tap it belonged to.++### Rationale++One screen, one save, stated in the rule. The staged section draws the reader's claims — a removed link is gone, an added one is there, a retyped one shows its new type — and Cancel puts every one of them back, which is what a draft owes the reader.++Q24's stated cost does not arrive. A link edit does not wait on the field edits beside it, because `commitLinkEdits` writes the `WorkLink` table and no `Work` row (Q17): a session that only retyped a link stamps no work and cannot reshuffle the works list. It does not conflict with them either, because the work's own basis check is a separate step in the same confirmation and either half refuses on its own terms.++`commitRecordEdits` had already established the shape — a staged sequence, applied in order, refused whole — and this is the same shape for a second table.++### Alternatives Considered++- **Fold the link edits into `updateWork`**: One call for the whole editor - Rejected: `updateWork` stamps every row of the work group unconditionally, so a session that only retyped a link would stamp the work and move it under a date sort, which is exactly what Q17 forbids.+- **Keep the immediate writes and exempt the section from the rule**: The smallest change - Rejected: the rule exists because these exemptions are what teach a reader that Save means different things in different parts of one screen, and the ticket is the owner overruling Q24.+- **Commit each staged edit one at a time at Save**: No new repository call - Rejected: that is `SeriesDetailModel.save()`'s defect (Decision 9) — a refusal halfway leaves some links written and others not, with nothing to review.++### Consequences++**Positive:**+- The work editor has one write boundary the reader can predict, and Cancel means what it says in the link section too.+- A refused session leaves nothing written and the staged edits on screen, so the reader can correct and re-save.+- `reloadPresentation()` is gone, and with it the only path that replaced the presentation under an open editor.++**Negative:**+- A staged link has a draft-local identifier that is not a row identifier, so the section draws an id the store has never seen until Save. Nothing outside the model reads it.+- The credit baseline (`work-creators` Q52) now has no live trigger, because the re-read it guarded against is gone. It stays as the guard for any re-read added later, and its test asserts the half that is still reachable.++---++## Decision 9: The series editor commits once, name, notes and every member together++**Date**: 2026-09-22+**Status**: accepted++### Context++`SeriesDetailModel.save()` wrote the name and notes through `updateSeries`, then looped over the members writing each position through its own `updateWork` (Q25). A position that would not parse halfway down the list returned with the name written and some positions written and others not; a conflict on one member did the same. The removals did not wait for Save at all — "Remove from series" committed on the tap — and so did adding a member.++Q25's reason for going through `updateWork` was sound: the redirect, the torn refusal and the conflict machinery should be the work editor's rather than a second write path onto the same two columns. But `updateWork` writes a work's *whole* metadata, so every member edit had to carry the member's title, tags, notes, statuses, verdict and release days back unchanged — a list that has grown twice since (`update-schedule` Req 1.7, `work-and-reading-status`), each time because a forgotten field would silently reset a reader's data.++### Decision++One repository call, `commitSeriesEdits(seriesID:name:notes:members:)`, writes the whole editor in one transaction: the series row's name and notes, every staged position edit, every staged removal and every staged addition. Each member is resolved through `resolveWorkWriteTarget` against its own basis and refused if torn, so Q25's machinery is kept; what is not kept is rewriting the member's other columns. The first refusal returns before the save, so nothing lands. Every position is parsed before the call is made, so a refused position never reaches the repository.++### Rationale++Every other editor in the app commits once, and this one could not honestly claim that a refusal left the library untouched. Narrowing the write to the two series columns is not a loss of the conflict machinery — that lives in the resolution step, which this call still makes — and it removes the standing hazard that a new column on `Work` must be threaded through a series-screen draft or be silently cleared.++Value guards throughout mean a save that changed nothing writes nothing, so the editor's confirmation does not put a row on the sync wire for a reader who opened the editor and changed their mind.++### Alternatives Considered++- **Keep the loop, roll back by hand on the first refusal**: No new repository call - Rejected: there is no way to undo a committed `updateWork` from the model, and a compensating write is a second chance to leave the library half-edited.+- **Parse every position first, then run the existing loop**: Fixes the reported symptom only - Rejected: a conflict or a redirect on the third member still leaves the first two written, and the removals still commit on the tap.+- **Send each member as a whole `WorkMetadataDraft` inside the one call**: Keeps Q25 literally - Rejected: it keeps the "carry every column back" hazard for no benefit, since the transaction is what makes the save atomic, not the draft's width.++### Consequences++**Positive:**+- A refused series save leaves the library exactly as it was, and the editor open on the reader's drafts (Q68: no `load()` on a refusal).+- Removals and additions are drafts, so Cancel puts the member list back.+- A new `Work` column cannot be cleared by a series-screen position edit, because the commit does not write it.++**Negative:**+- A second write path onto the two series columns exists in Core, beside `updateWork`. It is the same resolution and the same refusal, and `deleteSeries` was already a third.+- The series screen's Save now does more in one lock; the members it writes are the ones the reader edited, so the set is small.++---
diff --git a/specs/work-creators/decision_log.md b/specs/work-creators/decision_log.mdindex f50682c1..a4c07154 100644--- a/specs/work-creators/decision_log.md+++ b/specs/work-creators/decision_log.md@@ -102,6 +102,7 @@ | Q96 | 2026-09-08 | A view-mode credit is one compact tappable line, "NAME: role · role", the lines stacked inside the header card under the site row | The two-line row read as a block per creator on the phone; the owner asked for a list, and name-first keeps several roles readable on one line; the owner rejected both the two-line rows and the header-free series-row shape as too tall, so the lines drop the 44 pt minimum hit target deliberately, since a credit is a small fact with a secondary tap, not a primary control; the header was dropped last, on the owner's request, to see the lines stand alone; the owner asked for the credits to read as the work's top-level metadata beside the site rather than a section of their own | | Q97 | 2026-09-09 | `dedupeCredits` saves per chunk like the link dedupe; a mid-pass failure leaves earlier chunks committed, which the next pass finishes, since every chunk is a fixed point | The shape matches `MembershipReconciler.dedupeLinks` and is what Q73's measurement was taken over; one save over the whole pass would hold every deletion of a ~2,000-credit table open in one transaction, and the resumption it would buy is already there — a chunk that committed removed duplicates a re-run does not find | | Q98 | 2026-09-09 | The mutation hook the creator and series list screens take reports the snapshot generation it published, and the screen records it as loadedGeneration, instead of latching a read for the next bump | The refresh can return without publishing (the abandon arm of refreshAll, or a throwing read), and a latch nothing consumes swallows the next genuine arrival (Req 10.2); reporting the generation also removes the duplicate state beside loadedGeneration |+| Q99 | 2026-09-22 | The roles list's drag stages the order and raises its own Save and Cancel; the `EditButton` seam (Q81) stays and only toggles dragging | T-2328: the drag was the last reorder in the app that wrote on the gesture. `EditButton`'s Done is not a save — it has no discard beside it, and it does not exist on the Mac at all — so the two controls are the screen's own, drawn exactly while the list is an order the store has not been told about. A read that lands mid-drag (an add, a sync arrival) carries the staged order over it rather than silently undoing it | ## Decision 1: Reader-Defined Ordered Role List
URL → metadata → records → links → site removals are five repository calls. Q3 accepts that a late refusal leaves earlier steps landed with the staged edits still on screen. Confirm that is the intended reading of “one repository call when the reader presses Save” in CLAUDE.md, since the rule's text still says one call.
Remove-then-add on one pair relies on a predicated fetch excluding a row deleted in the same unsaved context. Unreachable from the picker today; if the picker is ever made draft-aware, add the Core test first.
20 issues in Preserve-first share flow, identical on main (run here: swift test --filter ShareCaptureFlowTests on the main checkout, 20 issues). Same family as the EPERM pending-capture suites the memory note records. Not this branch.
SeriesUITests/testTheSeriesEditorRepositionsAddsAndRemovesMembers changed meaning under this branch and was not in the report's verification list. Run on the simulator as part of this review: passed (49.3 s, make test-only). The simulator unit bundle (make test-only TEST=AsterismTests) also passed, 1,810 tests, 0 failures; neither run emits JUnit, so only the Core run feeds the Tests section below.