asterism branch T-2361/bugfix-unattached-flag-… commits 2 files 10 touched lines +608 / -21 tests 2,973 passed, 0 failed (3 suites skipped)

Pre-push review: T-2361 (second pass)

Second pre-push review of PR #89, reviewing git diff origin/main...HEAD (2 commits). The first review returned Needs fixes with four majors; commit 926ed2e3 claims to resolve them with EntryCitations.assignManually(), a fix to the attached arm, a regression test for it and decision rows Q128/Q129/Q35. This pass checks those resolutions and re-reviews the whole diff. Review-only: no file on the branch was modified.

At a glance

  • First-review majors — all resolved. (a) DuplicateReconciler.apply doc comment now says “no assignment pointer” and names the one constant arm it writes; (b) Q128 (Q67 narrowed), Q129 (Q85 reversed) and remove-article-mode Q35 (Q11 answered) are in the tables, sequential and dated; (c) the attached arm calls assignManually() instead of copying carried.workAssignment, with attachedOutcomeClearsTheSurvivorsURLAssignment covering a .urlRule survivor; (d) the triple is spelt once in EntryCitations.assignManually() with three production callers and no straggler in Sources/.
  • Helper is behaviour-preserving. applyManualAssignment before: editCitations { .manual; workURL = nil; workURLAssignmentKind = nil } then modifiedAt. After: editCitations { $0.assignManually() } then modifiedAt. Same fields, same order, the value guard is editCitations's, the discarded return was already @discardableResult.
  • Convergence properties hold. .manual is a constant (two devices reach one fixed point), no clock or PersistentIdentifier is read, and both reconciler tests assert reconcile().wroteNothing after the repair. A carrier that is itself flagged with a .none arm is skipped (row !== carrier), so the illegal state is neither propagated nor healed — recorded as “guard, not heal” in the comment and Q129.
  • Minors from the first review — resolved. The fan-out comment is explicit that pre-fix rows are not healed; reconciler and resolution tests now cover the same two sibling/survivor shapes; three reader-path arms are tested; the pre-existing .none-over-row.work branch is recorded in the report as out of scope.
  • Open follow-up without a ticket. applyEntryOutcome's else if provenanceKind == .manual { .none } branch still leaves row.work set, so choosing a variant without an assignment over a manually-assigned survivor rolls the resolution back. The report says “worth its own ticket”; none exists in Transit.
  • Tests: 2,973 passed / 0 failed on this host with the three EPERM suites skipped; verify-identity clean; no compiler warnings in the changed files. Full make test-core owed on an unlocked host.

Verdict

Ready to push

All four majors from the first review are resolved in code and recorded in the decision logs, and the helper does not change applyManualAssignment's behaviour (same three fields, same order, same value guard, same modifiedAt stamp). Both duplicate writers now reach a validator-legal row for every survivor shape (.none, .manual, .pattern, .urlRule with trio), the reconciler stays clock-free and the second pass writes nothing. The five new tests assert stored facts, validator output and the fixed point. What remains is minor: no Transit ticket yet for the pre-existing rejected-attached-variant branch the report defers, a stale Q39 “copied whole” comment above applyEntryOutcome, no forward pointers on the superseded rows Q67/Q85/Q11, and one resolution test missing the fixture pre-check its siblings have. Test caveat: swift test --no-parallel ran with the three pending-capture suites skipped (PendingCaptureSpoolTests, PendingCaptureDrainTests, ShareCaptureFlowTests), which fail with EPERM on this host on main as well (locked login keychain, docs/agent-notes/testing.md); 2,973 tests passed, 0 failed, 0 known issues, no new compiler warnings in the changed files, and make verify-identity passed. A full make test-core on an unlocked host is still owed before merge.

Review findings

11 raised · 0 fixed · 11 skipped

Jump to findings →

Tests

Pass rate: 100% (2973 of 2973)

New tests: 5

Diff coverage: 98% (250 of 256 added lines)

Jump to tests →

Commits

Three-level explanation

What changed

Asterism keeps a small “receipt” on every saved page (an Entry) saying how it was matched to a story (a Work): by a title rule, by a URL rule, by you (“manual”), or not yet decided (“none”). There is also a checkbox meaning “I deliberately left this page unattached”. The library's checker only accepts that checkbox when the receipt says manual and nothing else is written beside it.

Two pieces of code that merge duplicate copies of the same page were ticking the checkbox on a copy without also updating its receipt. The checker then refused the copy. On the silent path that quarantined the whole site (teaching, rule application and export stop working for it); on the reader's path the merge simply failed and nothing was saved.

The fix adds one small shared function, assignManually(), that writes the correct receipt (“manual, no URL rule, no URL kind”), and makes every place that ticks the checkbox — or copies a manual assignment — call it.

Why it matters

A quarantined site blocks features the reader relies on, and nothing told them why. A merge that fails closed leaves a duplicate the reader cannot resolve. Both are now fixed, and the second review round also caught a third case (copying a manual assignment onto a copy that had a URL-rule receipt) and fixed it the same way.

Key concepts

  • Citation blob: the receipt, stored as JSON on the row.
  • Duplicate set: several rows that are really the same page; one survives, the others are folded into it.
  • Validator: the checker that refuses impossible combinations.
  • Fixed point: after the repair, running the merge again changes nothing — important because every device runs it independently.

Changes overview

  • EntryCitations.assignManually() — the citation half of a manual assignment (.manual, workURL = nil, workURLAssignmentKind = nil), clock-free.
  • LibraryRepository.applyManualAssignment — now the helper plus the modifiedAt stamp; behaviour unchanged.
  • LibraryRepository+DuplicateResolution.applyEntryOutcome — the unattached arm writes the helper after setting the flag and nilling work; the attached arm writes the helper instead of copying carried.workAssignment, so a .urlRule survivor loses its trio.
  • DuplicateReconciler.apply(_:to:) — the same-UUID fan-out writes the helper through editCitations when it sets the flag.
  • GroupOrdering.authoredContent(of:) — comment only; the flag read stays ungated (Q11/Q35).
  • Five regression tests, two fixture helpers (insertTaughtSite, assignByURLRule), the bugfix report, and rows Q128/Q129/Q35.

Implementation approach

The invariant (“flag ⇔ .manual arm, nil work, no URL reference”) previously lived in one function that also stamped a clock, so the two clock-free writers could not call it and re-spelt half of it. The fix splits the invariant from the stamp: the citation half becomes a value-type mutation on EntryCitations, and every writer goes through editCitations, which decodes once, compares, and encodes only on change.

The writers write the constant rather than the carrier's arm. A content assignment is by definition the carrier's .manual arm (that is the only kind authoredContent reads as authored), so nothing is lost, and a carrier that is itself in the illegal state is repaired on its siblings rather than propagated.

Trade-offs

  • Gate the read instead (make a flagged .none row read as bare) — rejected in remove-article-mode Q11 and again here: it would classify the same row differently on two devices.
  • Call applyManualAssignment — rejected: it stamps modifiedAt from a clock, which the reconciler may not read.
  • Heal pre-fix rows — deferred (Q129): the fan-out skips the carrier and any row already flagged, and a survivor that outlived its set is in no set at all, so a heal needs a whole-table scan and a decision of its own. The reader's Move To → Leave unattached repairs such a row today.

Technical deep dive

Reachability of the defect rests on EntryAuthoredContent.isBare: the assignment component is gated on citations.workAssignment == .manual, the flag on nothing, so a sibling whose own arm is .none, .pattern or .urlRule reads as bare, folds into the carrier's variant, and becomes a fan-out target rather than a second variant. The reconciler's chunk save runs no diagnosis gate (only commit gates refuse introduced diagnoses), so the silent path committed the illegal row and the next validation quarantined the hostname; the reader path's commitResolution does gate and rolled back.

Validator cases after the fix: unattached arm writes flag=true, work=nil, .manual, trio nil — the .manual case requires !hasURLReference and work == nil ⇒ intentionallyUnattached, satisfied for any prior survivor arm because every field the validator reads is overwritten. Attached arm writes flag=false, work = carrier.work, .manual, trio nil — carrier.work is non-nil because content.workAssignment != nil only when the carrier's arm is .manual and work?.id != nil, and the carrier is re-found at commit by content equality.

Idempotence: the reconciler branch is guarded by carrier.intentionallyUnattached && !row.intentionallyUnattached, so once the flag has fanned out the branch is never entered and no decode happens; editCitations is value-guarded for the rest. changed = true is correct independent of the blob because the flag and pointer writes are unconditional inside the branch. At the fixed point the budgeted M4 duplicate arm never enters the branch (its fixture seeds no unattached rows), so the 2 s budget is untouched.

Architecture impact

Q67 is narrowed rather than broken: the duplicate writers still never copy an assignment pointer or the normalised equality key; the one arm they write is a constant. Q85's “provenance is deliberately left alone” is reversed, which is only legal because remove-article-mode Q6 removed the last non-.manual pairing of the flag — with one legal arm left, writing it invents nothing. The read in authoredContent stays ungated on purpose: it is what makes a half-written sibling a repair target rather than a second variant on one device only.

Potential issues

  • The sibling else if citations.workAssignment.provenanceKind == .manual { .none } branch keeps row.work, which the .none case refuses unless the blob is absent — and editCitations has just written bytes. Choosing an assignment-less variant over a manually-assigned survivor therefore rolls back. Same defect class, deliberately out of scope, no ticket yet.
  • A carrier that is itself flagged with a .none arm is skipped, so the pre-existing diagnosis stands after the pass; the set then reads as one variant (flag true, assignment nil on both) and reaches a fixed point with the quarantine intact. Documented, but only in comments — no test pins it.
  • Rows an earlier build left flagged with a .none arm are not healed by the fan-out (rows already holding the flag are skipped) and are unreachable when their set has already collapsed; repair is the reader's Move To → Leave unattached. Whether any exist in the real library is unverified (needs Library Check on the device).

Important changes — detailed

EntryCitations: add assignManually(), the citation half of a manual assignment

Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift

Why it matters. This is the invariant the bug was about, spelt once. Four writers now share it; a fifth that hand-spells the triple is the thing to refuse in review.

What to look at. EntryCitations.swift:146-161

Takeaway. When an invariant spans several fields and one writer also needs a side effect (here a clock stamp), split the pure part into a value-type mutation so the side-effect-free writers can share it.
Rationale. applyManualAssignment stamps modifiedAt from a clock; the reconciler may read no clock and the resolution stamps its own rows, so neither duplicate writer could call it. The helper carries no clock, so all three can (report.md, Root Cause).

applyEntryOutcome: both arms write the constant .manual arm with the trio cleared

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

Why it matters. The reader-path fix. The unattached arm previously set the flag and nilled work without touching the blob; the attached arm copied carried.workAssignment over a survivor that could still hold a URL-rule trio. Either shape was refused by the validator and rolled the resolution back.

What to look at. LibraryRepository+DuplicateResolution.swift:700-733

Takeaway. Write the invariant, not the carrier's copy of it: a constant repairs a carrier that is itself broken, whereas a copy propagates it.
Rationale. Q128: an unattachment or a manual assignment is an assignment decision; what Q67 forbids is copying the pointer or the normalised key, and neither is touched. A content assignment is by definition the carrier's .manual arm, so the constant loses nothing.

DuplicateReconciler.apply: the fan-out writes the .manual arm with the flag

Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift

Why it matters. The silent-path fix, and the one that corrupted the library rather than failing closed: the reconciler's chunk save has no diagnosis gate, so the illegal row was committed and the hostname quarantined on the next validation.

What to look at. DuplicateReconciler.swift:1656-1661

Takeaway. A convergence writer must be a deterministic function of synced content: a constant arm plus a value-guarded blob write gives two devices one fixed point and makes the second pass a no-op.
Rationale. Q129: Q85's 'provenance is deliberately left alone' held while a .none writer for the flag existed; remove-article-mode Q6 made .none refuse the flag, so .manual is the only legal arm and writing it invents nothing. The fan-out is a guard, not a heal — the carrier and already-flagged rows are skipped.

applyManualAssignment: delegate to the helper, keep the stamp

Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift

Why it matters. The caller asked specifically whether the helper changes this function. It does not: same three fields in the same order inside the same editCitations call, the return value was already discarded under @discardableResult, and modifiedAt is stamped unconditionally before and after.

What to look at. LibraryRepository.swift:1550-1553

Takeaway. A refactor that moves a field list into a helper is verifiable by diffing the field list and the call shape; existing tests (CitationBlobRefreshTests, WorkDeletionTests.detachClearsURLAssignmentReferences, RepositoryWorksTests moveEntry) already pin all three fields and the stamp.
Rationale. The report's Prevention section: the citation half lives in one named write and this function keeps only the clock stamp on top.

GroupOrdering.authoredContent: the flag read stays ungated

Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift

Why it matters. Comment-only, but it records why the obvious alternative fix (gate the flag on .manual) is wrong and closes remove-article-mode Q11.

What to look at. GroupOrdering.swift:631-648

Takeaway. The ungated read is what makes a half-written sibling a repair target rather than a second variant; gating it would classify the same row differently on two devices.
Rationale. remove-article-mode Q35: the writers were closed instead of the read; a pre-fix or future half-written row still reads consistently on every device.

Five regression tests and two seed helpers

Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift

Why it matters. They cover the .none and .urlRule sibling shapes on the silent path, the .none and .urlRule survivor shapes on the reader path's unattached arm, and the .urlRule survivor on the attached arm; the reconciler tests also assert the fixed point and that the validator is clean after the pass.

What to look at. DuplicateReconcilerTests.swift:359-440; DuplicateResolutionTests.swift:173-305, 1310-1316, 1368-1399

Takeaway. Asserting the fixture validates before the pass makes a red run the pass's and not the seed's; asserting wroteNothing afterwards makes idempotence executable rather than claimed.
Rationale. Report, Prevention: a fixture that runs LibraryValidator.validate after a convergence pass is what catches this class.

Key decisions

Q128 — Q67 narrowed: no assignment pointer, but the constant .manual arm is written with an unattachment or a manual assignment.

The flag is a legal state only beside a .manual arm and no URL reference; a content assignment is by definition the carrier's .manual arm. Copying the pointer or the normalised key is still forbidden. .manual is a constant, so two devices converge; editCitations is value-guarded, so the fixed point writes nothing.

Q129 — Q85 reversed: writing intentionallyUnattached as outcome content also writes the .manual arm.

Q85 held while Articles mode's .none writer existed. remove-article-mode Q6 made .none refuse the flag, so .manual is now the only legal arm and writing it invents nothing (Decision 10's lesson intact). The fan-out is a guard, not a heal; a heal pass needs a decision of its own.

remove-article-mode Q35 — Q11 answered: the writers were closed, the read stays ungated.

A row from before the fix, or one a future writer leaves half-written, would otherwise read as bare on one device and authored on another; the ungated read is what makes such a sibling a fan-out target the fix repairs.

Write the constant, not the carrier's arm.

A carrier that is itself in the illegal state is repaired on its siblings rather than propagated; on the attached arm, copying carried.workAssignment is what left the survivor's URL trio in place. Stated in the code comments and the report's approach rationale.

The rejected-attached-variant branch is left as is.

else if provenanceKind == .manual { .none } keeps row.work, which the validator refuses; the report records it under Related as a follow-up worth its own ticket. Deferring is defensible (different arm, different trigger), but no ticket has been created.

Q129 recorded as a quick decision rather than a full entry.

It reverses an earlier quick decision and has named alternatives and a negative consequence, which puts it at the boundary of the format's rule of thumb. The reversal is compelled by Q6 rather than weighed, so the quick row is acceptable; the superseded rows themselves carry no forward pointer.

(inferred — not stated by the author.)

Review findings

SeverityAreaFindingResolution
minorLibraryRepository+DuplicateResolution.swift:731-733 (pre-existing branch)The rejected-attached-variant branch writes .none while keeping row.work; the .none validator case refuses that unless the blob is absent, and editCitations has just written bytes, so choosing an assignment-less variant over a manually-assigned survivor rolls the resolution back. The report defers it as 'worth its own ticket', but no Transit ticket exists.Not changed (review-only run; pre-existing and out of the ticket's scope). Create the Transit ticket in this repository before merge, or fix it here with row.work = nil plus a ~30-line test using the new ResolutionSeedStore helpers.
minorLibraryRepository+DuplicateResolution.swift:684-687The comment 'The carrier's citation arms are copied whole rather than kind by kind ... (Q39)' above `let carried = carrier.citationValues` is now half-true: carried feeds only the chapter-title arm; the assignment arm is never copied from it.Not changed (review-only). Narrow the comment to the chapter title, or add 'the assignment arm is not copied at all — see below'.
minordecision logs: Q67, Q85 (duplicate-reconciliation), Q11 (remove-article-mode)The superseded rows carry no forward pointer, unlike the repo's 'amended by Q75' / 'superseded by Q45' convention; a reader landing on Q85's 'Provenance is deliberately left alone' or Q11's 'the gate belongs to T-2361' has no pointer to Q129/Q35.Not changed (review-only). Append 'narrowed by Q128' to Q67's rationale, 'reversed by Q129' to Q85's, and 'answered by Q35' to Q11's.
minorDuplicateResolutionTests.swift unattachedOutcomeCarriesItsProvenanceThe first of the three resolution tests lacks the `diagnose().tupleDiagnoses.isEmpty` pre-check its two siblings have. commitResolution refuses only introduced diagnoses, so without the pre-check a committed outcome does not prove the graph was valid.Not changed (review-only). Add the pre-check for symmetry.
minorURLOptionalSequenceIntegrationTests.swift:552-556, 563-567Two test sites still hand-spell the full triple (.manual, workURL = nil, workURLAssignmentKind = nil) on rows a URL rule had assigned — exactly the pattern the report's Prevention section says to refuse. Test code only; production has no straggler.Not changed (review-only). Replace both with $0.assignManually() (public, no @testable concern).
minorQ129 'guard, not heal' has no testThe one documented negative consequence — a sibling already flagged with a .none arm is left untouched by the fan-out — exists only in comments and the decision row.Not changed (review-only). One reconciler test (flagged .none sibling + valid carrier → sibling unchanged after reconcileToFixedPoint) would make it executable. Optional.
nitDuplicateReconciler.swift:1639-1655Seventeen lines of comment for a four-line branch, restating Q128, Q129 and the report.Not changed. Could be trimmed to ~5 lines with the Q references.
nitLibraryRepository.swift:1538-1549applyManualAssignment's doc comment still says it is 'one set of manual-assignment semantics ... not two copies of a list of fields' and repeats the URL-trio rationale, which now lives on assignManually().Not changed. Trim to: shared by moveEntry and commitWorkDeletion; citation half is EntryCitations.assignManually(); this adds the reader's modifiedAt stamp.
nitassignByURLRule comment (both test files)Both copies write .wholeTitleFallback while the comment says 'as applyAssignmentProvenance writes it'; that function writes .identity. The validator accepts either, so the tests are fine.Not changed. Use .identity or drop the clause. The trio seed is also duplicated between the two test files; CitationSurgery.swift is the shared test-only home if it is worth consolidating.
nitEntryFacts / entryCitations()The new ResolutionFixture.entryCitations() and the inline fetch in DuplicateReconcilerTests exist only because EntryFacts does not carry the URL trio; extending EntryFacts (which already decodes citationValues once) would let all three new tests assert through the facts they already fetch.Not changed. Optional consolidation.
nitTransit T-2361 comment / specs/remove-article-mode/design.md:72The ticket's last comment still describes three regression tests and the first run; design.md:72 says the authoredContent comment 'cites T-2361's writers as the reason', which the comment no longer does.Not changed. Add a Transit comment at push/merge; the design doc is a finished feature's history and may stay.

Tests

Source: local run at 2026-09-22T17:04:00+10:00 · snapshot 926ed2e332cd30ab6e094265608403543b11d582

Baseline: none

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

Coverage scope: every test in the repository

Totals: 2973 passed · 0 failed · 50 skipped · 0 errored · 0 flaky

New and removed tests

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

Diff coverage

FileAdded linesCoveredDiff coverage
Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift2719100%
Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift175100%
Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift1111100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift1818100%
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift11100%
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTests.swift8663100%
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift17513396%
specs/bugfixes/unattached-flag-without-manual-provenance/report.md270—no coverage data
specs/duplicate-reconciliation/decision_log.md2—no coverage data
specs/remove-article-mode/decision_log.md1—no coverage data

Aggregate diff coverage: 98% (250 of 256 measurable added lines).

Overall coverage

Head 91.0% (96048 of 105517 lines)

7 of 10 changed files matched coverage data.

Blast radius

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

addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

Click to expand.

Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift Modified +27 / -5
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swiftindex 51e60daa..6ab8f649 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift@@ -1599,11 +1599,14 @@ enum DuplicateReconciler {      /// Copies the carrier's authored fields onto every survivor row (Req 3.1).     ///-    /// **No assignment is ever written** (Q67). The survivor keeps its own-    /// physical assignment, and Req 5.2's collapse re-points it. Every other-    /// field copies straight: on the silent path the set has at most one variant,-    /// so a row differing from the carrier in an authored field would be a second-    /// variant and the set would not be here.+    /// **No assignment pointer is ever written** (Q67). The survivor keeps its+    /// own physical assignment, and Req 5.2's collapse re-points it. The one+    /// assignment *arm* this fan-out writes is the `.manual` an unattachment+    /// requires beside the flag (T-2361, Q128), and it is a constant rather+    /// than a pointer. Every other field copies straight: on the silent path+    /// the set has at most one variant, so a row differing from the carrier in+    /// an authored field would be a second variant and the set would not be+    /// here.     private static func apply(_ carrier: Entry, to rows: [Entry]) -> Bool {         var changed = false         // One decode of the carrier's blob for the whole fan-out, not one per row.@@ -1633,9 +1636,28 @@ enum DuplicateReconciler {             // would be a second variant. `work` goes with it, because a row             // that is intentionally unattached and still points somewhere is a             // state no write path produces.+            //+            // T-2361: **and so does the assignment arm.** The flag is a legal+            // state only beside a `.manual` arm with no URL reference, so+            // setting it alone left a row the next validation refuses and a+            // quarantined hostname behind it — and the reconciler's chunk save+            // runs no diagnosis gate, so nothing rolled it back. The sibling is+            // reachable because `authoredContent` gates the assignment on+            // `.manual` and the flag on nothing, so a row whose own arm is+            // `.none` or `.urlRule` reads as *bare* and folds into the carrier's+            // variant rather than making a second one. This is the one+            // assignment write the fan-out makes, and Q67 does not cover it: an+            // unattachment is an assignment decision, not a pointer copy+            // (Q128). `.manual` is a constant, so two devices reach the same+            // fixed point; `editCitations` is value-guarded, so the fixed point+            // writes nothing. It is a guard on the flag, not a heal: the+            // carrier and a row already holding the flag are skipped, so a row+            // an earlier build left flagged with a `.none` arm stays as it is+            // until the reader moves it (Move To → Leave unattached).             if carrier.intentionallyUnattached, !row.intentionallyUnattached {                 row.intentionallyUnattached = true                 row.work = nil+                row.editCitations { $0.assignManually() }                 changed = true             }         }
Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift Modified +17 / -0
diff --git a/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift b/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swiftindex 7a4fd148..e5a8ebf7 100644--- a/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift@@ -143,6 +143,23 @@ public struct EntryCitations: Codable, Equatable, Sendable {         self.workURLAssignmentKind = workURLAssignmentKind     } +    /// The citation half of a manual assignment: the `.manual` arm, and no URL+    /// reference beside it.+    ///+    /// The three move together or the row is illegal — `LibraryValidator`+    /// refuses a `.manual` arm that still cites a URL rule or keeps an+    /// assignment kind, and every Entry a URL-taught Site assigned carries both.+    /// Spelt once so a writer cannot copy two of the three: the reader's move+    /// and detach (`LibraryRepository.applyManualAssignment`) and the two+    /// duplicate writers that carry an unattachment or a manual assignment onto+    /// a survivor (T-2361) all go through it. It reads no clock; the stamp a+    /// reader's write owes is the caller's.+    public mutating func assignManually() {+        workAssignment = .manual+        workURL = nil+        workURLAssignmentKind = nil+    }+     /// The encoded default value, encoded once.     ///     /// `Entry.init` seeds every new row with it (Q13), and it needs a `Data`,
Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift Modified +11 / -7
diff --git a/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift b/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swiftindex b1103717..fd1834ff 100644--- a/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift@@ -631,13 +631,17 @@ public enum GroupOrdering {      public static func authoredContent(of entry: Entry) -> EntryAuthoredContent {         // `intentionallyUnattached` deliberately carries no provenance gate,-        // unlike the assignment and the chapter title beside it. T-2361's two-        // duplicate-resolution writers can still set the flag on a row whose own-        // provenance is `.none`, so a gate on `workAssignmentProvenance ==-        // .manual` would read that row as bare on one device and authored on-        // another (`remove-article-mode` Q11). Recorded as known: the cost is-        // that a derived unattachment counts as authored, which can classify a-        // group as non-bare and send it to the reader — the safe direction.+        // unlike the assignment and the chapter title beside it. T-2361 closed+        // the two duplicate writers that could set the flag on a row whose own+        // provenance is `.none` — both now write the `.manual` arm with it — and+        // the gate still does not belong here: a row from before that fix, or+        // one a future writer leaves half-written, would read as bare on one+        // device and authored on another (`remove-article-mode` Q11). The cost+        // of leaving it ungated is that a derived unattachment counts as+        // authored, which can classify a group as non-bare and send it to the+        // reader — the safe direction. The same ungated read is what T-2361+        // came in by: a `.none` sibling of an unattached carrier reads as bare,+        // so it is a fan-out target rather than a second variant.         // One decode of the blob, not two: both provenances come out of it.         let citations = entry.citationValues         return EntryAuthoredContent(
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift Modified +18 / -1
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swiftindex fa7c8780..de886d4f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift@@ -700,6 +700,17 @@ extension LibraryRepository {                 // somewhere is a state nothing else produces.                 row.intentionallyUnattached = true                 row.work = nil+                // T-2361: the flag is a legal state only beside a `.manual`+                // assignment arm and no URL reference — the validator refuses+                // every other pairing, and the commit gate below then rolls the+                // whole resolution back. The survivor is recomputed, not chosen+                // (Q21), so its own arm may be anything; an unattachment *is* an+                // assignment decision, which is why Q67's "no assignment is ever+                // written" does not reach here (Q128). Written as the constant+                // rather than copied from `carried`, so a carrier that is itself+                // in the illegal state is repaired rather than propagated. The+                // survivor's own `modifiedAt` stamp is the caller's.+                citations.assignManually()                 return             }             row.intentionallyUnattached = false@@ -710,7 +721,13 @@ extension LibraryRepository {                 // which throws when that Work has since gone and would fail the                 // whole resolution over an assignment.                 row.work = carrier.work-                citations.workAssignment = carried.workAssignment+                // A content assignment is by definition the carrier's `.manual`+                // arm (`authoredContent` reads no other kind as authored), and+                // the survivor's own arm may be a URL rule's, trio and all — so+                // the arm is written as the manual assignment it is rather than+                // copied from `carried` on top of a trio the validator refuses+                // beside it (T-2361).+                citations.assignManually()             } else if citations.workAssignment.provenanceKind == .manual {                 citations.workAssignment = .none             }
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift Modified +1 / -5
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex c060878f..41ace356 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -1548,11 +1548,7 @@ public actor LibraryRepository {     /// validates and so rolled the whole deletion back; `moveEntry` does not,     /// and saved a graph the next open quarantines.     internal static func applyManualAssignment(to row: Entry, at timestamp: Date) {-        row.editCitations { citations in-            citations.workAssignment = .manual-            citations.workURL = nil-            citations.workURLAssignmentKind = nil-        }+        row.editCitations { $0.assignManually() }         row.modifiedAt = timestamp     } 
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTests.swift Modified +86 / -3
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTests.swiftindex fe9dfdfb..f9409620 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTests.swift@@ -8,9 +8,10 @@ import Testing /// 3.1–3.3 and 5.1–5.2 (silent resolution), and 2.1–2.3/2.9 (deletion safety). /// /// What it must *not* do carries as much weight as what it must. It never reads-/// a clock, never writes a work assignment into outcome content, never deletes a-/// proper subset of an identity group, and never deletes anything at all on the-/// pass that first saw the set.+/// a clock, never writes an assignment *pointer* into outcome content (the one+/// assignment arm it writes is the constant `.manual` an unattachment requires,+/// T-2361), never deletes a proper subset of an identity group, and never+/// deletes anything at all on the pass that first saw the set. @Suite("Duplicate reconciliation", .serialized) struct DuplicateReconcilerTests { @@ -355,6 +356,88 @@ struct DuplicateReconcilerTests {         #expect(entries.allSatisfy { $0.chapterTitleProvenance == .manual })     } +    // MARK: - T-2361: the unattachment flag travels with its provenance++    /// The flag is a legal state only beside a `.manual` assignment citation and+    /// no Work (`LibraryValidator.validateAssignment`). A sibling row of the+    /// same record reads as *bare* while its own citation still says `.none` —+    /// the authored-content read gates the assignment on `.manual` and the flag+    /// on nothing — so the fan-out reaches it, and setting the flag alone left a+    /// row the next validation refuses with "none assignment has incompatible+    /// relationship or provenance", quarantining the hostname.+    @Test("The unattachment flag fans out with the manual provenance it requires")+    func unattachmentFanOutCarriesItsProvenance() throws {+        let store = try DuplicateStore()+        let site = store.addSite()+        let shared = DuplicateStore.rankedID(1)+        // The sibling: bare, and its own assignment arm has never been written.+        store.addEntry(id: shared, key: "chapter-1", capturedAt: 0, site: site)+        let carrier = store.addEntry(id: shared, key: "chapter-1", capturedAt: 0, site: site)+        carrier.intentionallyUnattached = true+        carrier.editCitations { $0.workAssignment = .manual }+        try store.commit()+        #expect(try store.diagnose().tupleDiagnoses.isEmpty, "the fixture did not start valid")++        try store.reconcileToFixedPoint()++        let entries = try store.entryFacts()+        #expect(entries.count == 2)+        #expect(entries.allSatisfy { $0.intentionallyUnattached })+        #expect(entries.allSatisfy { $0.workID == nil })+        #expect(entries.allSatisfy { $0.workAssignmentProvenance == .manual })+        #expect(+            try store.diagnose().tupleDiagnoses.isEmpty,+            "the fan-out quarantined the hostname")+        // The citation write is value-guarded, so the repaired library is a+        // fixed point: another pass writes nothing and exports nothing.+        #expect(try store.reconcile().wroteNothing)+    }++    /// The same fan-out over a sibling a **URL rule** assigned. Left as it was,+    /// the row is refused as "URL assignment requires one known assignment arm";+    /// writing `.manual` over it without clearing the URL trio beside it is+    /// refused as "manual assignment has incompatible relationship or+    /// provenance". So the write clears the whole trio, exactly as+    /// `applyManualAssignment` does on the reader's own detach path.+    @Test("The unattachment fan-out clears a sibling's URL assignment citations")+    func unattachmentFanOutClearsTheURLAssignment() throws {+        let store = try DuplicateStore()+        let site = store.addSite(mode: .taught)+        let ruleID = DuplicateStore.rankedID(7)+        _ = try store.addURLRule(id: ruleID, site: site, current: true)+        _ = try store.addPattern(id: DuplicateStore.rankedID(8), site: site, active: true)+        let shared = DuplicateStore.rankedID(1)+        let sibling = store.addEntry(id: shared, key: "chapter-1", capturedAt: 0, site: site)+        // The whole trio, as `applyAssignmentProvenance` writes it.+        sibling.editCitations {+            $0.workAssignment = .urlRule(CitedRule(id: ruleID))+            $0.workURL = CitedRule(id: ruleID)+            $0.workURLAssignmentKind = .wholeTitleFallback+        }+        let carrier = store.addEntry(id: shared, key: "chapter-1", capturedAt: 0, site: site)+        carrier.intentionallyUnattached = true+        carrier.editCitations { $0.workAssignment = .manual }+        try store.commit()+        #expect(try store.diagnose().tupleDiagnoses.isEmpty, "the fixture did not start valid")++        try store.reconcileToFixedPoint()++        let entries = try store.entryFacts()+        #expect(entries.count == 2)+        #expect(entries.allSatisfy { $0.intentionallyUnattached })+        #expect(entries.allSatisfy { $0.workID == nil })+        #expect(entries.allSatisfy { $0.workAssignmentProvenance == .manual })+        #expect(try store.read { context in+            try context.fetch(FetchDescriptor<Entry>()).map(\.citationValues)+                .allSatisfy { $0.workURL == nil && $0.workURLAssignmentKind == nil }+        })+        #expect(+            try store.diagnose().tupleDiagnoses.isEmpty,+            "the fan-out quarantined the hostname")+        // The repaired library is a fixed point: another pass writes nothing.+        #expect(try store.reconcile().wroteNothing)+    }+     // MARK: - Q67: outcome content never writes an assignment      @Test("Outcome content never writes a work assignment")
Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift Modified +175 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swiftindex b8ac606b..eb93efa0 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift@@ -170,6 +170,139 @@ struct DuplicateResolutionTests {         #expect(row.firstCapturedAt == ResolutionFixture.epoch)     } +    // MARK: - T-2361: the unattachment flag travels with its provenance++    /// The chosen variant is the one the reader deliberately left unattached,+    /// and the survivor is recomputed as the earliest capture (Q21) — a row+    /// whose own assignment arm is still `.none`. Writing the flag without the+    /// `.manual` citation it requires left a graph+    /// `LibraryValidator.validateAssignment` refuses, so the commit gate rolled+    /// the whole resolution back and the reader could not resolve the set at all.+    @Test("Choosing an unattached variant writes the manual provenance the flag requires")+    func unattachedOutcomeCarriesItsProvenance() async throws {+        let library = try ResolutionFixture()+        var earliest = UUID()+        try library.seed { store in+            store.insertSite(hostname: "dup.example")+            // Authored by its note alone; its assignment arm was never written.+            earliest = store.insertEntry(+                key: "one", title: "A", offset: 0, note: "earlier").id+            let unattached = store.insertEntry(key: "one", title: "A", offset: 40)+            unattached.intentionallyUnattached = true+            unattached.editCitations { $0.workAssignment = .manual }+        }+        let repository = try await library.openForApp()+        let setKey = try await Self.onlyEntrySetKey(repository)+        let contract = try await repository.projectDuplicateResolution(setKey: setKey)+        guard case .entry(_, let variants, _, _) = contract else {+            Issue.record("expected an Entry contract")+            return+        }+        let chosen = try #require(variants.first(where: \.intentionallyUnattached)?.id)++        let outcome = try await repository.commitDuplicateResolution(+            contract, choosing: chosen, appendingOtherNotes: false)++        #expect(outcome == .committed(survivorID: earliest))+        let rows = try library.entryRows()+        #expect(rows.count == 1)+        let row = try #require(rows.first)+        #expect(row.intentionallyUnattached)+        #expect(row.workID == nil)+        #expect(row.workAssignmentProvenance == .manual)+    }++    /// The same choice over a survivor a **URL rule** attached: it points at a+    /// Work and carries the `.urlRule` arm with the URL trio beside it. The+    /// unattachment has to take the pointer and the whole trio with it, or the+    /// validator refuses the row either way.+    @Test("Choosing an unattached variant detaches a URL-assigned survivor, trio and all")+    func unattachedOutcomeClearsTheSurvivorsURLAssignment() async throws {+        let library = try ResolutionFixture()+        let ruleID = UUID()+        var earliest = UUID()+        try library.seed { store in+            try store.insertTaughtSite(hostname: "dup.example", urlRuleID: ruleID)+            let work = store.insertWork(title: "Serial", offset: 0)+            let survivor = store.insertEntry(key: "one", title: "A", offset: 0, note: "earlier")+            earliest = survivor.id+            store.assignByURLRule(survivor, to: work, ruleID: ruleID)+            let unattached = store.insertEntry(key: "one", title: "A", offset: 40)+            unattached.intentionallyUnattached = true+            unattached.editCitations { $0.workAssignment = .manual }+        }+        #expect(try library.diagnose().tupleDiagnoses.isEmpty, "the fixture did not start valid")+        let repository = try await library.openForApp()+        let setKey = try await Self.onlyEntrySetKey(repository)+        let contract = try await repository.projectDuplicateResolution(setKey: setKey)+        guard case .entry(_, let variants, _, _) = contract else {+            Issue.record("expected an Entry contract")+            return+        }+        let chosen = try #require(variants.first(where: \.intentionallyUnattached)?.id)++        let outcome = try await repository.commitDuplicateResolution(+            contract, choosing: chosen, appendingOtherNotes: false)++        #expect(outcome == .committed(survivorID: earliest))+        let rows = try library.entryRows()+        #expect(rows.count == 1)+        let row = try #require(rows.first)+        #expect(row.intentionallyUnattached)+        #expect(row.workID == nil)+        #expect(row.workAssignmentProvenance == .manual)+        #expect(try library.entryCitations().allSatisfy {+            $0.workURL == nil && $0.workURLAssignmentKind == nil+        })+    }++    /// The **attached** arm of the same write. The chosen variant is the+    /// carrier's manual assignment to a Work; the recomputed survivor (Q21) is a+    /// row a URL rule assigned to that same Work. Copying the carrier's `.manual`+    /// arm onto it left the URL trio in place, which the validator refuses as+    /// "manual assignment has incompatible relationship or provenance", and the+    /// commit gate rolled the whole resolution back.+    @Test("Choosing a manually attached variant clears the survivor's URL assignment trio")+    func attachedOutcomeClearsTheSurvivorsURLAssignment() async throws {+        let library = try ResolutionFixture()+        let ruleID = UUID()+        var earliest = UUID()+        var workID = UUID()+        try library.seed { store in+            try store.insertTaughtSite(hostname: "dup.example", urlRuleID: ruleID)+            let work = store.insertWork(title: "Serial", offset: 0)+            workID = work.id+            let survivor = store.insertEntry(key: "one", title: "A", offset: 0, note: "earlier")+            earliest = survivor.id+            store.assignByURLRule(survivor, to: work, ruleID: ruleID)+            // `work:` seeds the `.manual` arm the reader's own move writes.+            store.insertEntry(key: "one", title: "A", offset: 40, work: work)+        }+        #expect(try library.diagnose().tupleDiagnoses.isEmpty, "the fixture did not start valid")+        let repository = try await library.openForApp()+        let setKey = try await Self.onlyEntrySetKey(repository)+        let contract = try await repository.projectDuplicateResolution(setKey: setKey)+        guard case .entry(_, let variants, _, _) = contract else {+            Issue.record("expected an Entry contract")+            return+        }+        let chosen = try #require(variants.first(where: { $0.workID != nil })?.id)++        let outcome = try await repository.commitDuplicateResolution(+            contract, choosing: chosen, appendingOtherNotes: false)++        #expect(outcome == .committed(survivorID: earliest))+        let rows = try library.entryRows()+        #expect(rows.count == 1)+        let row = try #require(rows.first)+        #expect(!row.intentionallyUnattached)+        #expect(row.workID == workID)+        #expect(row.workAssignmentProvenance == .manual)+        #expect(try library.entryCitations().allSatisfy {+            $0.workURL == nil && $0.workURLAssignmentKind == nil+        })+    }+     // MARK: - Staleness (Req 4.6)      @Test("A variant arriving after the sheet refuses the confirmation and re-presents")@@ -1172,6 +1305,16 @@ private final class ResolutionFixture {             .sorted { $0.firstCapturedAt < $1.firstCapturedAt }     } +    /// Every surviving row's citation blob, for the arms `EntryFacts` does not+    /// carry (the URL trio).+    func entryCitations() throws -> [EntryCitations] {+        try readContext().fetch(FetchDescriptor<Entry>()).map(\.citationValues)+    }++    func diagnose() throws -> LibraryDiagnostics {+        try LibraryValidator.validate(context: readContext())+    }+     func workRows() throws -> [WorkFacts] {         try readContext().fetch(FetchDescriptor<Work>())             .map(WorkFacts.init)@@ -1222,6 +1365,38 @@ private final class ResolutionSeedStore {         return site     } +    /// A taught site holding the one active title rule the validator requires+    /// of it and one current URL rule, so a seeded Entry can cite the rule.+    @discardableResult+    func insertTaughtSite(hostname: String, urlRuleID: UUID) throws -> Site {+        let site = insertSite(hostname: hostname)+        site.mode = .taught+        let pattern = try TitlePattern(+            id: UUID(), version: 1, isActive: true, createdAt: ResolutionFixture.epoch,+            definition: .segment(+                work: try SegmentRangeSpec(origin: .start, offset: 0, length: 1), ignored: []),+            trimPrefix: nil, trimSuffix: nil, site: site)+        context.insert(pattern)+        let rule = try URLRulePattern(+            id: urlRuleID, version: 1, isCurrent: true, createdAt: ResolutionFixture.epoch,+            origin: .readerTaught,+            definition: .work(locator: .query(name: ExactScalarString("identity"))), site: site)+        context.insert(rule)+        return site+    }++    /// The assignment a URL rule makes: the `.urlRule` arm with the URL trio+    /// beside it, as `applyAssignmentProvenance` writes it. Not authored, so the+    /// row reads as bare on its assignment.+    func assignByURLRule(_ entry: Entry, to work: Work, ruleID: UUID) {+        entry.work = work+        entry.editCitations {+            $0.workAssignment = .urlRule(CitedRule(id: ruleID))+            $0.workURL = CitedRule(id: ruleID)+            $0.workURLAssignmentKind = .wholeTitleFallback+        }+    }+     /// A `Series` row, so the sheet has a label to show for a membership rather     /// than the "Unavailable series" placeholder.     @discardableResult
specs/bugfixes/unattached-flag-without-manual-provenance/report.md Added +270 / -0
diff --git a/specs/bugfixes/unattached-flag-without-manual-provenance/report.md b/specs/bugfixes/unattached-flag-without-manual-provenance/report.mdnew file mode 100644index 00000000..0e115ac6--- /dev/null+++ b/specs/bugfixes/unattached-flag-without-manual-provenance/report.md@@ -0,0 +1,270 @@+# Bugfix Report: Duplicate resolution can set intentionallyUnattached without manual provenance++**Date:** 2026-09-22+**Status:** Fixed+**Ticket:** T-2361++## Description of the Issue++`Entry.intentionallyUnattached` is only a legal state beside a `.manual`+work-assignment citation, a nil `work`, and no URL reference; and a `.manual`+arm is only legal with no URL reference beside it. Two duplicate writers set+the flag and nil the pointer without touching the citation blob:++- `LibraryRepository+DuplicateResolution.applyEntryOutcome` — the reader's+  resolution, writing the chosen variant onto the recomputed survivor;+- `DuplicateReconciler.apply(_ carrier: Entry, to rows:)` — the silent+  same-UUID fan-out.++Both are reachable because `GroupOrdering.authoredContent(of:)` gates the+assignment on `.manual` but the flag on nothing: a row whose own citation is+`.none` (or `.urlRule`) reads as **bare**, bare folds into authored, so the set+has one variant and the row is a fan-out target rather than a second variant.++The same defect sits one branch down in `applyEntryOutcome`: its **attached**+arm copies the carrier's `.manual` assignment arm onto the survivor without+clearing the URL trio the survivor may carry. A survivor a URL rule assigned+keeps `workURL` and `workURLAssignmentKind` under a `.manual` arm, which the+validator refuses as "manual assignment has incompatible relationship or+provenance", and the commit gate rolls the resolution back. Found in review.++**Reproduction (both covered by the regression tests below):**++1. Two rows share one record UUID. One carries `intentionallyUnattached` with+   its `.manual` citation; the other is bare with a `.none` assignment arm.+2. Run `reconcileAfterSync`. The fan-out sets the flag on the bare row and+   leaves its `.none` arm.+3. `LibraryValidator` refuses it: `Invalid Entry tuple <id>: none assignment has+   incompatible relationship or provenance`, which quarantines the hostname.++And on the reader's path:++1. A divergent Entry set where the chosen variant is the intentionally+   unattached one and the earliest-captured member (the recomputed survivor,+   Q21) carries a `.none` assignment.+2. Confirm the resolution. `commitResolution` validates, finds the diagnosis it+   just introduced, and rolls the whole thing back with "The resolution produced+   an invalid library state".++And the attached arm, on the same path:++1. A divergent Entry set where the chosen variant is manually assigned to a+   Work and the earliest-captured member is a row a URL rule assigned to it —+   `.urlRule` arm, `workURL` and `workURLAssignmentKind` all set.+2. Confirm the resolution. The survivor gets `.manual` over its URL trio, and+   the commit is rolled back the same way.++**Impact:**++- *Silent path* (reconciler): a corrupt row is committed — the chunk save has no+  validation gate — and the hostname is quarantined on the next validation.+  Quarantine blocks teaching, capture-time rule application and export for that+  site. Recoverable by the reader through Move To → Leave unattached, which does+  write the manual provenance, but nothing tells them that.+- *Reader path* (resolution): fails closed. Nothing is written; the reader simply+  cannot resolve that duplicate set.++Unverified against a real library: confirming whether such a row already exists+needs a Library Check on the owner's device, which is out of scope here.++## Investigation Summary++- **Symptoms examined:** the ticket's two line references, read against+  `LibraryValidator.validateAssignment` (`LibraryValidator.swift:1313`+  onwards).+- **Code inspected:** `LibraryRepository+DuplicateResolution.swift`+  (`applyEntryOutcome`, `commitResolution`), `DuplicateReconciler.swift`+  (`apply`, `resolveEntrySets`), `GroupOrdering.swift` (`authoredContent(of:)`,+  `EntryAuthoredContent.isBare`), `LibraryRepository.applyManualAssignment` and+  `LibraryRepository+WorkDeletion` (the two *correct* writers), and+  `DuplicateScan.swift` for how a bare sibling folds into one variant.+- **Hypotheses tested:**+  - *"The fan-out is unreachable, because a differing flag would be a second+    variant"* — ruled out: `EntryAuthoredContent.isBare` makes the sibling bare+    and `GroupOrdering.variants` folds bare into authored. Reproduced.+  - *"The resolution path corrupts the library"* — ruled out: `commitResolution`+    gates on `introducedDiagnosis` and rolls back. It fails closed instead.+  - *"Only the `.none` arm is affected"* — ruled out: a `.urlRule` sibling is+    bare by the same read and produces "URL assignment requires one known+    assignment arm".+  - *"Only the unattached arm is affected"* — ruled out in review: the attached+    arm copies `.manual` over a `.urlRule` survivor's URL trio. Reproduced by+    `attachedOutcomeClearsTheSurvivorsURLAssignment`, which fails with 4 issues+    against the previous copy of the arm.++## Discovered Root Cause++The invariant "the unattachment flag, a nil `work`, a `.manual` assignment+citation and no URL reference move together" existed in exactly one place —+`LibraryRepository.applyManualAssignment` — and the two duplicate writers wrote+half of it by hand instead of going through it. The attached arm wrote a+different half: the `.manual` arm without the trio clear.++**Defect type:** incomplete state transition; an invariant duplicated by hand+rather than shared.++**Why it occurred:** `applyManualAssignment` also stamps `modifiedAt`, which+neither duplicate writer may do (the reconciler must read no clock, and the+resolution owns its own timestamps), so neither could call it as it stands. The+citation half was then written out at the detach sites and left out at the+duplicate sites.++**Contributing factors:** the duplicate writers' "no assignment is ever written"+rule (Q67) reads as *do not touch the assignment arm*, which is right for a+pointer copy and wrong for an unattachment — an unattachment **is** an+assignment decision.++## Resolution for the Issue++**Changes made:**++- `Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift`+  — new `EntryCitations.assignManually()`: the clock-free citation half of a+  manual assignment (`.manual` arm, nil `workURL`, nil+  `workURLAssignmentKind`), spelt once.+- `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift`+  — `applyManualAssignment` calls the helper and keeps its `modifiedAt` stamp.+- `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift`+  — `applyEntryOutcome`'s unattached arm calls the helper inside the+  `editCitations` block it is already in, before returning; its **attached**+  arm calls the helper instead of copying `carried.workAssignment`, so a+  `.urlRule` survivor loses its trio with the arm.+- `Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift`+  — the fan-out's unattachment write calls the helper through `editCitations`.+- `Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift`+  — comment only: the note naming T-2361 as an open hole now records that the+  two writers carry the provenance and why the read stays ungated.+- `specs/duplicate-reconciliation/decision_log.md` Q128, Q129 and+  `specs/remove-article-mode/decision_log.md` Q35 — the narrowing of Q67, the+  reversal of Q85, and the answer to Q11.++**Approach rationale:** write the invariant, not the carrier's blob. `.manual`+is a constant, so both devices reach the same fixed point from synced content+with no clock and no `PersistentIdentifier` read; `editCitations` is+value-guarded, so a row already in the state is not written again and the pass+stays idempotent. Copying the carrier's assignment arm instead would propagate+a carrier that is itself in the broken state — and, on the attached arm, did+propagate `.manual` on top of a survivor's URL trio. A content assignment is by+definition the carrier's `.manual` arm (`authoredContent` reads no other kind+as authored), so writing the constant loses nothing the copy carried.++**Alternatives considered:**++- *Call `applyManualAssignment`* — it stamps `modifiedAt` from a passed clock.+  The reconciler has no clock by design and the resolution stamps its own rows+  later; adding a timestamp here would write a different `modifiedAt` on two+  devices. Rejected.+- *Gate `GroupOrdering.authoredContent`'s flag read on `.manual` provenance* —+  would make the fan-out unreachable, but it also reclassifies any row already+  in the broken state as bare on one device and authored on another, which is+  exactly what `remove-article-mode` Q11 rejected. Rejected; the ungated read+  stays.+- *Add a heal pass for rows already broken* — a survivor that has outlived its+  group is not in any duplicate set, so a heal would need a whole-table scan on+  every reconcile; and the fan-out itself skips the carrier and any row already+  holding the flag, so a pre-fix row *inside* a set is not healed either. The+  reader's Move To → Leave unattached already repairs such a row. Not done;+  recorded here and in Q129 instead — it needs a decision of its own.++## Regression Tests++**Test file:** `Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTests.swift`++- `unattachmentFanOutCarriesItsProvenance` — a bare `.none` sibling of an+  unattached carrier converges to `.manual`, no Work, and leaves no tuple+  diagnosis; a further pass writes nothing, so the repair is a fixed point.+  Before the fix: "none assignment has incompatible relationship or+  provenance".+- `unattachmentFanOutClearsTheURLAssignment` — a sibling a URL rule assigned+  loses its whole URL trio and its Work with the flag, leaves no diagnosis, and+  a further pass writes nothing. Before the fix: "URL assignment requires one+  known assignment arm".++Both start by asserting the fixture is valid, so a red run is the pass's and+not the seed's.++**Test file:** `Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift`++- `unattachedOutcomeCarriesItsProvenance` — choosing the unattached variant of a+  divergent set commits onto the earliest-captured survivor and leaves it+  unattached with `.manual` provenance. Before the fix the commit was refused+  and nothing was written.+- `unattachedOutcomeClearsTheSurvivorsURLAssignment` — the same choice over a+  survivor a URL rule attached to a Work: the pointer and the whole trio go+  with the flag.+- `attachedOutcomeClearsTheSurvivorsURLAssignment` — choosing a manually+  attached variant over a `.urlRule` survivor of the same Work commits with the+  `.manual` arm and no trio. Against the previous copy of the attached arm this+  fails with 4 issues (the commit is refused and the row keeps its trio).++**Run command:**++```+cd Packages/AsterismCore && swift test --no-parallel \+  --filter "unattachmentFanOut|OutcomeCarriesItsProvenance|OutcomeClearsTheSurvivorsURLAssignment"+```++## Affected Files++| File | Change |+|------|--------|+| `Packages/AsterismCore/Sources/AsterismCore/EntryCitations.swift` | `assignManually()`: the manual-assignment citation triple, spelt once |+| `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift` | `applyManualAssignment` uses the helper |+| `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift` | Unattached and attached outcomes write the manual assignment citation |+| `Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift` | Unattachment fan-out writes the manual assignment citation |+| `Packages/AsterismCore/Sources/AsterismCore/GroupOrdering.swift` | Comment: T-2361 is closed at the writers |+| `Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTests.swift` | Two regression tests |+| `Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateResolutionTests.swift` | Three regression tests, plus taught-site and URL-rule seeding helpers |+| `specs/duplicate-reconciliation/decision_log.md` | Q128 (Q67 narrowed), Q129 (Q85 reversed) |+| `specs/remove-article-mode/decision_log.md` | Q35 (Q11 answered) |++## Verification++**Automated:**+- The first three regression tests, red before the fix (9 recorded issues+  across them), green after; the attached-arm test, red against the previous+  copy of the arm (4 issues), green after.+- `make test-core` on the fix: `EXIT=0`, 3,064 passing tests, 0 failures, 0+  known issues, no new compiler warnings — the pre-commit bar.+- Re-run after the review round (helper, attached arm, two new tests):+  2,992 passing, 0 known issues, no new compiler warnings, and three suites+  red — `Pending-capture drain`, `Pending-capture spool` and `Preserve-first+  share flow`, 123 issues, all `NSCocoaErrorDomain 257` / EPERM on the spool's+  files. The same three fail identically (123 issues) on a clean `main`+  checkout on the same host, and none of them touches the changed code; that+  is the host's permission condition noted in `docs/agent-notes/testing.md`'s+  locked-keychain entry, not this branch. The two affected suites+  (`DuplicateReconcilerTests`, `DuplicateResolutionTests`: 91 tests, 3 suites)+  pass on their own.++**Not verified:**+- Whether a real library already holds such a row. That needs Library Check on+  the owner's device and is deliberately untouched here.++## Prevention++- An invariant spanning a flag, a relationship and a citation belongs in one+  named write. `EntryCitations.assignManually()` is now the citation half of+  it, and `applyManualAssignment` keeps only the clock stamp on top; a fourth+  writer that spells the triple by hand is the thing to refuse in review.+- The validator already states the invariant precisely. A fixture that runs+  `LibraryValidator.validate` after a convergence pass — which the two new+  reconciler tests now do — is what catches this class.++## Related++- `specs/remove-article-mode/` Q6 and Q11 — the arms this fix has to satisfy;+  Q35 answers Q11.+- `specs/duplicate-reconciliation/` Q67, Q85 — the "no assignment is ever+  written" rule and the flag/pointer pairing; Q128 narrows the first and Q129+  reverses the second.+- **Follow-up candidate, not fixed here:** `applyEntryOutcome`'s+  rejected-attached-variant branch (the `else if+  citations.workAssignment.provenanceKind == .manual` arm) writes `.none` while+  keeping `row.work`, which the validator refuses as "none assignment has+  incompatible relationship or provenance" unless the blob is absent — so+  choosing a variant *without* an assignment over a survivor that has a manual+  one rolls the resolution back. Pre-existing and out of this ticket's scope;+  the same shape of defect, worth its own ticket.+- T-2328 — the write-before-Save violations list; unrelated, but the same shape+  of "one invariant, two writers".
specs/duplicate-reconciliation/decision_log.md Modified +2 / -0
diff --git a/specs/duplicate-reconciliation/decision_log.md b/specs/duplicate-reconciliation/decision_log.mdindex 7b8014de..433e6441 100644--- a/specs/duplicate-reconciliation/decision_log.md+++ b/specs/duplicate-reconciliation/decision_log.md@@ -131,6 +131,8 @@ | Q125 | 2026-08-02 | Req 10.1's samples come from re-seeded **generations** over one store, not from a fresh 5,000-Entry store per sample; each generation is a fresh UUID namespace | A fresh store per sample is ~20 s of seeding for ~1 s of measurement, three runs deep. The generation has to be fresh because `DuplicateSetKey` is the member UUIDs: re-seeding identical rows would hand the next pass a key the ledger had already fingerprinted at that exact shape, so it would delete on *first* observation and the pass after it would be measuring an empty library. Every row a generation ever seeded is deleted before the next one is written, so the library's row count returns to the seeded shape rather than growing per sample | | Q126 | 2026-08-02 | Both passes are timed and both are asserted against Req 10.1's 2 s; the requirement's number is the second | Req 2.3 forbids a first observation from deleting, but it does not forbid it from *writing*: the survivor's outcome content and every Entry of a losing Work move on pass 1, because Req 2.1 needs them committed before a deletion can exist. Pass 1 is the write-heavy half and pass 2 the deletion-heavy one, so quoting only the second would let a pass meet 2 s by having deferred half its work to the pass before it | | Q127 | 2026-08-02 | `M4ToleratedScalePerformanceTests.captureRuleApplication` names its three states instead of iterating `allCases` | Req 5.4 is `library-integrity-tolerance`'s, and its "every state from 1.1" means *that* spec's three tolerated states. `.duplicateSets` is this spec's Req 10.1 fixture shape, not a tolerated state; measuring it there would assert one spec's budget over another spec's fixture and add a fourth 5,000-Entry seed to a half-hour target |+| Q128 | 2026-09-22 | Q67 is narrowed: outcome content writes no assignment **pointer**, but both duplicate writers write the constant `.manual` arm (with the URL trio cleared) whenever they carry an unattachment or a manual assignment onto a survivor | T-2361: the flag is a legal state only beside a `.manual` arm and no URL reference, and a content assignment is by definition the carrier's `.manual` arm, so a survivor whose own arm is `.none` or `.urlRule` was left in a shape the validator refuses — quarantined on the silent path, rolled back on the reader's. An unattachment or a manual assignment *is* an assignment decision; what Q67 forbids is copying the normalised key or the pointer, and neither is touched. `.manual` is a constant, so two devices reach one fixed point, and `editCitations` is value-guarded, so the fixed point writes nothing. Spelt once as `EntryCitations.assignManually()`, which the reader's `applyManualAssignment` shares |+| Q129 | 2026-09-22 | Q85's "provenance is deliberately left alone" is reversed: writing `intentionallyUnattached` as outcome content also writes the `.manual` arm | Q85 held while Articles mode's `.none` writer existed, because the flag then had a legal `.none` pairing and inventing a provenance could have been wrong (Decision 10). `remove-article-mode` deleted that writer and Q6 made `.none` refuse the flag, so `.manual` is now the only arm the flag may carry and writing it invents nothing. The fan-out is a guard, not a heal: the carrier and a row already flagged are skipped, so a row an earlier build left flagged with a `.none` arm stays until the reader moves it; a heal pass would need a decision of its own |  ## Decision 1: Bare-side auto-collapse relaxes "identical" for Entries and Works 
specs/remove-article-mode/decision_log.md Modified +1 / -0
diff --git a/specs/remove-article-mode/decision_log.md b/specs/remove-article-mode/decision_log.mdindex ba06c49c..5c31acfd 100644--- a/specs/remove-article-mode/decision_log.md+++ b/specs/remove-article-mode/decision_log.md@@ -38,6 +38,7 @@ | Q32 | 2026-09-22 | `schema-migration.md` was rewritten where a removing bump falsified it, not renumbered | Three standing claims were true only of adding stages: that the live stored shape is never a subset of the frozen one (V16 restores the subset until the next adding version, and a stale frozen registration then answers a key the live schema lacks), that a stage needs a default, and that a removing stage changes no wire shape (true of V9, whose dropped columns were never archived; false of V16). `asterism-design.md` §4.6 is struck through and put in the past tense, not deleted, so §4.5 to §4.7 stays explained | | Q33 | 2026-09-22 | Requirements 1.1, 1.2, 1.4, 2.1 and 2.4 are proved by deletion and the Req 7.2 grep, and 2.3 by the compiler | No test asserts the absence of a removed view or identifier; the views, identifiers and the parameters that carried the mode are gone, so there is nothing left to assert against. Recorded so the coverage reads as chosen, not missed | | Q34 | 2026-09-22 | The seven UI failures are not this branch's, and Req 7.1's two UI targets stay red until `main` fixes them | Run on `main` at `36d874e9`: four fail there verbatim (three works-options cases already root-caused in `launch-to-today` §3.4, and the largest-Dynamic-Type entry card, which asserts before it scrolls), one is already fixed by #82, which landed after this branch was cut, and the two Today cases fail only on the first day of the displayed week, which is the day every branch run was made. This supersedes Q23's load explanation. The branch was then rebased onto `main` at `36d874e9`, after which `make test-ui-ipad` passes (30 tests, 0 failures), so `make test` is the one target left red; whether Req 7.1 is waived for the failures `main` owns is the owner's call. `implementation.md` has the table |+| Q35 | 2026-09-22 | Q11's "the gate belongs to T-2361" is answered: T-2361 closed the two duplicate writers instead of gating the read | Both writers now carry the `.manual` arm with the flag (`duplicate-reconciliation` Q128, Q129), so no current writer leaves the flag on a `none` row. `authoredContent(of:)` stays ungated all the same: a row from before the fix, or one a future writer leaves half-written, would still read as bare on one device and authored on another, and the ungated read is what makes such a sibling a fan-out target that the fix repairs rather than a second variant it cannot reach |  ## Decision 1: Assume no articles Site exists and build no conversion 

Things to double-check

Full Core run on an unlocked host.

The verification here skipped PendingCaptureSpoolTests, PendingCaptureDrainTests and ShareCaptureFlowTests, which fail with EPERM on this host on main as well (locked login keychain, docs/agent-notes/testing.md). None touches the changed code, but make test-core with zero known issues is the pre-commit bar and is still owed.

Carrier itself in the illegal state.

A carrier flagged with a .none arm is skipped by row !== carrier: its siblings get the constant, it stays illegal, and the pre-existing diagnosis stands. The set reaches a fixed point with the quarantine intact. Documented as 'guard, not heal'; make sure that is the intended behaviour rather than an accident of the skip.

Follow-up ticket for the .none-over-work branch.

The report names it; nothing tracks it. Same function, same defect class, one line to fix. Decide whether it goes in now or gets a ticket before merge.