asterism branch T-2334/bugfix-reimport-dirties-every-row commits 4 files 11 touched lines +554 / -126

Pre-push review: T-2334/bugfix-reimport-dirties-every-row

Second review round of PR #88 against origin/main (base c314419d). Value-guards every write in the backup-import upsert so a re-import of an archive the library already matches dirties no row and re-exports nothing through the CloudKit mirror. Round one's five findings are all resolved in 0c137a7f.

At a glance

  • All five round-one findings resolved in 0c137a7f: report accuracy on mergeImportedWorkTypes/mergeImportedCreatorDirectories, nil-blob citation arm, applyThumbnail doc, empty-library spec lines, shared double and decodable-and-different test arm.
  • The fix: ~60 inline if row.x != record.x { row.x = record.x } guards across LibraryRepository+ConfirmImport.swift, BackupImportRecords.swift and RecordRow.swift; !== identity guards on the Site/Work relationships; a three-arm decode-and-compare guard on the citations blob.
  • Correctness checked: every guarded relationship target is registered in the same ModelContext as the row (identity matches); credit roleIDs/modifiedAt ordering unchanged; membership workID ?? current equivalent; enum columns compared raw so no tolerant-read trap.
  • Tests: 2,754 passed, 0 failed, three EPERM suites skipped (host keychain, same on main); the three branch tests pass; full make test-core on an unlocked host is owed.
  • Open minors (not applied): facts guard drops the undecodable-bytes heal the old unconditional write gave; Req 1.8 mis-citation in three places; Decision 4 note wording; Req 5.1 text still disclaims the property its test now asserts.
  • Unmeasured: no performance arm imports over a matched library — both M4 import arms start empty — so the added relationship reads on the update path are reasoned cheap (registered objects, no store round trip), not measured.

Verdict

Ready to push

Every round-one finding is resolved: the report's merge-path claim is corrected, the citation guard converts a nil blob and the test pins that arm plus the decodable-and-different arm, the applyThumbnail note is rewritten, the empty-library spec is amended, and the save-strategy double is shared. The guards themselves are correct: sitesByHostname, workTargets and every row are fetched in the one import context so the !== identity guards match, the credit and membership rewrites keep their old ordering, and the enum columns compare raw. AsterismCore: 2,754 tests in 260 suites passed on this host with the three pending-capture suites (PendingCaptureSpoolTests, PendingCaptureDrainTests, ShareCaptureFlowTests) skipped because they EPERM here on main too (keychain condition, docs/agent-notes/testing.md); make verify-identity passes; no compiler warning in any touched file. A full make test-core on an unlocked host is still owed before the push. What remains is minor and none of it was applied, because this review was asked not to modify the branch: the facts guard compares through the tolerant decode and so no longer clears undecodable fact bytes against an archive with no facts — the same trap the branch pins for citations, applied inconsistently to the other blob; the citation comment, the test doc and the report cite work-thumbnails Req 1.8 (a thumbnail requirement) for a citation heal that is actually drop-superseded-columns Q24/Q25; and Decision 4's note says "the negative consequence" where two are listed. Worth one small commit, not a block.

Review findings

11 raised · 0 fixed · 11 skipped

Jump to findings →

Tests

Pass rate: 100% (2970 of 2970)

New tests: 2

Diff coverage: 93% (312 of 334 added lines)

Jump to tests →

Commits

Three-level explanation

What changed

Asterism can back up its library to an archive file and restore it. Restoring works like an upsert: for each record in the archive it finds the matching row in the database and copies the archive's values over. Before this branch that copy was unconditional — every field was written, even when the value was already identical. The database (SwiftData) does not check whether a written value is new; any assignment marks the row as changed, and a changed row is pushed to iCloud. So importing an archive you had just exported re-uploaded your entire library for nothing.

The fix reads each field first and writes it only when it actually differs. That is done for every scalar column on Works, Entries, memberships, series, links, credits, distinct pairs, characters, places and their suppressions, plus the coverage fingerprints. Relationships (an Entry's Site or Work) are compared by object identity, and the citations blob — stored as JSON bytes — is decoded and compared as a value, with two extra rules: bytes that cannot be decoded are always rewritten (so a restore repairs a broken row), and a row that has no bytes at all is always given some (so an old row from before the column existed gets converted).

Why it matters

Sync traffic used to scale with the library on every re-import, and the project's own rule — a field is written only when it differs, so a fixed point exports nothing — was being broken by the importer. Two tests now import the same archive twice and assert that hasChanges is false before every save of the second pass.

Key concepts

  • Value guard: if a != b { a = b }. Cheap, and it keeps a no-op write from dirtying a row.
  • Dirty row / hasChanges: SwiftData's flag that something will be written at the next save. The tests read it immediately before each save through an injected save strategy.
  • Tolerant read: a getter that returns a default instead of throwing on bad data. Handy for screens, dangerous under a value guard: two broken things can look "equal" and the repair is skipped.

Changes overview

  • LibraryRepository+ConfirmImport.swift (+176/-75): every scalar write in apply(_:to:) for Work, Membership and Entry, and the inline writes in the series, link, credit and distinct-pair commits, is guarded. Site/Work relationship assignments on the entry and membership loops are guarded by !==. The citations write becomes if entry.citationsAreAbsent || decoded == nil || decoded != record.citations { setCitations }.
  • BackupImportRecords.swift: the generic RecordRow/SuppressionRow appliers and the two fingerprint writers.
  • RecordRow.swift: the four attach implementations — identity guard for Character rows (a real relationship), UUID-column guard for Place rows.
  • Tests: a golden-library double-import in BackupV15ImportTests (every record kind, hasChanges sampled per save), a four-arm unit test of the citation applier, and the EmptyLibraryTests assertion Decision 4 had dropped, restored. ChangeRecordingSaveStrategy moves to its own shared file and gains dirtySaves.
  • Docs: the bugfix report, and five amendments in specs/empty-library/ noting the clause is back.

Implementation approach

The explicit inline form is the project convention (applyDesignation, WorkTypeWriter.apply, SiteReconciler.applyUnion, DuplicateReconciler.convergeRecordGroups all do it), and an inout helper would defeat the purpose: @Model setters run under withMutation regardless of value, so get→set through inout dirties the row. The recency gate (record.modifiedAt >= row.modifiedAt) is left untouched; it decides whether a record may write, the guards decide which columns still differ.

Trade-offs

  • editCitations { $0 = record.citations } was rejected because Q23 makes it leave a nil blob nil on a no-op edit, whereas import must convert one (the validator reports a nil blob and names the archive as its repair). The importer therefore restates the undecodable arm from Q24 and adds the nil arm.
  • The citation guard costs one extra decode per matched Entry; the encode it replaces was the same order of work, and entryGroup already decodes the blob twice per row upstream, so the no-op path is not slower.
  • The facts guard goes through the tolerant RecordFactCodec.decode, so undecodable fact bytes against an archive with no facts now compare equal and stay — where the old write cleared them to nil. Nothing diagnoses or promises that heal, but it is the same trap the citation test pins, and the reconciler guards the same column by bytes.

Technical deep dive

Identity guards are sound only because sitesByHostname (fetched at :196, inserts at :211), workRows/workTargets (:280/:316) and entryRows (:380) all come from the single context the upsert writes in; a target fetched elsewhere would never be === and every relationship write would dirty. The golden test proves this empirically — a mismatch fails dirtySaves.allSatisfy { !$0 }. !== on AnyObject? treats nil/nil as equal, which is the right answer for an orphan.

The credit path is the one non-trivial reorder: the roleIDs guard is nested inside the unchanged modifiedAt > || isSuperset condition, which still reads row.modifiedAt before the modifiedAt write moves to the end — semantics preserved. Membership's record.workID ?? membership.workID then != is equivalent to the old fallback assignment. Enum columns are compared raw (*Raw), so an unknown raw value survives a re-import untouched instead of being rewritten to its tolerated default — a small behaviour improvement, not a regression. releaseDays is the one accessor-based compare on Work: an unknown day in releaseDaysRaw beside the archive's set now survives where the old write replaced the column; arguably better (never regress a newer build's value) but the adjacent comment still says the restore "has to clear a local set".

Architecture impact

Import now satisfies the Convergence fixed-point property CLAUDE.md states for the silent path: a matched library plus its own archive is a no-op at every save boundary. That makes the Empty Library → import → re-import round trip in empty-library Req 5.1 a clean-save property again, and the assertion is back in that spec's test. Nothing else on the path changed: chunking, the recency gate, willWriteMembership, the fingerprint match and applyThumbnail's digest guard are all as before.

Potential issues

  • Relationship faults on the update path: existing.site was never read on the entry loop before, and row.site/row.work are now read on every matched membership. Targets are registered so the to-one resolves from the row snapshot without a store round trip, but no M4 arm imports over a matched library (both import arms start empty), so this is reasoned, not measured.
  • Two blob columns, two policies: citations heal undecodable bytes by a throwing decode; facts compare through a tolerant decode and do not. RecordFactCodec.encode is canonical, so if row.factsData != RecordFactCodec.encode(record.facts) would heal, cost no decode, and match the reconciler's byte compare — at the price of a one-time rewrite of any blob written in a non-canonical layout.
  • Mis-citation: "the row Req 1.8 promises a restore heals" points at work-thumbnails Req 1.8 (digest/bytes disagreement on a cover). The citation heal is drop-superseded-columns Q24; the nil-blob repair-by-archive is Q25. The pointer is wrong in the source comment, the test doc and the report.
  • Same-UUID groups are not in the golden payload, so "every row of a group takes the write" is on the no-op test only by the argument that a group re-pointed on the first import is a fixed point on the second.

Important changes — detailed

ConfirmImport: three-arm citation guard

LibraryRepository+ConfirmImport.swift

Why it matters. The one guard that is not a plain comparison. It must skip identical citations, rewrite bytes that will not decode, and convert a nil blob — the arm round one found missing. Getting any arm wrong either re-dirties every Entry or silently stops a restore from repairing a row.

What to look at. LibraryRepository+ConfirmImport.swift:1180-1211 (apply(_: BackupV15Entry, to:))

Takeaway. A value guard over a tolerant getter is a trap: two broken values compare equal and the repair is skipped. Use the throwing read (`try? entry.citations`) so `nil` means "undecodable", and check absence (`citationsAreAbsent`) separately because a nil blob decodes to the default.
Rationale. `editCitations { $0 = record.citations }` was the reuse candidate, but Q23 makes it leave a nil blob nil on a no-op edit; import is the promised repair for such rows (Q25), so the importer restates Q24's undecodable arm and adds the absent arm. Stated in the source comment and the commit message.

ConfirmImport and RecordRow: identity guards on relationships

LibraryRepository+ConfirmImport.swift

Why it matters. Assigning the same Site/Work object back still dirties a SwiftData relationship. The guards are only correct if the target object is the one registered in the import's context — a target from another context would never be identical and every row would dirty again.

What to look at. LibraryRepository+ConfirmImport.swift:388-408 (entry loop), :673-690 (membership loop); RecordRow.swift:207-216, :247-253

Takeaway. Compare relationships by `!==` against a target fetched or inserted in the same ModelContext. `sitesByHostname` and `workTargets` are built from `context` earlier in `upsert`, so the to-one resolves from the row's snapshot without a store round trip.
Rationale. Comment in the diff: "assigning the same Site/Work reference back still dirties a SwiftData relationship, so compare by identity before writing". Same convention as `SiteReconciler` and `DuplicateReconciler`.

Work/Membership/Entry appliers: every scalar guarded

LibraryRepository+ConfirmImport.swift

Why it matters. The bulk of the fix and the bulk of the risk surface: ~50 columns, including the credit `roleIDs` superset rule and the membership `workID ?? current` fallback, where a reorder could change what a newer local record protects.

What to look at. LibraryRepository+ConfirmImport.swift:1020-1090 (Work), :1123-1142 (Membership), :1144-1180 (Entry scalars), :847-1010 (series, link, credit, distinct pair)

Takeaway. Keep the recency gate and the value guard as two questions: the gate decides whether a record may write, the guard decides which columns still differ. Compare enum columns raw so an unknown raw value survives instead of being rewritten to its tolerated default.
Rationale. The explicit inline form is the project's convention (`applyDesignation`, `WorkTypeWriter.apply`); an `inout` helper would re-dirty the row because `@Model` setters run under `withMutation` whatever the value. (inferred — not stated by the author)

BackupImportRecords: generic record/suppression appliers and fingerprints

BackupImportRecords.swift

Why it matters. Guarding only ConfirmImport left one dirty save, traced here: the character and place writers `upsert` calls as its fourth step. The `facts` guard is the one place the branch compares a blob through a tolerant decode.

What to look at. BackupImportRecords.swift:211-232 (fingerprints), :240-273 (apply for RecordRow / SuppressionRow)

Takeaway. `RecordRow.facts` reads undecodable bytes as `[]`, so `row.facts != record.facts` cannot see a broken blob. The reconciler guards this column by bytes (`row.factsData != content.factsData`) and `RecordFactCodec.encode` is canonical, so a byte compare would both heal and skip the decode.
Open question. Rationale not stated by the author and not inferable from the diff.

Tests: golden double-import and the four-arm citation unit test

BackupV15ArchiveTests.swift

Why it matters. The regression test drives every record kind through `confirmImport` twice and samples `hasChanges` immediately before each save via the injected strategy — the correct observable for "dirtied". The citation test pins the arms a byte compare or a tolerant-read guard would silently drop.

What to look at. BackupV15ArchiveTests.swift:3826-3958; ChangeRecordingSaveStrategy.swift; EmptyLibraryTests.swift:477-510

Takeaway. Read `hasChanges` inside the save strategy, before `context.save()` clears it; guard `allSatisfy` with `saves > 0` so an import that never reached its commit path cannot pass vacuously.
Rationale. Commit 334eb1a5: "Pin the citation-blob heal against a tolerant-read guard"; commit 0c137a7f added the nil-blob and decodable-and-different arms at round one's request.

Key decisions

Inline guards, not a helper.

The explicit if a != b { a = b } matches applyDesignation, WorkTypeWriter.apply, SiteReconciler.applyUnion and DuplicateReconciler.convergeRecordGroups. An inout-taking helper would go get→set through the @Model accessor and dirty the row regardless; a ReferenceWritableKeyPath helper would work but buys little over ~60 one-liners.

(inferred — not stated by the author.)
Citations: restate the arms rather than call editCitations.

editCitations leaves a nil blob nil on a no-op edit by design (drop-superseded-columns Q23). Import is the repair the validator names for a nil blob (Q25), so the importer needs a third arm and restates Q24's undecodable-bytes arm beside it. Stated in the source comment.

The recency gate is unchanged.

The report names and rejects moving the guard into the gate: the gate answers eligibility (cloudkit-mirroring Decisions 2 and 8, never regress a newer local record); the guards answer which columns still differ. Also rejected: skipping the upsert when the whole record equals the local one — partial matches would still need per-field guards.

Shared ChangeRecordingSaveStrategy file rather than folding into InstrumentedSaveStrategy.

Round one suggested a dirtySaves field on the shared failure injector. The author instead promoted the private double to its own file with a doc block saying why it is not the injector ("did the save run" vs "did it have anything to write"). Consistent with the ~20 single-purpose doubles in the test directory; reasonable.

Decision 4 amended in place, no new Quick Decision row.

A dated note inside empty-library Decision 4 records that T-2334 restored the assertion; status stays accepted because the decision (assert stored state, hand the guard to T-2334) was carried out, not reversed. No bugfix folder carries a decision log, so the report's Alternatives section is the convention for the fix itself.

(inferred — not stated by the author.)

Review findings

SeverityAreaFindingResolution
minorBackupImportRecords.swift:246 (facts guard)`if row.facts != record.facts` compares through RecordRow.facts, whose RecordFactCodec.decode returns [] for undecodable bytes. A row holding broken fact bytes against an archive record with no facts now compares equal and is skipped; the old unconditional write set factsData = nil and cleared it. This is the trap the branch's own citation test pins, applied inconsistently to the other blob column. No validator diagnosis or requirement promises this heal, so it is a consistency point, not a broken contract. Three of four agents raised it independently.Not applied (review asked not to modify the branch). Suggested: `let encoded = RecordFactCodec.encode(record.facts); if row.factsData != encoded { row.factsData = encoded }` — encode is canonical (sorted keys, canonicalOrder, Q75), matches DuplicateReconciler.convergeRecordGroups's byte guard at DuplicateReconciler.swift:325, heals broken bytes and costs an encode instead of a decode-plus-sort. Trade-off: a blob written in a non-canonical layout is rewritten once. Either way, name the choice in the comment and the report.
minorLibraryRepository+ConfirmImport.swift:1190; BackupV15ArchiveTests.swift test doc; report.md Regression Test paragraph"the row Req 1.8 promises a restore heals" cites work-thumbnails Req 1.8, which is about a cover whose digest and bytes disagree (the pre-existing comment at :1069 cites it correctly for applyThumbnail). No requirement promises a restore heals undecodable citation bytes; the sources are drop-superseded-columns Q24 (editCitations repairs bytes that will not decode) and Q25 (a nil blob is a report and the archive import is one of its repairs). The nil-blob arm's "the validator and the diagnosis both promise" is Q25's claim.Not applied. Replace "Req 1.8" with Q24 in the undecodable arm and cite Q25 for the nil-blob arm, in the source comment, the test doc comment and the report.
minorspecs/empty-library/decision_log.md:177 (Decision 4 note)The note says "the negative consequence below no longer applies", but Decision 4 lists two negatives. The first ("still dirties and re-exports every row until T-2334 lands") is discharged; the second ("Req 5.1 is weaker than the owner approved; the owner should confirm the amendment") still stands because the clause was not put back into the requirement text.Not applied. Say "the first negative consequence below".
minorspecs/empty-library/requirements.md:84 (Req 5.1) and implementation.md:125Req 5.1 still disclaims the clean-save property ("is T-2334's, not this feature's") while aSecondImportOfTheArchiveDirtiesNothing now asserts it — the mirror of the case Decision 4 rejected (a requirement nothing checks). implementation.md keeps the item under "Partially implemented" while its own text ends "Since restored".Not applied. Either restore the clause to 5.1 as a parenthetical ("and, since T-2334, leaves no pending changes") and adjust the note, or leave the text and accept a test stricter than its requirement; move the implementation.md item out of "Partially implemented".
minorspecs/bugfixes/reimport-dirties-every-row/report.md Verification and Reproduction"make test-core passes" cannot be confirmed on this host: the three pending-capture suites EPERM under the keychain condition (also on main). This review's run skipped them (2,754 passed). Reproduction step 3's "every row re-exported by the mirror" is inferred from hasChanges, not observed on a host — nothing mirrors on the host.Not applied. State the run shape the claim rests on, and mark the re-export as the inferred consequence of a dirty save. A full make test-core on an unlocked host is owed before the push.
nitLibraryRepository+ConfirmImport.swift:1067 (releaseDays)The guard goes through the canonicalising accessor, which compactMaps unknown raw days away, so ["monday","funday"] compares equal to an archive [monday] and the unknown value survives where the old write replaced the raw column. Arguably better (never regress a newer build's value; export refuses it by name, Req 8.3), but the comment beside it still says the restore "has to clear a local set the archive says is gone".Not applied. One sentence in the comment, or compare releaseDaysRaw against the canonical raw form if the old behaviour is wanted.
nitLibraryRepository+ConfirmImport.swift:1026"The recency gate above (record.modifiedAt >= group.modifiedAt)" — the gate is in the caller (commitWorks), not above in this static function.Not applied. "the caller's recency gate".
nitLibraryRepository+ConfirmImport.swift:680-681 (membership site guard)`let site = archivedSite ?? row.site; if row.site !== site` reads row.site even when it then compares it to itself.Not applied. `if let archivedSite, row.site !== archivedSite { row.site = archivedSite }` skips the read for the no-Site case and mirrors the work line beside it.
nitMatched-row import path unmeasuredThe entry loop now reads existing.site (never read there before) and existing.work; the membership loop reads row.site and row.work on every matched row. Targets are registered in the context so the to-one resolves without a store round trip, but both M4 import arms (importChunkSweep, backupImportOverACoveredLibrary) import into an empty store, so nothing measures the update path.Not applied. Say so in the report, or add one matched-import sample to the chunk sweep when it is next re-run.
nitEmptyLibraryTests.swift:489; report PreventionThe test display name still reads "changes no stored value" while the body now also asserts clean saves. The Prevention section could warn that an inout-taking assign helper would silently reintroduce the bug (@Model setters run under withMutation regardless of value).Not applied. Optional rename; one sentence in Prevention.
nitCLAUDE.md Sync > Conflicts"Import is upsert by UUID, never deletes, and never regresses a newer local record" could gain "and dirties nothing on a re-import of a matched archive (T-2334)" — now a property future importer changes must keep. Nothing in CLAUDE.md or docs/agent-notes is inaccurate as it stands.Not applied. Optional.

Tests

Source: local run at 2026-09-22T17:05:00+10:00 · snapshot 0c137a7f267022f898db9d9e5a98c1d30e5027a8

Baseline: none

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

Coverage scope: every test in the repository

Totals: 2970 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/LibraryRepository+ConfirmImport.swift17615287%
Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift3030100%
Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift1212100%
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift13499100%
Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift3716100%
Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift133100%
specs/bugfixes/reimport-dirties-every-row/report.md145—no coverage data
specs/empty-library/decision_log.md3—no coverage data
specs/empty-library/design.md1—no coverage data
specs/empty-library/implementation.md2—no coverage data
specs/empty-library/requirements.md1—no coverage data

Aggregate diff coverage: 93% (312 of 334 measurable added lines).

Overall coverage

Head 91.0% (96007 of 105506 lines)

6 of 11 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/LibraryRepository+ConfirmImport.swift Modified +176 / -75
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swiftindex bfba187d..8c2ab8aa 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift@@ -385,6 +385,8 @@ extension LibraryRepository {             normalising: entryRows.values.flatMap { $0 }, context: context)         for chunk in chunks(of: payload.entries, size: batchSize) {             for record in chunk {+                let site = sitesByHostname[record.hostname]+                let work = record.workID.flatMap { workTargets[$0] }                 if let rows = entryRows[record.id], !rows.isEmpty {                     // Import is a bulk path with the whole store in `entryRows`, so the                     // normalisation is derived once for it above rather than per record.@@ -399,14 +401,17 @@ extension LibraryRepository {                     guard record.modifiedAt >= group.modifiedAt else { continue }                     for existing in group.rows {                         apply(record, to: existing)-                        existing.site = sitesByHostname[record.hostname]-                        existing.work = record.workID.flatMap { workTargets[$0] }+                        // Value-guarded (T-2334): assigning the same Site/Work+                        // reference back still dirties a SwiftData relationship,+                        // so compare by identity before writing.+                        if existing.site !== site { existing.site = site }+                        if existing.work !== work { existing.work = work }                     }                 } else {                     let entry = ArchiveRecordBuilders.makeEntry(record)                     context.insert(entry)-                    entry.site = sitesByHostname[record.hostname]-                    entry.work = record.workID.flatMap { workTargets[$0] }+                    entry.site = site+                    entry.work = work                     entryRows[record.id] = [entry]                 }             }@@ -665,16 +670,21 @@ extension LibraryRepository {                     appliedWorkIDs: appliedWorkIDs)                 else { continue }                 let target = record.workID.flatMap { workTargets[$0] }+                let archivedSite = sitesByHostname[record.hostname]                 if let rows = rowsByID[record.id], !rows.isEmpty {                     for row in rows {                         apply(record, to: row)-                        row.site = sitesByHostname[record.hostname] ?? row.site-                        if let target { row.work = target }+                        // Value-guarded (T-2334): assigning the same Site/Work+                        // reference back still dirties a SwiftData relationship,+                        // so compare by identity before writing.+                        let site = archivedSite ?? row.site+                        if row.site !== site { row.site = site }+                        if let target, row.work !== target { row.work = target }                     }                     if let workID = record.workID { touched.insert(workID) }                 } else {                     let row = ArchiveRecordBuilders.makeMembership(-                        record, work: target, site: sitesByHostname[record.hostname])+                        record, work: target, site: archivedSite)                     context.insert(row)                     rowsByID[record.id] = [row]                     if let workID = record.workID { touched.insert(workID) }@@ -837,10 +847,14 @@ extension LibraryRepository {             for record in chunk {                 if let rows = rowsByID[record.id], !rows.isEmpty {                     for row in rows where record.modifiedAt >= row.modifiedAt {-                        row.name = record.name-                        row.notes = record.notes-                        row.createdAt = record.createdAt-                        row.modifiedAt = record.modifiedAt+                        // Value-guarded (T-2334): a re-import at the same+                        // `modifiedAt` must write nothing.+                        if row.name != record.name { row.name = record.name }+                        if row.notes != record.notes { row.notes = record.notes }+                        if row.createdAt != record.createdAt { row.createdAt = record.createdAt }+                        if row.modifiedAt != record.modifiedAt {+                            row.modifiedAt = record.modifiedAt+                        }                     }                 } else {                     let row = ArchiveRecordBuilders.makeSeries(record)@@ -874,11 +888,19 @@ extension LibraryRepository {             for record in chunk {                 if let rows = rowsByID[record.id], !rows.isEmpty {                     for row in rows where record.modifiedAt >= row.modifiedAt {-                        row.lowerWorkID = record.lowerWorkID-                        row.higherWorkID = record.higherWorkID-                        row.linkType = record.linkType-                        row.createdAt = record.createdAt-                        row.modifiedAt = record.modifiedAt+                        // Value-guarded (T-2334): a re-import at the same+                        // `modifiedAt` must write nothing.+                        if row.lowerWorkID != record.lowerWorkID {+                            row.lowerWorkID = record.lowerWorkID+                        }+                        if row.higherWorkID != record.higherWorkID {+                            row.higherWorkID = record.higherWorkID+                        }+                        if row.linkType != record.linkType { row.linkType = record.linkType }+                        if row.createdAt != record.createdAt { row.createdAt = record.createdAt }+                        if row.modifiedAt != record.modifiedAt {+                            row.modifiedAt = record.modifiedAt+                        }                     }                 } else {                     let row = ArchiveRecordBuilders.makeLink(record)@@ -927,15 +949,19 @@ extension LibraryRepository {                 let record = record.normalized                 if let rows = rowsByID[record.id], !rows.isEmpty {                     for row in rows where record.modifiedAt >= row.modifiedAt {-                        row.workID = record.workID-                        row.creatorID = record.creatorID-                        row.createdAt = record.createdAt+                        // Value-guarded (T-2334): a re-import at the same+                        // `modifiedAt` must write nothing.+                        if row.workID != record.workID { row.workID = record.workID }+                        if row.creatorID != record.creatorID { row.creatorID = record.creatorID }+                        if row.createdAt != record.createdAt { row.createdAt = record.createdAt }                         if record.modifiedAt > row.modifiedAt                             || Set(record.roleIDs).isSuperset(of: row.roleIDs)                         {-                            row.roleIDs = record.roleIDs+                            if row.roleIDs != record.roleIDs { row.roleIDs = record.roleIDs }+                        }+                        if row.modifiedAt != record.modifiedAt {+                            row.modifiedAt = record.modifiedAt                         }-                        row.modifiedAt = record.modifiedAt                     }                 } else {                     let row = ArchiveRecordBuilders.makeCredit(record)@@ -964,9 +990,17 @@ extension LibraryRepository {             for record in chunk {                 if let rows = rowsByID[record.id], !rows.isEmpty {                     for row in rows where record.recordedAt >= row.recordedAt {-                        row.lowerWorkID = record.lowerWorkID-                        row.higherWorkID = record.higherWorkID-                        row.recordedAt = record.recordedAt+                        // Value-guarded (T-2334): a re-import at the same+                        // `recordedAt` must write nothing.+                        if row.lowerWorkID != record.lowerWorkID {+                            row.lowerWorkID = record.lowerWorkID+                        }+                        if row.higherWorkID != record.higherWorkID {+                            row.higherWorkID = record.higherWorkID+                        }+                        if row.recordedAt != record.recordedAt {+                            row.recordedAt = record.recordedAt+                        }                     }                 } else {                     let row = ArchiveRecordBuilders.makeDistinctPair(record)@@ -986,17 +1020,30 @@ extension LibraryRepository {     internal static func apply(         _ record: BackupV15Work, to work: Work, thumbnail: ArchiveThumbnail     ) {-        work.displayTitle = record.displayTitle-        work.lastParsedTitle = record.lastParsedTitle-        work.genericNotes = record.genericNotes-        work.genreTags = record.genreTags-        work.titleProvenanceRaw = record.titleProvenance.rawValue+        // Every scalar below is value-guarded (T-2334): re-importing an archive+        // the library already matches must write nothing, so a re-export mirrors+        // no unchanged row through CloudKit. The recency gate above (`record.+        // modifiedAt >= group.modifiedAt`) already decided *whether* this record+        // writes; this only decides which of its columns still differ.+        if work.displayTitle != record.displayTitle { work.displayTitle = record.displayTitle }+        if work.lastParsedTitle != record.lastParsedTitle {+            work.lastParsedTitle = record.lastParsedTitle+        }+        if work.genericNotes != record.genericNotes { work.genericNotes = record.genericNotes }+        if work.genreTags != record.genreTags { work.genreTags = record.genreTags }+        if work.titleProvenanceRaw != record.titleProvenance.rawValue {+            work.titleProvenanceRaw = record.titleProvenance.rawValue+        }         // Req 8.1 and 2.6: the record's three, written raw like the provenance         // beside them. A work materialised from an archive carries what the         // file says; the column defaults only stand where no record reaches it.-        work.workStatusRaw = record.workStatus.rawValue-        work.readingStatusRaw = record.readingStatus.rawValue-        work.verdict = record.verdict+        if work.workStatusRaw != record.workStatus.rawValue {+            work.workStatusRaw = record.workStatus.rawValue+        }+        if work.readingStatusRaw != record.readingStatus.rawValue {+            work.readingStatusRaw = record.readingStatus.rawValue+        }+        if work.verdict != record.verdict { work.verdict = record.verdict }         // Q36's deferral, landing with the record that carries it: the         // membership pair is authored content on the Work row         // (`series-and-related-works` Req 13.1), so an archive that carries it@@ -1004,20 +1051,26 @@ extension LibraryRepository {         // record cannot hold half a pair, because both doors refuse one         // (Req 13.5) — so a work the reader took out of a series before the         // export is restored out of it rather than left in the library's.-        work.seriesID = record.seriesID-        work.seriesPosition = record.seriesPosition+        if work.seriesID != record.seriesID { work.seriesID = record.seriesID }+        if work.seriesPosition != record.seriesPosition {+            work.seriesPosition = record.seriesPosition+        }         // `update-schedule` Req 8.1: the record's set, written through the         // accessor so the column lands canonical whatever order the file spelled-        // it in. Required on the wire and written every time — an empty set in-        // the archive is a work the reader gave no days, and restoring it has to-        // clear a local set the archive says is gone, exactly as the statuses-        // are restored over local ones. The record has already passed the-        // never-regress guard above, so this is the newer state of this work.-        work.releaseDays = record.releaseDays-        // V14 (Req 8.1, 8.4, Q71). All three columns every time, and the digest-        // **re-derived** from the archived bytes rather than carried in the-        // file: that is what makes a restore heal Req 1.8's tolerated row, where-        // the stored digest and the stored blob had stopped agreeing.+        // it in. Required on the wire and written every time it actually differs+        // — an empty set in the archive is a work the reader gave no days, and+        // restoring it has to clear a local set the archive says is gone,+        // exactly as the statuses are restored over local ones. The record has+        // already passed the never-regress guard above, so this is the newer+        // state of this work.+        if work.releaseDays != record.releaseDays { work.releaseDays = record.releaseDays }+        // V14 (Req 8.1, 8.4, Q71). All three columns where they differ, and the+        // digest **re-derived** from the archived bytes rather than carried in+        // the file: that is what makes a restore heal Req 1.8's tolerated row,+        // where the stored digest and the stored blob had stopped agreeing.+        // `applyThumbnail` carries its own value guard already (Req 1.11's+        // argument), because rewriting the cover costs a sidecar file and a+        // CloudKit asset upload, not just a column.         //         // `.dropped` clears exactly as `.none` does. On the update path the         // record has already passed the modification guard above, so it is the@@ -1026,8 +1079,8 @@ extension LibraryRepository {         // insert path there is nothing to clear. Either way the work is imported         // and its title is named in the report.         applyThumbnail(thumbnail, to: work)-        work.createdAt = record.createdAt-        work.modifiedAt = record.modifiedAt+        if work.createdAt != record.createdAt { work.createdAt = record.createdAt }+        if work.modifiedAt != record.modifiedAt { work.modifiedAt = record.modifiedAt }         WorkTypeWriter.apply(record.assignment, to: work)     } @@ -1035,8 +1088,8 @@ extension LibraryRepository {     /// they differ** (Req 1.11's argument, applied to import).     ///     /// Every other field of `apply` is a scalar whose rewrite costs a column,-    /// and the value guards this project normally relies on are the reconcilers'-    /// rather than the importer's. The cover is not a scalar: assigning+    /// and since T-2334 each of them carries a value guard of its own. The cover+    /// was guarded first because it is not a scalar: assigning     /// `thumbnailData` rewrites an external-storage sidecar on disk and     /// re-uploads a CloudKit asset, so re-importing the archive a reader just     /// exported would push every cover in their library through the mirror@@ -1068,37 +1121,80 @@ extension LibraryRepository {     /// `createdAt` are set at construction, so what an update moves is the     /// site-specific content: the URL identity triple and the confirmed Work URL.     internal static func apply(_ record: BackupV15Membership, to membership: WorkSiteMembership) {-        membership.hostname = record.hostname-        membership.createdAt = record.createdAt-        membership.urlIdentity = record.urlIdentity-        membership.urlIdentityState = record.urlIdentityState-        membership.urlIdentityRuleID = record.urlIdentityRuleID-        membership.workURLString = record.workURLString-        membership.workID = record.workID ?? membership.workID+        // Value-guarded (T-2334): a re-import of a record the row already+        // matches must write nothing.+        if membership.hostname != record.hostname { membership.hostname = record.hostname }+        if membership.createdAt != record.createdAt { membership.createdAt = record.createdAt }+        if membership.urlIdentity != record.urlIdentity {+            membership.urlIdentity = record.urlIdentity+        }+        if membership.urlIdentityState != record.urlIdentityState {+            membership.urlIdentityState = record.urlIdentityState+        }+        if membership.urlIdentityRuleID != record.urlIdentityRuleID {+            membership.urlIdentityRuleID = record.urlIdentityRuleID+        }+        if membership.workURLString != record.workURLString {+            membership.workURLString = record.workURLString+        }+        let workID = record.workID ?? membership.workID+        if membership.workID != workID { membership.workID = workID }     }      internal static func apply(_ record: BackupV15Entry, to entry: Entry) {-        entry.captureTitle = record.captureTitle-        entry.captureTitleSourceRaw = record.captureTitleSource.rawValue-        entry.rawURLString = record.rawURL-        entry.canonicalURLString = record.canonicalURL-        entry.hostname = record.hostname-        entry.entryIdentityKey = record.entryIdentityKey-        entry.conservativeIdentityKey = record.conservativeIdentityKey-        entry.identityBasisRaw = record.identityBasis.rawValue-        entry.urlWorkIdentity = record.urlWorkIdentity-        entry.chapterSequence = record.chapterSequence-        entry.chapterTitle = record.chapterTitle-        entry.note = record.note-        entry.ratingRaw = record.rating?.rawValue-        entry.firstCapturedAt = record.firstCapturedAt-        entry.lastSharedAt = record.lastSharedAt-        entry.modifiedAt = record.modifiedAt-        entry.intentionallyUnattached = record.intentionallyUnattached+        // Value-guarded (T-2334): a re-import of a record the row already+        // matches must write nothing.+        if entry.captureTitle != record.captureTitle { entry.captureTitle = record.captureTitle }+        if entry.captureTitleSourceRaw != record.captureTitleSource.rawValue {+            entry.captureTitleSourceRaw = record.captureTitleSource.rawValue+        }+        if entry.rawURLString != record.rawURL { entry.rawURLString = record.rawURL }+        if entry.canonicalURLString != record.canonicalURL {+            entry.canonicalURLString = record.canonicalURL+        }+        if entry.hostname != record.hostname { entry.hostname = record.hostname }+        if entry.entryIdentityKey != record.entryIdentityKey {+            entry.entryIdentityKey = record.entryIdentityKey+        }+        if entry.conservativeIdentityKey != record.conservativeIdentityKey {+            entry.conservativeIdentityKey = record.conservativeIdentityKey+        }+        if entry.identityBasisRaw != record.identityBasis.rawValue {+            entry.identityBasisRaw = record.identityBasis.rawValue+        }+        if entry.urlWorkIdentity != record.urlWorkIdentity {+            entry.urlWorkIdentity = record.urlWorkIdentity+        }+        if entry.chapterSequence != record.chapterSequence {+            entry.chapterSequence = record.chapterSequence+        }+        if entry.chapterTitle != record.chapterTitle { entry.chapterTitle = record.chapterTitle }+        if entry.note != record.note { entry.note = record.note }+        if entry.ratingRaw != record.rating?.rawValue { entry.ratingRaw = record.rating?.rawValue }+        if entry.firstCapturedAt != record.firstCapturedAt {+            entry.firstCapturedAt = record.firstCapturedAt+        }+        if entry.lastSharedAt != record.lastSharedAt { entry.lastSharedAt = record.lastSharedAt }+        if entry.modifiedAt != record.modifiedAt { entry.modifiedAt = record.modifiedAt }+        if entry.intentionallyUnattached != record.intentionallyUnattached {+            entry.intentionallyUnattached = record.intentionallyUnattached+        }         // An archive record carries the citations as one blob (Q25) and the store has         // exactly one home for them, so the record's value is written straight-        // in. This is a **whole-value** write, not an edit: the record replaces-        // everything the row cited, bytes that would not decode included.+        // in wherever it differs. This is a **whole-value** write, not an edit:+        // where it writes at all, the record replaces everything the row cited,+        // bytes that would not decode included.+        //+        // Three arms. Bytes that are present but will not decode+        // (`decodedCitations == nil` below) always write, because that is the+        // row Req 1.8 promises a restore heals. Bytes that decode write only+        // where they disagree with the archive. And **no bytes at all** always+        // write: `citations` reads a nil blob as the default, so a pre-V9 row+        // against an archive carrying the default would otherwise never be+        // converted, while the validator and the diagnosis both promise that+        // the archive repairs it. The first two arms are `editCitations`'s, but+        // it leaves a nil blob nil on a no-op edit by design (Q23), which is+        // why it is not the door here.         //         // Swallowed deliberately, and this function stays non-throwing: the         // value being encoded came out of `JSONDecoder` moments ago as the same@@ -1107,6 +1203,11 @@ extension LibraryRepository {         // Making the whole record-application path throwing to carry an error         // that cannot arise would put a `try` on every sibling `apply` for         // nothing.-        try? entry.setCitations(record.citations)+        let decodedCitations = try? entry.citations+        if entry.citationsAreAbsent || decodedCitations == nil+            || decodedCitations != record.citations+        {+            try? entry.setCitations(record.citations)+        }     } }
Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift Modified +30 / -16
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swiftindex 3e8df06c..ebee867d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift@@ -211,14 +211,20 @@ extension LibraryRepository {             guard let fingerprint = record.genericNotesExtractionFingerprint else { continue }             for row in workRows[record.id] ?? []             where CharacterCoverageFingerprint.of(row.genericNotes) == fingerprint {-                row.genericNotesExtractionFingerprint = fingerprint+                // Value-guarded (T-2334): re-importing an archive that already+                // covers this text must write nothing.+                if row.genericNotesExtractionFingerprint != fingerprint {+                    row.genericNotesExtractionFingerprint = fingerprint+                }             }         }         for record in payload.entries {             guard let fingerprint = record.characterExtractionFingerprint else { continue }             for row in entryRows[record.id] ?? []             where CharacterCoverageFingerprint.of(row.note) == fingerprint {-                row.characterExtractionFingerprint = fingerprint+                if row.characterExtractionFingerprint != fingerprint {+                    row.characterExtractionFingerprint = fingerprint+                }             }         }     }@@ -232,24 +238,32 @@ extension LibraryRepository {     /// is `attach(to:archivedWorkID:)`'s, which the two tables answer     /// differently (Q60).     internal static func apply<Row: RecordRow>(_ record: some ArchivedRecord, to row: Row) {-        row.name = record.name-        row.nameKey = record.nameKey-        row.aliases = record.aliases-        row.note = record.note-        row.facts = record.facts-        row.createdAt = record.createdAt-        row.modifiedAt = record.modifiedAt+        // Value-guarded (T-2334): a re-import at the same `modifiedAt` must+        // write nothing, so a matched library re-exports nothing through the+        // mirror.+        if row.name != record.name { row.name = record.name }+        if row.nameKey != record.nameKey { row.nameKey = record.nameKey }+        if row.aliases != record.aliases { row.aliases = record.aliases }+        if row.note != record.note { row.note = record.note }+        if row.facts != record.facts { row.facts = record.facts }+        if row.createdAt != record.createdAt { row.createdAt = record.createdAt }+        if row.modifiedAt != record.modifiedAt { row.modifiedAt = record.modifiedAt }     }      internal static func apply<Row: SuppressionRow>(         _ record: some ArchivedSuppression, to row: Row     ) {-        row.kindRaw = record.kindRaw-        row.nameKey = record.nameKey-        row.sourceKindRaw = record.sourceKindRaw-        row.sourceEntryID = record.sourceEntryID-        row.evidence = record.evidence-        row.statusRaw = record.statusRaw-        row.actionAt = record.actionAt+        // Value-guarded (T-2334), for the reason above.+        if row.kindRaw != record.kindRaw { row.kindRaw = record.kindRaw }+        if row.nameKey != record.nameKey { row.nameKey = record.nameKey }+        if row.sourceKindRaw != record.sourceKindRaw {+            row.sourceKindRaw = record.sourceKindRaw+        }+        if row.sourceEntryID != record.sourceEntryID {+            row.sourceEntryID = record.sourceEntryID+        }+        if row.evidence != record.evidence { row.evidence = record.evidence }+        if row.statusRaw != record.statusRaw { row.statusRaw = record.statusRaw }+        if row.actionAt != record.actionAt { row.actionAt = record.actionAt }     } }
Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift Modified +12 / -4
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swiftindex 6e6f90d0..40da0882 100644--- a/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift@@ -207,6 +207,9 @@ extension CharacterRecord: RecordRow {     /// is not a relationship.     public func attach(to work: Work?, archivedWorkID: UUID?, workTargets: [UUID: Work]) {         guard let work else { return }+        // Value-guarded (T-2334): assigning the same Work reference back still+        // dirties a SwiftData relationship, so compare by identity first.+        guard self.work !== work else { return }         self.work = work     } }@@ -244,6 +247,8 @@ extension CharacterSuppression: SuppressionRow {     /// resolution map say nothing this table can use.     public func attach(to work: Work?, archivedWorkID: UUID?, workTargets: [UUID: Work]) {         guard let work else { return }+        // Value-guarded (T-2334), for `CharacterRecord.attach`'s reason.+        guard self.work !== work else { return }         self.work = work     } }@@ -309,10 +314,12 @@ extension Place: RecordRow {     /// orphan of Req 5.5, which the codec admits by design — would move a local     /// P off its work and make it invisible everywhere.     public func attach(to work: Work?, archivedWorkID: UUID?, workTargets: [UUID: Work]) {+        // Value-guarded (T-2334): each arm writes only where the resolved+        // value actually differs from the column's current one.         if let work {-            workID = work.id+            if workID != work.id { workID = work.id }         } else if let archivedWorkID, workTargets[workID] == nil {-            workID = archivedWorkID+            if workID != archivedWorkID { workID = archivedWorkID }         }     } }@@ -360,10 +367,11 @@ extension PlaceSuppression: SuppressionRow {     /// empty map answers "nothing resolves" for a row that has no owner yet, so     /// the orphan round trip is unchanged.     public func attach(to work: Work?, archivedWorkID: UUID?, workTargets: [UUID: Work]) {+        // Value-guarded (T-2334), for `Place.attach`'s reason.         if let work {-            workID = work.id+            if workID != work.id { workID = work.id }         } else if let archivedWorkID, workTargets[workID] == nil {-            workID = archivedWorkID+            if workID != archivedWorkID { workID = archivedWorkID }         }     } }
Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift Modified +134 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swiftindex a96e5bbc..e73d0453 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift@@ -3822,6 +3822,140 @@ struct BackupV15ImportTests {         #expect(restored.readingStatus == .toRead)         #expect(restored.entries.count == 1)     }++    // MARK: - T-2334: a no-op re-import dirties nothing++    /// The bug T-2334 tracks: the upsert's `apply` functions wrote every+    /// scalar column unconditionally, so a second import of an archive the+    /// library already matches reported pending changes at every save while+    /// writing back identical values — dirtying every row of a re-imported+    /// archive and, under mirroring, re-exporting every one of them for+    /// nothing.+    ///+    /// Driven over `BackupGoldenLibrary.payload`, which carries one record of+    /// every kind the 15/16 payload holds — Sites and rules, Works, Entries,+    /// memberships, series, links, creators, creator roles and credits, plus+    /// characters, places and their suppressions — so the guard is exercised+    /// on every table the upsert writes, not just the ones a narrower fixture+    /// happens to cover.+    ///+    /// `hasChanges` is read immediately **before** each armed save, since+    /// `ModelContext.save()` clears whatever it reports; a context that goes+    /// into a save already clean is one the second import wrote nothing into.+    @Test("A second import of an unchanged archive dirties no save")+    func aSecondImportOfAnUnchangedArchiveDirtiesNoSave() async throws {+        let strategy = ChangeRecordingSaveStrategy()+        let fixture = try await M5Fixture(saveStrategy: strategy)+        let payload = BackupGoldenLibrary.payload++        try await fixture.repository.confirmImport(plan: BackupV15Fixtures.plan(payload))+        let firstImport = try await fixture.repository.backupV15Snapshot()++        strategy.arm()+        try await fixture.repository.confirmImport(plan: BackupV15Fixtures.plan(payload))++        #expect(strategy.saves > 0, "the second import must have reached its saves")+        #expect(+            strategy.dirtySaves.allSatisfy { !$0 },+            "a second import of an unchanged archive must dirty no save, got \(strategy.dirtySaves)")+        #expect(try await fixture.repository.backupV15Snapshot() == firstImport)+    }++    /// The citation arm of the guard above, in one context so the store itself+    /// answers, on the cover test's shape. Four states: a blob that decodes to+    /// what the archive carries dirties nothing; bytes that will not decode are+    /// **rewritten** — the reason the guard is a decode-and-compare rather than+    /// a byte comparison, and the row Req 1.8 promises a restore heals; a+    /// **nil** blob is converted even against an archive carrying the default,+    /// because `citations` reads it as the default and the validator promises+    /// the archive repairs it; and bytes that decode to something *different*+    /// are written, so the guard's `!=` cannot be flipped without a test+    /// noticing. Each arm is pinned here rather than traced through+    /// `editCitations` by hand, because the third is exactly where the two+    /// differ (Q23).+    @Test("Re-applying the same archive citations writes nothing; undecodable and absent blobs heal")+    func reapplyingTheSameCitationsWritesNothing() throws {+        let schema = Schema(versionedSchema: AsterismSchemaV16.self)+        let container = try ModelContainer(+            for: schema,+            configurations: [+                ModelConfiguration(+                    schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+            ])+        let context = ModelContext(container)+        context.autosaveEnabled = false+        let record = try #require(BackupV15Fixtures.minimalTaughtPayload().entries.first)+        #expect(record.citations != EntryCitations(), "the arm needs a non-default value to compare")+        let entry = ArchiveRecordBuilders.makeEntry(record)+        context.insert(entry)+        try context.save()+        #expect(try entry.citations == record.citations)++        LibraryRepository.apply(record, to: entry)+        #expect(!context.hasChanges, "a second import of the same citations must write nothing")++        // Req 1.8's tolerated row: bytes are present and will not decode. The+        // restore is what heals it, so this one *must* write.+        entry.citationsData = Data("not json".utf8)+        try context.save()+        LibraryRepository.apply(record, to: entry)+        #expect(context.hasChanges, "a restore must heal a row whose citations will not decode")+        #expect(try entry.citations == record.citations)+        try context.save()++        // The same row against an archive carrying the *default* citations: a+        // guard written over the tolerant read (`citationValues`, which reads+        // undecodable bytes as the default) would see no difference and skip+        // the heal. This is the arm that pins the decode-and-compare.+        let defaulted = BackupV15Entry(+            id: record.id, captureTitle: record.captureTitle,+            captureTitleSource: record.captureTitleSource, rawURL: record.rawURL,+            canonicalURL: record.canonicalURL, hostname: record.hostname,+            entryIdentityKey: record.entryIdentityKey,+            conservativeIdentityKey: record.conservativeIdentityKey,+            identityBasis: record.identityBasis, urlWorkIdentity: record.urlWorkIdentity,+            chapterSequence: record.chapterSequence, chapterTitle: record.chapterTitle,+            note: record.note, rating: record.rating, firstCapturedAt: record.firstCapturedAt,+            lastSharedAt: record.lastSharedAt, modifiedAt: record.modifiedAt,+            workID: record.workID, intentionallyUnattached: record.intentionallyUnattached,+            citations: EntryCitations(),+            characterExtractionFingerprint: record.characterExtractionFingerprint)+        entry.citationsData = Data("not json".utf8)+        try context.save()+        LibraryRepository.apply(defaulted, to: entry)+        #expect(+            context.hasChanges,+            "undecodable bytes must be rewritten even where the archive carries the default")+        #expect(try entry.citations == EntryCitations())+        try context.save()++        // No bytes at all — a pre-V9 row the drop stage reached before anything+        // converted it — against that same defaulted archive. `citations` reads+        // a nil blob as the default, so a guard over the decoded value alone+        // sees nothing to write; the archive is what the validator and the+        // diagnosis promise repairs the row, so this arm *must* leave bytes+        // behind. Once it has, a second pass is a no-op like any other.+        entry.citationsData = nil+        try context.save()+        #expect(entry.citationsAreAbsent)+        LibraryRepository.apply(defaulted, to: entry)+        #expect(+            context.hasChanges,+            "a nil blob must be converted even where the archive carries the default")+        #expect(!entry.citationsAreAbsent)+        #expect(try entry.citations == EntryCitations())+        try context.save()+        LibraryRepository.apply(defaulted, to: entry)+        #expect(!context.hasChanges, "a converted blob re-imported against the same archive writes nothing")++        // Decodable bytes that differ from the archive: the plain arm of the+        // comparison. Every arm above would still pass on a guard that only+        // ever wrote over broken or absent bytes.+        #expect(try entry.citations != record.citations)+        LibraryRepository.apply(record, to: entry)+        #expect(context.hasChanges, "citations that decode and differ from the archive must be written")+        #expect(try entry.citations == record.citations)+    } }  // MARK: - Test Doubles
Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift Added +37 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swiftnew file mode 100644index 00000000..64ca1d46--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift@@ -0,0 +1,37 @@+import Foundation+import SwiftData+@testable import AsterismCore++/// Counts the saves a pass makes once it is armed, so "the second import+/// reached its commit path" is a fact rather than an assumption — and records+/// whether the context carried pending changes at each of those saves, which+/// is what T-2334's value guards are for: a save entered with `hasChanges ==+/// true` before it runs is a save that is about to write something, even if+/// what it writes happens to equal what was already there.+///+/// Shared by `EmptyLibraryTests` and `BackupV15ImportTests`, which ask the+/// same question of two fixtures. `InstrumentedSaveStrategy` is the failure+/// injector and deliberately not this: it answers "did the save run", never+/// "did it have anything to write".+final class ChangeRecordingSaveStrategy: RepositorySaveStrategy, @unchecked Sendable {+    private let lock = NSLock()+    private var armed = false+    private var _saves = 0+    private var _dirtySaves: [Bool] = []++    func arm() { lock.withLock { armed = true; _saves = 0; _dirtySaves = [] } }+    var saves: Int { lock.withLock { _saves } }+    /// `hasChanges` as observed immediately before each armed save. Read after+    /// the pass completes, since `context.save()` clears the flag it reports.+    var dirtySaves: [Bool] { lock.withLock { _dirtySaves } }++    func save(_ context: ModelContext) throws {+        lock.withLock {+            if armed {+                _saves += 1+                _dirtySaves.append(context.hasChanges)+            }+        }+        try context.save()+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift Modified +13 / -26
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swiftindex 5529ba92..a9706310 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift@@ -475,18 +475,17 @@ struct EmptyLibraryTests {     }      /// Q15's second half: a second import of the same archive changes no stored-    /// value and moves no modification timestamp.+    /// value and moves no modification timestamp — asserted both as the stored+    /// result and, now that T-2334 has value-guarded the importer, as+    /// `hasChanges` at each save.     ///-    /// **Asserted as the library before and after, not as `hasChanges` at each-    /// save.** The design's testing table asks for the second form; the-    /// importer's `apply` deliberately writes every scalar column unconditionally-    /// (see `applyThumbnail`'s own note — the value guards this project relies on-    /// are the reconcilers', and only the cover is guarded, because only the-    /// cover's rewrite costs a file and an asset upload). So every one of the-    /// second import's nine saves reports pending changes while writing back the-    /// values that are already there. What Req 5.1 is a promise about is the-    /// *stored* result, and the whole payload — every column of every record —-    /// is a strictly stronger statement of it than a count of dirty saves.+    /// The stored-result half is the whole payload — every column of every+    /// record — which is a strictly stronger statement than a count of dirty+    /// saves on its own; the `hasChanges` half is what Req 5.1 originally asked+    /// for and Decision 4 dropped, pending the importer's own fix. T-2334+    /// value-guards every scalar `apply` writes in+    /// `LibraryRepository+ConfirmImport.swift`, so this is that assertion,+    /// restored.     @Test("A second import of the same archive changes no stored value")     func aSecondImportOfTheArchiveDirtiesNothing() async throws {         let strategy = ChangeRecordingSaveStrategy()@@ -503,6 +502,9 @@ struct EmptyLibraryTests {         try await fixture.repository.confirmImport(plan: EmptyLibraryFixture.plan(archive))          #expect(strategy.saves > 0, "the second import must have reached its saves")+        #expect(+            strategy.dirtySaves.allSatisfy { !$0 },+            "a second import of an unchanged archive must dirty no save, got \(strategy.dirtySaves)")         #expect(try await fixture.repository.backupV15Snapshot() == restored)         #expect(try await fixture.repository.modificationStampsForTesting() == stamps)         await fixture.tearDown()@@ -756,21 +758,6 @@ private final class ShutdownAfterSweepsSaveStrategy: RepositorySaveStrategy, @un     } } -/// Counts the saves a pass makes once it is armed, so "the second import-/// reached its commit path" is a fact rather than an assumption.-private final class ChangeRecordingSaveStrategy: RepositorySaveStrategy, @unchecked Sendable {-    private let lock = NSLock()-    private var armed = false-    private var _saves = 0--    func arm() { lock.withLock { armed = true; _saves = 0 } }-    var saves: Int { lock.withLock { _saves } }--    func save(_ context: ModelContext) throws {-        lock.withLock { if armed { _saves += 1 } }-        try context.save()-    }-}  // MARK: - The fixture 
specs/bugfixes/reimport-dirties-every-row/report.md Added +145 / -0
diff --git a/specs/bugfixes/reimport-dirties-every-row/report.md b/specs/bugfixes/reimport-dirties-every-row/report.mdnew file mode 100644index 00000000..efacb5d1--- /dev/null+++ b/specs/bugfixes/reimport-dirties-every-row/report.md@@ -0,0 +1,145 @@+# Bugfix Report: Re-importing an Unchanged Archive Dirties Every Row++**Date:** 2026-09-22+**Status:** Fixed+**Ticket:** T-2334++## Description of the Issue++A second import of an archive the library already matched reported pending+changes at every save while writing back identical values. No stored value and+no `modifiedAt` moved, but every row was dirtied, so a no-op re-import of a+large archive re-exported every record through the CloudKit mirror.++**Reproduction steps:**+1. Import an archive into a library.+2. Import the same archive again.+3. Observe `ModelContext.hasChanges == true` before every save of the second+   import, and every row re-exported by the mirror.++**Impact:** Sync traffic proportional to the library on every re-import, and a+violation of the Convergence rule in CLAUDE.md: a field is written only when it+differs, so the fixed point dirties nothing and exports nothing.++## Investigation Summary++- **Symptoms examined:** a counting save strategy over a second import of+  `BackupGoldenLibrary.payload` showed dirty saves.+- **Code inspected:** the `upsert` in `LibraryRepository+ConfirmImport.swift`,+  `BackupImportRecords.swift`, `RecordRow.swift`, and the import recency gate+  (`cloudkit-mirroring` Decisions 2 and 8).+- **Hypotheses tested:** guarding only `LibraryRepository+ConfirmImport.swift`+  left one dirty save, traced to the character and place record writers that+  `upsert` calls as its fourth step. The recency gate was confirmed to decide+  only *whether* a record's fields are eligible to write; it does not need to+  change.++## Discovered Root Cause++The import upsert's `apply(_:to:)` functions for `Work`, `WorkSiteMembership`+and `Entry`, the inline writes in the series, link, credit and distinct-pair+commits, and the record and suppression writers all assigned every column+unconditionally. `applyDesignation`, `applyThumbnail`, `WorkTypeWriter.apply`+and the two directory merges (`mergeImportedWorkTypes` through+`WorkTypeWriter.setState`, `mergeImportedCreatorDirectories` through the+`CreatorWriter` setters under strictly-later field stamps) were already+value-guarded, which is why the defect never showed on those tables.++**Defect type:** Missing value guards on writes.++**Why it occurred:** import was written before the Convergence rule made value+guards the standard for the reconcilers' writes, and as a reader action rather+than part of the silent path it was never brought under the same rule — even+though a matched library must leave a no-op re-import with nothing to export.+`empty-library` Decision 4 dropped the "no pending changes" clause from its+Req 5.1 for this reason and handed it to this ticket.++## Resolution for the Issue++**Changes made:**+- `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift`+  — every scalar write follows `if current != new { current = new }`; the+  citation blob is compared by decoded value so corrupt bytes still heal, and+  a nil blob is always written because `Entry.citations` reads it as the+  default and the archive is the promised repair for it; relationship+  assignments are guarded by reference identity.+- `Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift` — the+  record and suppression `apply` functions and the coverage-fingerprint writes.+- `Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift` — the four+  `attach` implementations, by reference identity for characters and by UUID+  column for places.++**Approach rationale:** the shape `applyDesignation`, `applyThumbnail` and+`WorkTypeWriter.apply` already use, applied to every remaining write on the+path.++**Alternatives considered:**+- Skip the upsert entirely when the incoming record equals the local one —+  rejected because partial matches would still need per-field guards, and a+  whole-record comparison duplicates the field list.+- Move the guard into the recency gate — rejected; the gate answers a+  different question (eligibility), and mixing them would change what a newer+  local record protects.++## Regression Test++**Test file:** `Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift`+**Test name:** `aSecondImportOfAnUnchangedArchiveDirtiesNoSave`++**What it verifies:** importing `BackupGoldenLibrary.payload` twice through a+`ChangeRecordingSaveStrategy` records `hasChanges == false` before every+save of the second import, and the stored archive is unchanged.++`EmptyLibraryTests.aSecondImportOfTheArchiveDirtiesNothing` restores the half+of `empty-library` Req 5.1 that Decision 4 dropped, over that spec's own golden+fixture.++`reapplyingTheSameCitationsWritesNothing` (same file, added at review) pins+the one guard that is not a plain comparison: re-applying citations the row+already holds dirties nothing; bytes that will not decode are rewritten,+including against an archive carrying the default value, the arm a guard+written over the tolerant read would silently skip (Req 1.8's heal); a nil+blob is converted against that same default archive, the arm the first+review round's guard had dropped, since `Entry.citations` reads a nil blob as+the default; and decodable bytes that differ are written, so the guard's `!=`+cannot be inverted unnoticed.++**Run command:** `make test-core`++## Affected Files++| File | Change |+|------|--------|+| `Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift` | value-guard every write in the upsert |+| `Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift` | value-guard record and suppression writes |+| `Packages/AsterismCore/Sources/AsterismCore/RecordRow.swift` | value-guard the four `attach` implementations |+| `Packages/AsterismCore/Tests/AsterismCoreTests/BackupV15ArchiveTests.swift` | regression tests |+| `Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift` | restored `hasChanges` assertion |+| `Packages/AsterismCore/Tests/AsterismCoreTests/ChangeRecordingSaveStrategy.swift` | the save-strategy double both tests share, moved out of `EmptyLibraryTests` |++## Verification++**Automated:**+- [x] Regression tests pass+- [x] `make test-core` passes+- [x] No linter is configured; no new compiler warnings in touched files++**Manual verification:**+- None needed; host-only store change.++## Prevention++- Every write on the silent path is value-guarded, and so is every write of+  the one reader action that replays a whole library. A new importer or+  reconciler should add a `hasChanges == false` assertion over a second pass+  of the same input from the start.+- Audited at review: `mergeImportedWorkTypes` and+  `mergeImportedCreatorDirectories` sit on the same path and were already+  value-guarded per field, which is why they never showed the defect. No+  ticket is owed for them.++## Related++- `specs/empty-library/decision_log.md` Decision 4+- `specs/cloudkit-mirroring/decision_log.md` Decisions 2 and 8+- PR #88
specs/empty-library/decision_log.md Modified +3 / -1
diff --git a/specs/empty-library/decision_log.md b/specs/empty-library/decision_log.mdindex f2318d3c..f26c3fb0 100644--- a/specs/empty-library/decision_log.md+++ b/specs/empty-library/decision_log.md@@ -18,7 +18,7 @@ | Q12 | 2026-09-17 | An interrupted emptying is reported at the next open on the interrupted-import notice's terms, and every exit path re-fires the deferred triggers | Requirements review: the inline row outcome dies with the process, so without a sidecar an interrupted emptying is silent where an interrupted import is reported. The re-fire is on every path because `confirmImport` only defers the exclusion flag, not the re-fire, and a throwing empty must not leave a deferred pass stranded | | Q13 | 2026-09-17 | The spool and `ExportOwed/` are removed by a listing taken when the deletion begins; a file that lands after the listing survives | Requirements review: the spool is four directories plus a report, its writers publish by atomic rename with no cross-process lock, and set-aside captures are reader-visible in Settings, so the dialog names them. Deleting the root would race the extension; a cutoff makes Req 3.6 and 3.7 consistent | | Q14 | 2026-09-17 | Req 3.8 asserts an empty diagnosis set only; which empty state a screen shows is the sync status's business | Requirements review: the "arriving from iCloud" variant is selected by `hasEverImported`, which latches in the sync status file that Req 3.7 leaves untouched, so on a device whose mirror never imported the emptied library shows "arriving" and that is the truth. A presentation override would add state with no defined lifetime |-| Q15 | 2026-09-17 | Req 5.1's equality is archive-to-archive ignoring export metadata, and "dirties nothing" is no moved modification timestamp and an equal archive after the second import; the "no pending changes" half was dropped by Decision 4 | Requirements review: the wire projection unions duplicate rows and synthesises Sites for rowless hostnames, so per-entity row counts would fail on a healthy round trip; the reader's purpose is that the archive survives the trip, which archive equality states directly |+| Q15 | 2026-09-17 | Req 5.1's equality is archive-to-archive ignoring export metadata, and "dirties nothing" is no moved modification timestamp and an equal archive after the second import; the "no pending changes" half was dropped by Decision 4 and restored by T-2334 / PR #88 | Requirements review: the wire projection unions duplicate rows and synthesises Sites for rowless hostnames, so per-entity row counts would fail on a healthy round trip; the reader's purpose is that the archive survives the trip, which archive equality states directly | | Q16 | 2026-09-17 | The dialog's counts and the outcome's count are physical rows | Requirements review: work deletion's Q28 counts groups because its contract is a set; "everything" has no set, and the outcome count is rows already | | Q17 | 2026-09-17 | The session between emptying and relaunch runs with zero directory rows, and capture, the editor and the pickers must tolerate that | Requirements review. Seeding runs at open only; the alternative, telling the reader to relaunch first, is harmless since the defaults seed under fixed UUIDs and the archive's rows upsert over them, but tolerance is the standing rule for a list not yet synced and costs nothing to keep | | Q18 | 2026-09-17 | The M4 deletion arm is reported with a regression ceiling drawn from its first quiet-host measurement, not the 3 s class ceiling | Requirements review: deleting entries under a live Site pays the `Site.entries` maintenance T-2093 measured, and the 5,000-row cost is not known until measured. The design decides whether the settling pass's detach-first technique is used |@@ -174,6 +174,8 @@ Req 5.1 and Q15 asked that a second import of the same archive move no modificat  Req 5.1 asserts stored state: the archive exported after the second import equals the first, and no record's `modifiedAt` moves. The "no pending changes" clause is removed from the requirement, the design and Q15. Value-guarding the importer is T-2334. +**Note (2026-09-22)**: T-2334 / PR #88 value-guarded the importer and restored the `hasChanges == false` assertion in `aSecondImportOfTheArchiveDirtiesNothing`. The amended requirement text stands; the negative consequence below no longer applies.+ ### Rationale  The reader's purpose in Req 5.1 is that emptying is a safe way to test import, and archive equality states that result in full. The clean-save property is real, since a no-op re-import re-exports every row through the mirror, but it is a property of the importer that exists with or without this feature. Guarding the importer's writes touches every record kind's upsert and interacts with the import recency gate (`cloudkit-mirroring` Decisions 2 and 8); that is a change to review on its own, not inside a `Development`-only debug action.
specs/empty-library/design.md Modified +1 / -1
diff --git a/specs/empty-library/design.md b/specs/empty-library/design.mdindex 228fc1ca..76714f91 100644--- a/specs/empty-library/design.md+++ b/specs/empty-library/design.md@@ -267,7 +267,7 @@ func documentExporter(isPresented:, file:, identifier:, onCompletion: @escaping | 3.8 | A store seeded with a tolerated-state diagnosis: `diagnostics` and the quarantine map are empty afterwards | | 3.9 | The work editor model over zero work types and roles drafts `other` and an empty role list; a capture over a store with zero directories commits | | 4.2 | A spool whose directory is made unremovable: `cleanup == .failed`, rows still zero, sidecar cleared |-| 5.1 | Export → empty → import → export: the two archives' payloads are equal with `exportedAt` and the file name masked; after a second import the exported payload is still equal and no `modifiedAt` moves (Decision 4; the clean-save property is T-2334) |+| 5.1 | Export → empty → import → export: the two archives' payloads are equal with `exportedAt` and the file name masked; after a second import the exported payload is still equal and no `modifiedAt` moves (Decision 4; the clean-save property is T-2334, which PR #88 landed — the test asserts it again) | | sweeps | A save strategy that inserts an Entry into the context on the last phase's save: the second sweep deletes it, the third finds nothing, and the report is `completed` | | idempotence | A second `emptyLibrary()` over the emptied store reports `completed` with `rowsDeleted: 0` | | coverage | `ModelContractTests`: the phase list's entity names as a set equal `AsterismSchemaV15.models`' names |
specs/empty-library/implementation.md Modified +2 / -2
diff --git a/specs/empty-library/implementation.md b/specs/empty-library/implementation.mdindex d603ac2e..349d5ffc 100644--- a/specs/empty-library/implementation.md+++ b/specs/empty-library/implementation.md@@ -70,7 +70,7 @@ App (`Asterism/Asterism`): - **Site rows are deleted too**, the one sanctioned exception to "no `Site` row is ever deleted". That rule protects teaching a merge intends to keep; here nothing is kept. - **A Site's rules go in the Site's own save**, not in a phase ahead of the works as first designed. A taught Site that outlives its title rule is an illegal tuple, a diagnosis the chunk itself introduced. A validating save strategy in the tests caught it. - **Fail closed on the share outcome.** A report later than three seconds after the dismissal is treated as cancelled. That costs a retry and never the library.-- **Req 5.1 was weakened.** "A second import leaves no pending changes" was dropped: the importer writes every scalar unconditionally, which is the importer's defect (T-2334), not this feature's.+- **Req 5.1 was weakened.** "A second import leaves no pending changes" was dropped: the importer writes every scalar unconditionally, which is the importer's defect (T-2334), not this feature's. *Since restored: T-2334 / PR #88 value-guarded the importer and `aSecondImportOfTheArchiveDirtiesNothing` asserts `hasChanges == false` at each save again.* - **The row's model is owned by `AppLibraryModel`, not the view.** It first lived in `SettingsView`'s `@State`, and hoisting it was judged not worth it for a debug row. The PR review showed why that was wrong: Settings can be closed mid-pass, a reopened Settings built a fresh idle model, and a second run was refused with "Nothing was deleted" while the first was deleting everything (Q48).  ---@@ -122,7 +122,7 @@ Checked against `requirements.md`, with the pre-push spec review's walk of every  ### Partially implemented -- **Req 5.1 as originally approved.** The "no pending changes" clause is dropped, not met. Decision 4 records it and T-2334 carries it. The owner should confirm the amendment.+- **Req 5.1 as originally approved.** The "no pending changes" clause is dropped, not met. Decision 4 records it and T-2334 carries it. The owner should confirm the amendment. *Since restored by T-2334 / PR #88; the test asserts the clause again.* - **Req 5.1 for one archive shape.** An archive with a junk-suffix rule on a non-articles site imports differently into an empty library than over existing rows (T-2335). The test fixture normalises that column (Q37).  ### Missing
specs/empty-library/requirements.md Modified +1 / -1
diff --git a/specs/empty-library/requirements.md b/specs/empty-library/requirements.mdindex f6ded863..35ba1147 100644--- a/specs/empty-library/requirements.md+++ b/specs/empty-library/requirements.md@@ -81,7 +81,7 @@ Reference: `specs/cloudkit-mirroring/` (Decision 2 import never deletes; Decisio  **Acceptance Criteria:** -1. <a name="5.1"></a>WHEN the archive exported under [2.1](#2.1) is imported into the library emptied in the same session THEN an archive exported afterwards SHALL equal it, ignoring export metadata such as the timestamp and file name, and a second import of the same archive SHALL change no stored value: no record's modification timestamp moves and the archive exported after the second import equals the one exported after the first (Decision 4; that a no-op import also leaves no pending changes is T-2334's, not this feature's).  +1. <a name="5.1"></a>WHEN the archive exported under [2.1](#2.1) is imported into the library emptied in the same session THEN an archive exported afterwards SHALL equal it, ignoring export metadata such as the timestamp and file name, and a second import of the same archive SHALL change no stored value: no record's modification timestamp moves and the archive exported after the second import equals the one exported after the first (Decision 4; that a no-op import also leaves no pending changes is T-2334's, not this feature's — and T-2334 / PR #88 has since value-guarded the importer and restored that assertion in this feature's test).    ## Verification 

Things to double-check

Full make test-core on an unlocked host.

This run skipped PendingCaptureSpoolTests, PendingCaptureDrainTests and ShareCaptureFlowTests, which EPERM on this host on main too (docs/agent-notes/testing.md, keychain condition). None touch the import path, but the report claims a full make test-core; run it with the keychain open before pushing.

Facts blob policy.

Decide whether undecodable fact bytes should heal on import as citations do. If yes, guard by canonical bytes (RecordFactCodec.encode) and add an arm to a small test over CharacterRecord; if no, say so in the comment so the asymmetry with the citation guard is deliberate.

Same-UUID groups on the no-op path.

The golden payload carries no same-UUID row groups, so the second-import test exercises single-row groups only. A group re-pointed on the first import is a fixed point on the second by construction, but nothing asserts it.