asterism branch feature/launch-to-today commits 19 unpushed files 35 touched lines +3287 / -384 launch reads 2.497 s \u2192 0.852 s

Pre-push review: launch-to-today

Today is published from its own read and the works snapshot follows in the background. Repository reads before Today is drawable fell 2.497 s → 0.852 s (65.9%). 19 commits, all 25 requirements implemented, four narrow concurrency gaps left for a decision.

At a glance

  • The measured result holds up. 2.497 s → 0.852 s is a like-for-like pair taken twelve minutes apart on one host; launch-reads-full barely moved (−2.5%), which is the evidence that the work was relocated rather than removed.
  • Every requirement has code behind it. 1.1–1.4, 2.1–2.5, 3.1–3.10, 4.1–4.2 and 5.1–5.4, verified individually against the diff.
  • Four concurrency gaps, all narrow, none blocking. The one to care about is C4: a Retry abandoned at a gate leaves a spinner with no button.
  • The launch path is now written twice. publishToday() and refreshAll() share a nine-statement publish block and a read prologue; one helper would subsume that and two redundant-state findings.
  • An unplanned saving fell out of the refactor. works() stopped building entry snapshots it discarded — every attached entry in an unsplit group was snapshotted twice, with a JSON decode each time.
  • Tests are green where they can run. make test-core is red on this machine only because the screen is locked and the pending-capture suites are file-protected; nothing but documentation has changed since the last clean run.

Verdict

Ready to push \u2014 four decisions owed before merge

The feature is complete and coherent: an independent pass over all 25 numbered requirements found code behind every one, all four design decisions match the implementation, and no unrecorded architectural divergence. make test-quick passes at 1,681 checks after this review's fixes.

Six documentation and comment defects were found and fixed here, the most serious being an index claim that the performance figures came from a quiet host when the verification run says in bold that they did not.

What is not fixed, and why: four narrow concurrency gaps (a teardown window that can mark a load failed when Req 3.8 says it must not; an unguarded first read in the launch tail; a doubled read on the fallback path; and a Retry that can leave a permanent spinner) plus three duplication findings. Each changes behaviour that an approved design listing specifies, and this repository treats those listings as artifacts that move by decision entry rather than by quiet edit. They are described in full below and in implementation.md.

Review findings

19 raised · 6 fixed · 13 skipped

Jump to findings →

Tests

Pass rate: n/a

New tests: 40

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

What Changed

Opening Asterism used to mean waiting for the whole library to be read before anything appeared. The largest part of that wait was building the works snapshot — a list of every work with its entries attached. Today, the screen you land on, did not actually need that list. It needed it for one thing only: working out which stories are due a new chapter today.

So the app now does that calculation somewhere else — while it is already reading Today's own data, from information it has in its hands anyway. Today can be drawn immediately, and the big list is fetched afterwards, in the background, while you are already reading.

Two things follow. Works and Stats do need the big list, so they now show a spinner until it arrives and an error with a Retry button if it fails. And Today lost its search field — it had become a dashboard, and note search is moving to Works instead.

Why It Matters

The reads you wait on before Today is drawable fell from about 2.5 seconds to about 0.85 seconds on the 5,000-entry test library — roughly two-thirds less. The work did not get cheaper; it moved out of the way, to where nobody is waiting for it.

There is also a new log line at every launch saying how long the launch took and where the time went, so the next person asking “why is opening slow?” has numbers rather than a guess.

Key Concepts

  • Snapshot — a frozen, read-only copy handed to the screens. Screens never touch the database; they get photocopies, not the original.
  • Publication — one moment when fresh snapshots reach the screens. Everything in one publication describes the same instant, so you never see half-old, half-new data.
  • The schedule — the Releasing and Catching up lists and the week-strip dots. This is the thing that moved.
  • Reconcile — a background repair pass for duplicates after a sync. It now runs after the big list loads, because they compete for one database lock and only one of them has a person waiting on it.

Changes Overview

The change splits one launch publication into two, and moves one derivation across a module boundary.

AsterismCore. TodayDayPlan.swift extracts the bucket test into TodaySchedule.admits(readingStatus:workStatus:releaseDays:), so there is one spelling instead of an inline copy. LibraryRepository.swift splits the work snapshot into a fields-only core taking entry snapshots as a parameter. LibraryRepository+Groups.swift adds an overload that builds a group snapshot from entry rows the caller already holds. LibraryRepository+TodayPresentation.swift computes the work groups once, prefilters through admits so only listed works are snapshotted, buckets the entry rows once by work id, and returns schedule and workTitles on TodayPresentation.

App. AppLibraryModel.swift gains publishToday(), a worksLoad state, scheduleLaunchTail() (first load, one retry, then the reconcile), a repositoryEpoch, and one consolidated enterCycle()/canPublish(_:) gate used by both publishers. WorksLoadGate.swift wraps Works and Stats. LaunchMeasurement.swift holds a LaunchPhaseRecord value type that both the signposts and the log line are built from. TodayView.swift loses the search field; the filter stays, defaulted inactive.

Implementation Approach

One publication, two publishers. The file's existing invariant — no await between the publish gate and the last assignment, so a reader observes one cycle's values — is preserved in both. enterCycle() captures calendar, calendar key, generation and epoch synchronously before the first read; canPublish(_:) re-checks all three.

Answer “not loaded yet” once. Five readers of the works snapshot would otherwise have to tell “empty library” from “not read yet”. Rather than teaching all five, the question is answered at the screen boundary: WorksView and StatsView are constructed only in the .loaded arm.

Equivalence checked by test. TodayScheduleEquivalenceTests asserts the new schedule equals the works-derived one over seven fixtures, including a same-UUID split group whose rows disagree, a dismissed cross-site pair, a split entry group pointing at two works, and an empty library.

Trade-offs

  • Moving the derivation rather than caching it. A cache would need invalidation on every write, and the pairing with the rows is what makes Today coherent.
  • One gate view rather than five taught readers. One place to get right and one place to change.
  • An ordinary refreshAll() as the first works load. One code path instead of two, at the cost of the tail repeating the Today read the reader just waited for — off the critical path, but real.
  • Reported, not budgeted. The new launchReads arm asserts nothing: no time-to-first-Today number exists yet, so a bound drawn now would be a guess.

Technical Deep Dive

Why the schedule can move without changing its answer. TodaySchedule.build reads only readingStatus, workStatus, releaseDays and each work's entry days. A snapshot's statuses and release days are its carrier's, so asking admits of the carrier before snapshotting is an exact prefilter, not an approximation. Only admitted groups are snapshotted, with series: .empty and credits: .empty, because ScheduledWork reads neither.

Why nothing on the new path faults work.entries. The fields-only core touches stored columns only. The group overload passes entries: [] for the representative and carrier and supplies the group's entries from rows the caller holds, bucketed once by row.work?.id — a to-one the surrounding loop has already faulted for the common case. A to-many fault per work over a 1,000-work fixture is the cost the whole feature exists to avoid.

A side effect worth naming. Because the pre-existing group snapshot now delegates to the new overload, works() stopped building per-row entry snapshots for the representative and carrier that it then discarded — including a citationsData JSON decode per entry. For an unsplit group, every attached entry was snapshotted twice and one copy thrown away. This was not in the design; it fell out of the refactor.

What the three guards do and do not promise. The generation guard means a cycle that entered at n can never overwrite one that published at n+1. It does not order two cycles that entered at the same generation: the repository is an actor, their reads serialise invisibly, and the first to the publish wins even holding the staler read. The residue is a write-then-refresh whose refresh loses and leaves a change unshown until the next one — self-correcting. A re-read loop would close it and is deliberately not taken: a CloudKit hydration republishes dozens of times, and retrying until the counter holds still is exactly the shape that does not terminate under the load it would matter most in.

Why the reconcile moved behind the works load. CrossProcessLibraryLock polls a non-blocking lock with no writer fairness, so a reconcile winning it first could time the works read out from under the Works tab. Two tail attempts are the bound; if both are abandoned at a gate the reconcile runs anyway, a knowingly accepted gap against Req 3.10's “published or failed” wording.

Architecture Impact

TodayPresentation becomes the single source of Today's schedule, and TodaySchedule.build has no app-layer caller left. The model gains a lifecycle counter (repositoryEpoch) beside the existing pendingCaptureGeneration, both bumped in the same teardown for the same purpose — a third should be resisted.

snapshotGeneration changed meaning: it bumps twice per launch, so a non-zero generation no longer implies the works snapshot was read. Anything keyed on it wants re-reading in that light — ArrivingLibraryPresentation.hasContent(snapshotGeneration:) is documented as “a refresh cycle has completed”, which is no longer what the counter means.

Potential Issues

Four narrow concurrency gaps, none blocking, none fixed here because each changes behaviour specified by an approved design listing:

  1. Teardown window. repositoryEpoch is bumped before the first suspension, but repository is not cleared until after await shutdown(). A cycle entering during teardown captures the new epoch, reads a dying store, and may publish or mark .failed — the case Req 3.8 says must not be a failure.
  2. The tail's first read is unguarded. scheduleLaunchTail() awaits refreshAll() before any cancellation or epoch check.
  3. The .fellBack launch reads twice. bootstrap() runs refreshAll() and the tail then runs it again unconditionally.
  4. Retry has no retry. retryWorksLoad() makes one attempt; abandoned at a gate it leaves worksLoad == .loading — a spinner with the Retry button gone.

Carried forward: works() still faults work.entries per work, which the new overload makes trivially fixable but which this branch did not touch.

Important changes — detailed

todayPresentation builds the schedule and the title map itself

LibraryRepository+TodayPresentation.swift

Why it matters. The load-bearing change. It is what lets Today be drawn without the works snapshot, and it is the one place where a mistake would make Today disagree with itself.

What to look at. LibraryRepository+TodayPresentation.swift:230-326

Takeaway. A prefilter is exact when it asks the same question of the same row the answer will come from. Asking admits of the carrier before snapshotting is safe precisely because a snapshot's statuses are its carrier's.
Rationale. Decision 2, superseding update-schedule Q28. Deriving the schedule from the works snapshot made Today wait for a read it did not otherwise need; the rows the presentation already holds carry everything build consumes.

One publish gate for both publishers

AppLibraryModel.swift

Why it matters. Two publishers now race where there was one. The gate is the only thing standing between that and a reader seeing two moments of the library mixed together.

What to look at. AppLibraryModel.swift:1295-1366 (enterCycle, canPublish)

Takeaway. When you add a second writer to a published value, consolidate the guards before adding the writer. The three inline guards became one named pair, and the new epoch guard joined them rather than being bolted on.
Rationale. Q60 (overlap), Q44 (calendar) and Q19 (epoch) were three separate inline guards in refreshAll; publishToday needed all three, and copying them would have been the third and fourth spelling.

WorksLoadGate answers \u201cnot loaded yet\u201d once, at the screen boundary

WorksLoadGate.swift

Why it matters. Without it, five readers of the works snapshot would each have to distinguish an empty library from an unread one \u2014 and each would get it wrong differently.

What to look at. WorksLoadGate.swift:21-112

Takeaway. When a new state would force every consumer to learn a distinction, put the distinction at the boundary and let the consumers stay ignorant. WorksView and StatsView are unchanged by this feature.
Rationale. Decision 3. An audit found five such readers; teaching all five was rejected as five places to get right instead of one.

The launch reports its own phases

LaunchMeasurement.swift

Why it matters. The feature is about launch time, and before this there was no way to say where launch time went on a real device.

What to look at. LaunchMeasurement.swift:1-178

Takeaway. Build the signpost and the log line from one small value type. The record is testable without OSLog, which is why the export-pass ordering could be asserted at all.
Rationale. Req 1.1 and 1.2. The total is measured rather than summed because UI-test seeding sits between two phases and belongs to neither.

The group snapshot stopped discarding entry snapshots it had built

LibraryRepository+Groups.swift

Why it matters. An unintended but real saving on works(), the most expensive read in the app \u2014 and a reminder that the measured before/after figures straddle it.

What to look at. LibraryRepository+Groups.swift:382-432

Takeaway. Splitting a function into a fields-only core surfaces callers that were paying for a part they discarded. Here every attached entry in an unsplit group was snapshotted twice, with a JSON decode each time.
Rationale. Not in the design; it fell out of routing the old overload through the new one rather than duplicating 70 lines of assembly. (inferred — not stated by the author)

Today loses its search field, keeps its filter

TodayView.swift

Why it matters. The only user-visible removal in the branch, and the one most likely to be noticed.

What to look at. TodayView.swift:184-232, 973-985

Takeaway. When removing a feature that a successor will reuse, keep the data path and delete only the entry point. The filter still runs; nothing can reach it until T-2347 wires it up on Works.
Rationale. Decision 1, superseding the search clauses of update-schedule Q4 and Q10. Today is a dashboard; note search belongs where the notes are listed.

Key decisions

The schedule moves into the Today read rather than being cached.

A cache would need invalidating on every write that could change a release day or a reading status, and the pairing between the rows and the schedule is exactly what makes one Today publication coherent. Building it from rows the read already holds costs one prefilter and a bucketing pass, measured at about +0.15 s inside a 2 s budget.

The launch reconcile follows the works load, not the first Today publication.

CrossProcessLibraryLock polls a non-blocking lock with no writer fairness. A reconcile that won the lock first could time out the works read that a reader is waiting on behind the gate. Nobody waits on the reconcile, so it goes last.

The first works load is an ordinary refreshAll(), not a works-only publisher.

One code path rather than two. The cost is that the tail repeats the Today read the reader has just waited for — about 0.85 s, off the critical path but real, and it delays the Works gate by that much. Worth revisiting if the gate's spinner ever feels long.

(inferred — not stated by the author.)
The launchReads arm is reported, never budgeted.

No time-to-first-Today figure exists yet, so any bound drawn now would be a guess dressed as a budget. The arm records a band that a later budget can be set from, once a reading has been taken on a phone (Q4).

The works-load failure is shown per screen, not per app.

A failed works read leaves Today entirely usable, so failing the whole app would be a lie about what is broken. The gate is on Works and Stats only, and Export stays available on Today (Req 5.2).

Review findings

SeverityAreaFindingResolution
majorspecs/OVERVIEW.md \u2014 measurement conditionsThe index claimed the launch saving came from \u201ctwo same-session make test-performance-m4 runs on a quiet host\u201d. verification-run.md \u00a74.1 says the opposite in bold \u2014 \u201cA busy host is not a quiet host and neither run sets a band\u201d \u2014 and the before side was a filtered two-test swift test, not the full target. An index asserting a quiet host invites a future reader to treat 0.852 s as a band.Rewritten to say the host was busy for both, that the pair gives a like-for-like comparison rather than an absolute, and that the before side was a filtered run. The omitted make test-ui failure and its exit status were added at the same time.
minorCHANGELOG.md \u2014 missing headline resultThe changelog carried only the before figures, in the future tense (\u201cthe final verification re-measures before and after in one session\u201d). That re-measurement happened and produced the feature's headline number, which appeared in CLAUDE.md, the overview and the verification run but nowhere in the changelog.Added the 1.645 s / 65.9% result to the Changed entry, with the caveats that it is a like-for-like pair rather than a band and is repository read time rather than time-to-first-Today.
minorAppLibraryModel.swift \u2014 todaySchedule docThe property is now a verbatim mirror of todayPresentation.schedule, and the change deleted the justification the doc used to carry (\u201cTodaySchedule.build is O(works + entries)\u201d), leaving \u201cthe Today screen reads it on every body pass\u201d \u2014 which is not a reason to cache a stored property of another published struct.Doc corrected to say what it now is: a stored mirror kept for the property name, with collapsing it to a computed property named as a known simplification deliberately not taken in the same change.
minorTodayView.swift \u2014 false comment on a dead branchsearchEmptyBranch is unreachable now that the plan's searchFilter defaults to inactive and the view is its only production caller, but its doc still said \u201cthe difference matters to a reader who has just typed\u201d \u2014 true of nobody.Comment rewritten to record that the branch is unreachable since Req 5.1, why it is kept (Req 5.4 holds the filter for T-2347), and what would make it render again.
minorWorksLoadGate.swift \u2014 miscited decisionThe loading label cited Q3 for the re-wording to \u201cLoading works\u2026\u201d. Q3 decides the indicator over skeleton rows and says the presentation should match \u201cOpening library\u2026\u201d; it says nothing about re-wording.Comment now attributes the shape to Req 3.2, reads \u201cpresentation\u201d as shape rather than string, and says plainly that Q3 did not decide the wording.
minorAppLibraryModel.swift \u2014 undocumented test seamscheduleLaunchTail() dropped private with no comment, unlike its neighbours waitForLaunchTail and launchReconcileCompleted which both say they are read by tests. A future tidy-up would push it back to private and break four tests.Doc now says it is internal as a test seam and why bootstrap() cannot reach those cases, and records the unguarded-first-read gap below as deliberately left for a decision.
majorAppLibraryModel.swift \u2014 teardown window (C1)repositoryEpoch is bumped before the first suspension, but repository is not cleared until after await shutdown(). A cycle entering during teardown captures the new epoch, reads a store being shut down, and either publishes values from a dying repository or throws and sets worksLoad = .failed \u2014 which is exactly the case Req 3.8 says must not count as a failure. Narrow, and self-correcting on the next publication.Not fixed. The fix (clear the reference in the same suspension-free prologue as the counter, shut down a local afterwards) reorders teardown, which is concurrency-critical code covered by the new tests. Flagged for a decision before merge.
majorAppLibraryModel.swift \u2014 unguarded first tail read (C2)scheduleLaunchTail() awaits refreshAll() before any cancellation or epoch check, so a tail cancelled before it first resumes still issues one full library read \u2014 possibly against the library that replaced the one it was scheduled for. The existing guard three lines below catches the reconcile but not the read.Not fixed. The design listing is written this way and task 6 implemented it verbatim, so tightening it changes an approved listing and wants a decision-log entry. A note recording the gap was added to the function's doc.
minorAppLibraryModel.swift \u2014 the .fellBack launch reads twice (C3)When publishToday() publishes nothing, bootstrap() runs refreshAll() (setting .loaded) and the tail then runs refreshAll() again unconditionally \u2014 a second full works() read, measured at 1.6\u20132.4 s on the M4 fixture, milliseconds later. Only the tail's second attempt is conditional on worksLoad == .loading.Not fixed. Making both attempts conditional preserves Q21's two-attempt bound and removes the redundant read, but it diverges from the design listing. Flagged.
majorAppLibraryModel.swift \u2014 Retry has no retry (C4)retryWorksLoad() sets .loading and makes one refreshAll(). If that cycle is abandoned at the calendar or generation gate it publishes nothing and never sets .loaded, leaving the gate showing a spinner with the Retry button no longer on screen, until an unrelated refresh happens to publish. The launch tail covers exactly this case for itself (Q21); the reader's path does not.Not fixed \u2014 the most user-visible of the four. The fix is to mirror the tail's one further attempt, or to fall back to .failed when a retry publishes nothing. Needs a decision on which.
majorAppLibraryModel.swift \u2014 one publish block, written twicepublishToday() and refreshAll() duplicate the read prologue and the nine-statement publish block, with one line deliberately spelled differently (workTitlesByID, derived from the presentation in one and from the works snapshot in the other). The file's central invariant is now asserted in two places and commented in both. A third publisher will copy it again.Not fixed. One private publish helper taking an optional WorksSnapshot would subsume this and the two redundant-state findings below, but it restructures the launch path that thirteen new tests were just written against. Recommended as the first follow-up.
minorAppLibraryModel.swift \u2014 workTitlesByID has two derivationsThe map is written from presentation.workTitles in one publisher and hand-derived from works.works in the other, and a new Core test exists solely to police that the two agree. They are already not reliably in step: teardown resets workTitlesByID to empty while leaving todayPresentation \u2014 its launch-time source \u2014 untouched.Not fixed. Taking the presentation's map in both publishers would make Q16's required equality hold by construction, but it changes which store instant the map is paired with, which Q13 discusses explicitly. Flagged as a design question.
minorLibraryRepository+TodayPresentation.swift \u2014 double entry snapshotThe row loop already builds an EntrySnapshot for every entry group, decoding citationsData each time. todaySchedule then hands raw rows to the group overload, which buckets and decodes them a second time for every entry of every admitted work. Part of the measured +0.143 s, though how much is not separately measured.Not fixed. Bucketing the snapshots already built would remove the second pass, but row-level and carrier-level bucketing differ for a split entry group straddling two works, and Req 2.3's equivalence is stated against works(), which is row-level. Needs care, not a quick edit.
minorLibraryRepository+TodayPresentation.swift \u2014 whole-table bucketingThe admitted set is computed before the bucketing loop but is not used to restrict it, so all 5,000 entry rows are bucketed when only the admitted works' buckets are ever read.Not fixed, though it is provably equivalent and about three lines. Left with the finding above, since both touch the same loop and the measured figures in three documents were taken against this exact code.
minorThree copies of the unavailable-state presentationWorksLoadGate's loading and failed states copy ContentView's app-loading and app-unavailable blocks, including the minHitTarget frame verbatim; SettingsScreen already held a second copy. The gate's own docstring says it is \u201con ContentView's app-unavailable shape\u201d \u2014 a shape that should be a symbol rather than a comment.Not fixed. Extracting one view and routing three call sites through it is a worthwhile follow-up but touches surfaces this feature otherwise leaves alone.
minorTodayScheduleEquivalenceTests.swift \u2014 forked test fixtureThe private ScheduleFixture and ScheduleSeedStore are a near-verbatim fork of PublicationFixture in DuplicatePublicationTests (same epoch, same seed-and-open sequence), differing only in a couple of defaulted parameters. The target already has the convention for shared fixtures in its *TestSupport.swift files.Not fixed \u2014 test-only refactoring, deliberately out of scope for a pre-push pass. Promoting PublicationFixture into a TestSupport file is the follow-up.
minorArrivingLibraryPresentation \u2014 a docstring the change falsifiedhasContent(snapshotGeneration:) is documented as meaning \u201ca refresh cycle has completed\u201d. Since publishToday() bumps the generation before the works snapshot exists, a non-zero generation no longer means that, and StatsView's stats-unread branch is unreachable behind the gate.Not fixed. Either retire the branch or have hasContent ask worksLoad; both are decisions about a pre-existing mechanism rather than this feature's code. Recorded in implementation.md under Architecture Impact.
nitLaunchMeasurement.swift \u2014 two unpinned spellingsThe four phase names are spelled once as Phase raw values and again as StaticString signpost names, because OSSignposter requires the latter. Tests pin the raw values; nothing pins the two spellings against each other, so a typo would mislabel an Instruments track with no test failing.Not fixed. A four-line test over Phase.allCases would close it; noted in implementation.md's completeness assessment.
nitAppLibraryModel.swift \u2014 the fault seam ships in releaseUITestLaunchSupport gates its fault factory behind #if DEBUG and says \u201ca shipping build has no business carrying a way to break its own read\u201d, but the property, the init parameter and the try worksReadFault?() call on the refresh path are not gated. Production passes nil, so this is dead weight rather than a risk \u2014 but the comment claims a gating that does not exist.Not fixed. Wrapping the three sites matches the file's own precedent and is a small follow-up.

Tests

Source: local run at 2026-09-20T23:30:16+1000 · snapshot 1152e9dfd548d26a8820ea4c2e5c0abe8a479086 (dirty working tree)

Baseline: none

Execution: passed · JUnit: none · Coverage: none · Baseline: absent

Coverage scope: as the project configures it

No test results

The test runner could not be detected.

New and removed tests

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

Blast radius

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

Dependents none found Changed Dependencies none found . Asterism/Asterism Asterism/Asterism/Layout Asterism/Asterism/ViewModels Asterism/Asterism/Views Asterism/AsterismTests Asterism/AsterismUITests …rismCore/Sources/AsterismCore …mCore/Tests/AsterismCoreTests docs/agent-notes specs specs/launch-to-today specs/update-schedule CHANGELOG.mdCHANGELOG.md CLAUDE.mdCLAUDE.md Asterism/Asterism/ContentView.swift…sm/Asterism/ContentView.swift Asterism/Asterism/UITestLaunchSupport.swift…ism/UITestLaunchSupport.swift Asterism/Asterism/Layout/AppScreens.swift…erism/Layout/AppScreens.swift Asterism/Asterism/Layout/NavigationActions.swift…ayout/NavigationActions.swift Asterism/Asterism/Layout/WorksLoadGate.swift…sm/Layout/WorksLoadGate.swift Asterism/Asterism/ViewModels/AppLibraryModel.swift…wModels/AppLibraryModel.swift Asterism/Asterism/ViewModels/LaunchMeasurement.swift…odels/LaunchMeasurement.swift Asterism/Asterism/Views/TodayView.swift…sterism/Views/TodayView.swift Asterism/AsterismTests/AppLibraryModelBackgroundExportTests.swift…elBackgroundExportTests.swift Asterism/AsterismTests/AppLibraryModelTests.swift…ts/AppLibraryModelTests.swift Asterism/AsterismTests/CrossViewRefreshTests.swift…s/CrossViewRefreshTests.swift Asterism/AsterismTests/IntegrationSafetyNetTests.swift…tegrationSafetyNetTests.swift Asterism/AsterismTests/LaunchPhaseRecordTests.swift…/LaunchPhaseRecordTests.swift Asterism/AsterismTests/NavigationActionsTests.swift…/NavigationActionsTests.swift Asterism/AsterismTests/TodayFixtureSeedingTests.swift…odayFixtureSeedingTests.swift Asterism/AsterismUITests/SearchUITests.swift…smUITests/SearchUITests.swift Asterism/AsterismUITests/TodayUITests.swift…ismUITests/TodayUITests.swift Asterism/AsterismUITests/WideLayoutUITests.swift…Tests/WideLayoutUITests.swift Asterism/AsterismUITests/WorksLoadGateUITests.swift…ts/WorksLoadGateUITests.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift…ibraryRepository+Groups.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift…itory+TodayPresentation.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift…mCore/LibraryRepository.swift Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift…terismCore/TodayDayPlan.swift Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swift…mCore/TodayPresentation.swift Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift…edScalePerformanceTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/TodayScheduleEquivalenceTests.swift…cheduleEquivalenceTests.swift docs/agent-notes/testing.mddocs/agent-notes/testing.md specs/OVERVIEW.mdspecs/OVERVIEW.md specs/launch-to-today/implementation.md…ch-to-today/implementation.md specs/launch-to-today/tasks.mdspecs/launch-to-today/tasks.md specs/launch-to-today/verification-run.md…-to-today/verification-run.md specs/update-schedule/decision_log.md…date-schedule/decision_log.md specs/update-schedule/requirements.md…date-schedule/requirements.md
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+Groups.swift Modified +27 / -6
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swiftindex 73fadccc..98c7d7f9 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Groups.swift@@ -382,10 +382,31 @@ extension LibraryRepository {         _ group: WorkGroup, canonicalWorkIDs: [UUID: UUID], types: WorkTypeDirectory,         series: SeriesDirectory, credits: CreditIndex     ) throws -> WorkSnapshot {-        let base = try snapshot(-            group.representative, types: types, series: series, credits: credits)-        let entries = try entryGroups(-            group.rows.flatMap { $0.entryValues }, canonicalWorkIDs: canonicalWorkIDs)+        try snapshot(+            group, entryRows: group.rows.flatMap { $0.entryValues },+            canonicalWorkIDs: canonicalWorkIDs, types: types, series: series, credits: credits)+    }++    /// The same, over Entry rows the caller already holds+    /// (`launch-to-today` Decision 2).+    ///+    /// `entryRows` is every Entry row pointing at any row of the group. Every+    /// row of a group shares `group.id`, so a caller that has bucketed the+    /// Entry table by `row.work?.id` passes the one bucket at that id, and it is+    /// the same row set `group.rows.flatMap(\.entryValues)` reads through the+    /// inverse — `Entry.work` is the only link between the two tables.+    ///+    /// **Nothing here traverses `work.entries`**: the representative's and the+    /// carrier's fields come through the fields-only core with no entries, so a+    /// bulk caller pays no to-many fault per work+    /// (`docs/agent-notes/swiftdata-relationships.md`).+    internal static func snapshot(+        _ group: WorkGroup, entryRows: [Entry], canonicalWorkIDs: [UUID: UUID],+        types: WorkTypeDirectory, series: SeriesDirectory, credits: CreditIndex+    ) throws -> WorkSnapshot {+        let base = snapshot(+            group.representative, entries: [], types: types, series: series, credits: credits)+        let entries = try entryGroups(entryRows, canonicalWorkIDs: canonicalWorkIDs)             .values             .map { try snapshot($0) }             .sorted(by: entryActivityOrder)@@ -407,8 +428,8 @@ extension LibraryRepository {         // The carrier's assignment, like every other authored field of a split         // group: the row holding the content the group presents is the row whose         // type it presents (Q41).-        let carried = try snapshot(-            group.carrier, types: types, series: series, credits: credits)+        let carried = snapshot(+            group.carrier, entries: [], types: types, series: series, credits: credits)         return WorkSnapshot(             id: base.id,             displayTitle: carried.displayTitle,
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift Modified +63 / -4
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swiftindex d9d8942e..18d610b1 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+TodayPresentation.swift@@ -75,7 +75,10 @@ extension LibraryRepository {                 .values                 .map { (snapshot: try Self.snapshot($0), group: $0) } -            let workTitles = Self.recentWorkTitles(works, types: types)+            // Computed once and shared by the title fold, the unfiltered title+            // map and the schedule (`launch-to-today` Decision 2).+            let workGroups = Self.workGroups(works, types: types)+            let workTitles = Self.recentWorkTitles(workGroups)             // `sitesByHostname` resolves the row whose *current* teaching drives             // the row's mode and presentation — a genuine winner-selection             // question, since the Entry may point at a different row than the@@ -227,6 +230,13 @@ extension LibraryRepository {                 }             } +            // After the row loop on purpose: the entry snapshots above have+            // already faulted every row's `work` to-one, which is the only+            // relationship the bucketing below reads.+            let schedule = try Self.todaySchedule(+                workGroups: workGroups, entryRows: entryRows,+                canonicalWorkIDs: canonicalWorkIDs, types: types, calendar: calendar)+             todayPresentationLogger.debug(                 "Built Recent presentation with \(sortedEntries.count, privacy: .public) rows and \(actionableCount, privacy: .public) actionable"             )@@ -241,7 +251,13 @@ extension LibraryRepository {                 // Req 4.1's banner count, produced by the same call that produces                 // `actionableCount` rather than by a second, separately-timed read.                 diagnosisCount: self.diagnostics.affectedRecordCount,-                duplicateWorkload: workload+                duplicateWorkload: workload,+                schedule: schedule,+                // **Unfiltered**, unlike the fold the rows read (Q16): the app+                // derives this same map from the works snapshot, blank titles+                // included, and the two have to be equal for a restored+                // selection to resolve the same way against either.+                workTitles: workGroups.mapValues { $0.carrier.displayTitle }             )         }         // Published for the surfaces that are not Recent — Settings' health line@@ -266,6 +282,49 @@ extension LibraryRepository {         return result     } +    /// Today's schedule, from the rows this publication already holds+    /// (`launch-to-today` Decision 2).+    ///+    /// Equal to `TodaySchedule.build(works: works().works, calendar:)` by+    /// construction (Req 2.3): the same group projection over the same rows,+    /// fed to the same `build`. Two things keep it off the cost of `works()`:+    ///+    /// - **Only the groups the schedule lists are snapshotted.** The prefilter+    ///   asks `TodaySchedule.admits` of the carrier, which is exact — a+    ///   snapshot's statuses and release days are its carrier's, and an unsplit+    ///   group's carrier is its representative.+    /// - **The entries come from `entryRows`, bucketed once by `row.work?.id`**,+    ///   the to-one the entry snapshots have already faulted. No `work.entries`+    ///   is traversed (`docs/agent-notes/swiftdata-relationships.md`).+    ///+    /// `series` and `credits` are empty: `ScheduledWork` reads neither.+    private static func todaySchedule(+        workGroups: [UUID: WorkGroup], entryRows: [Entry], canonicalWorkIDs: [UUID: UUID],+        types: WorkTypeDirectory, calendar: Calendar+    ) throws -> TodaySchedule {+        let admitted = workGroups.values.filter { group in+            let carrier = group.carrier+            return TodaySchedule.admits(+                readingStatus: carrier.readingStatus, workStatus: carrier.workStatus,+                releaseDays: carrier.releaseDays) != nil+        }+        guard !admitted.isEmpty else {+            return TodaySchedule.build(works: [], calendar: calendar)+        }+        var entryRowsByWorkID: [UUID: [Entry]] = [:]+        for row in entryRows {+            guard let workID = row.work?.id else { continue }+            entryRowsByWorkID[workID, default: []].append(row)+        }+        let snapshots = try admitted.map { group in+            try snapshot(+                group, entryRows: entryRowsByWorkID[group.id] ?? [],+                canonicalWorkIDs: canonicalWorkIDs, types: types, series: .empty,+                credits: .empty)+        }+        return TodaySchedule.build(works: snapshots, calendar: calendar)+    }+     /// The display title each Work UUID resolves to.     ///     /// Two demotions in one helper. Works sharing an application UUID no longer@@ -285,10 +344,10 @@ extension LibraryRepository {     ///     /// Presence only, so nothing here faults a blob (Decision 1).     private static func recentWorkTitles(-        _ works: [Work], types: WorkTypeDirectory+        _ workGroups: [UUID: WorkGroup]     ) -> [UUID: (title: String, thumbnail: ThumbnailIdentity?)] {         var result: [UUID: (title: String, thumbnail: ThumbnailIdentity?)] = [:]-        for (id, group) in workGroups(works, types: types) {+        for (id, group) in workGroups {             let title = group.carrier.displayTitle             guard !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { continue }             result[id] = (title, group.carrier.thumbnailIdentity)
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift Modified +18 / -1
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex 2075892e..d4400a81 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -1955,7 +1955,24 @@ public actor LibraryRepository {     internal static func snapshot(         _ work: Work, types: WorkTypeDirectory, series: SeriesDirectory, credits: CreditIndex     ) throws -> WorkSnapshot {-        let entries = try work.entryValues.map(snapshot).sorted(by: entryActivityOrder)+        snapshot(+            work, entries: try work.entryValues.map(snapshot).sorted(by: entryActivityOrder),+            types: types, series: series, credits: credits)+    }++    /// The fields-only core of the snapshot above: everything the row itself+    /// holds, with the entries handed in rather than read.+    ///+    /// Split out for `launch-to-today` Decision 2. A caller that already holds+    /// the library's Entry rows builds a work's entries from those and passes+    /// them here, so nothing on its path traverses `work.entries` — a fault per+    /// work on a budgeted read (`docs/agent-notes/swiftdata-relationships.md`).+    /// The group projection passes none at all for the representative and the+    /// carrier, whose entries it replaces with the group's own.+    internal static func snapshot(+        _ work: Work, entries: [EntrySnapshot], types: WorkTypeDirectory,+        series: SeriesDirectory, credits: CreditIndex+    ) -> WorkSnapshot {         let membership = GroupOrdering.membership(of: work)         return WorkSnapshot(             id: work.id,
Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift Modified +44 / -17
diff --git a/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift b/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swiftindex 657a404b..f6a0a3cc 100644--- a/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/TodayDayPlan.swift@@ -169,10 +169,11 @@ extension CivilDay: CustomStringConvertible {  /// Every scheduled work in the library, and the weekdays any of them is due on. ///-/// Built once per publication from the works snapshot `AppLibraryModel` already-/// publishes, beside the entry presentation and in the same no-`await` block, so-/// a reader sees one cycle's values rather than two moments of the same library-/// (Q28). The screen's per-day work is `TodayDayPlan.build`, which reads this.+/// Built once per publication, inside `todayPresentation` and under the lock+/// that reads the entry rows, so the rows and the schedule are one observation+/// rather than two moments of the same library (`launch-to-today` Decision 2,+/// superseding Q28's works-snapshot derivation). The screen's per-day work is+/// `TodayDayPlan.build`, which reads this. public struct TodaySchedule: Equatable, Sendable {     /// The scheduled works — at least one release day, work status `ongoing`,     /// reading status `reading`@@ -208,28 +209,54 @@ public struct TodaySchedule: Equatable, Sendable {         self.catchingUp = catchingUp     } +    /// Which of the schedule's two lists a work belongs in.+    public enum Bucket: Equatable, Sendable {+        case scheduled+        case catchingUp+    }++    /// The bucket a work with these three values lands in, or nil where the+    /// schedule does not list it at all.+    ///+    /// The one spelling of the test (`launch-to-today` Decision 2): `build` asks+    /// it of every snapshot, and `todayPresentation` asks it of every work+    /// group's carrier *before* snapshotting, so only the works the schedule+    /// lists pay for a snapshot. The prefilter is exact because a snapshot's+    /// statuses and release days are its carrier's.+    ///+    /// The **order of the two tests is load-bearing**: the reading status+    /// decides which bucket a work lands in (Q8), so `catchingUp` is claimed+    /// first and only what is left is offered to the scheduled predicate. The+    /// two are disjoint as that predicate stands today — it still requires+    /// `readingStatus == .reading` — but that clause is exactly the sort of+    /// thing a later change to Req 6.1 relaxes, and a catch-up work with release+    /// days must never be swallowed by the scheduled bucket when it does.+    public static func admits(+        readingStatus: ReadingStatus, workStatus: WorkStatus, releaseDays: [ReleaseDay]+    ) -> Bucket? {+        if readingStatus == .catchingUp { return .catchingUp }+        if workStatus == .ongoing && readingStatus == .reading && !releaseDays.isEmpty {+            return .scheduled+        }+        return nil+    }+     /// The schedule the library's works amount to under `calendar`.     ///     /// O(works + entries), and the calendar is consulted only to bucket each     /// work's entries into civil days.     public static func build(works: [WorkSnapshot], calendar: Calendar) -> TodaySchedule {-        // One walk, two buckets, and the **order of the two tests is-        // load-bearing**: the reading status decides which bucket a work lands-        // in (Q8), so `catchingUp` is claimed first and only what is left is-        // offered to the scheduled predicate. The two are disjoint as that-        // predicate stands today — it still requires `readingStatus ==-        // .reading` — but that clause is exactly the sort of thing a later-        // change to Req 6.1 relaxes, and a catch-up work with release days must-        // never be swallowed by the scheduled bucket when it does.+        // One walk, two buckets; `admits` owns the test and its order.         var scheduledSnapshots: [WorkSnapshot] = []         var catchingUpSnapshots: [WorkSnapshot] = []         for work in works {-            if work.readingStatus == .catchingUp {-                catchingUpSnapshots.append(work)-            } else if work.workStatus == .ongoing && work.readingStatus == .reading-                && !work.releaseDays.isEmpty+            switch admits(+                readingStatus: work.readingStatus, workStatus: work.workStatus,+                releaseDays: work.releaseDays)             {-                scheduledSnapshots.append(work)+            case .catchingUp: catchingUpSnapshots.append(work)+            case .scheduled: scheduledSnapshots.append(work)+            case nil: break             }         }         let collate = { (snapshots: [WorkSnapshot]) in
Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swift Modified +18 / -1
diff --git a/Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swift b/Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swiftindex 549d240f..3067144b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swift@@ -26,17 +26,34 @@ public struct TodayPresentation: Equatable, Sendable {     /// state and its *set* to `duplicateWorkload.reviewCount` — different     /// actions, both real (Req 9.1).     public let duplicateWorkload: DuplicateWorkload+    /// The Releasing and Catching up sections and the week strip's dots+    /// (`launch-to-today` Decision 2), built from the same rows under the same+    /// lock as `groups`, so Today draws whole without the works snapshot+    /// (Req 2.1, 2.2).+    ///+    /// Equal to `TodaySchedule.build(works: works().works, calendar:)` over the+    /// same store (Req 2.3); only the works the schedule lists are snapshotted+    /// to build it.+    public let schedule: TodaySchedule+    /// Every work's display title by id, **unfiltered** (Q16): blank titles+    /// included, so this equals the map the app derives from the works snapshot+    /// and a restored selection resolves the same way against either.+    public let workTitles: [UUID: String]      public init(         groups: [TodayPresentationGroup],         actionableCount: Int,         diagnosisCount: Int = 0,-        duplicateWorkload: DuplicateWorkload = .empty+        duplicateWorkload: DuplicateWorkload = .empty,+        schedule: TodaySchedule = TodaySchedule(works: [], dueWeekdays: [], catchingUp: []),+        workTitles: [UUID: String] = [:]     ) {         self.groups = groups         self.actionableCount = actionableCount         self.diagnosisCount = diagnosisCount         self.duplicateWorkload = duplicateWorkload+        self.schedule = schedule+        self.workTitles = workTitles     }      /// All rows flattened in display order.
Asterism/Asterism/ContentView.swift Modified +15 / -1
diff --git a/Asterism/Asterism/ContentView.swift b/Asterism/Asterism/ContentView.swiftindex 5e09b6cf..637382bd 100644--- a/Asterism/Asterism/ContentView.swift+++ b/Asterism/Asterism/ContentView.swift@@ -136,7 +136,18 @@ struct ContentView: View {             for key in WorksListStorageKey.seededLaunchResets {                 UserDefaults.standard.removeObject(forKey: key)             }-            return AppLibraryModel(configuration: configuration, uiTestFixture: fixture)+            // `launch-to-today` Q17: nil for every scenario but the one that+            // asks for a failed works load. Written as a closure literal at the+            // parameter's own declared type rather than handed back from+            // `UITestLaunchSupport`: that type is implicitly `@Sendable`, and a+            // function value converted into it warns about data races.+            var worksReadFault: (@MainActor () throws -> Void)?+            if UITestLaunchSupport.worksReadFailsUntilRetry() {+                worksReadFault = { throw UITestLaunchSupport.InjectedWorksReadFailure() }+            }+            return AppLibraryModel(+                configuration: configuration, uiTestFixture: fixture,+                worksReadFault: worksReadFault)         case .invalid(let message):             return AppLibraryModel(startupFailureMessage: message)         }@@ -684,6 +695,9 @@ struct ContentView: View {         return NavigationActions(             tab: navigation.selectedTab,             isWide: !usesCompactTree,+            // Q22: ⌘F focuses the Works search field, which does not exist+            // while the list is behind the works-load gate.+            worksLoaded: model.worksLoad == .loaded,             subject: subject,             newWork: { navigation.showingNewWork = true },             find: navigation.requestSearchFocus,
Asterism/Asterism/Layout/AppScreens.swift Modified +39 / -6
diff --git a/Asterism/Asterism/Layout/AppScreens.swift b/Asterism/Asterism/Layout/AppScreens.swiftindex 8c2c666d..542cdaac 100644--- a/Asterism/Asterism/Layout/AppScreens.swift+++ b/Asterism/Asterism/Layout/AppScreens.swift@@ -77,12 +77,6 @@ struct AppScreens {             // list wears the selected-row recipe. The compact tree pushes the             // entry instead, so there is no beside and nothing to mark.             selectedEntryID: isWide ? navigation.selectedTodayEntryID : nil,-            // Req 6.1 is the iPad's hardware keyboard as well as the Mac's menu-            // bar, and a narrow Split View is the compact tree — so ⌘F reaches-            // the search field on both. Per tab: a `SwiftUI.Tab` keeps the-            // unselected tab's content alive, so one shared token focused both-            // lists' fields and the keyboard came up unasked on the next switch.-            searchFocusRequest: navigation.searchFocusRequest(for: .today),             showsSky: showsSky,             // A noted row clears the Today stack under it, so the entry is the             // pane's whole content — the Works list's unattached route's shape.@@ -158,7 +152,23 @@ struct AppScreens {      // MARK: - Works +    /// Behind the works-load gate (`launch-to-today` Req 3.3): `WorksView` is+    /// not built until the snapshot has published, so its settled-empty branch+    /// cannot stand in for a library that has not been read yet. Both trees put+    /// this screen inside a stack of their own, so the gate needs none.     func works() -> some View {+        WorksLoadGate(+            state: model.worksLoad,+            retry: { Task { await model.retryWorksLoad() } },+            title: AppTab.works.title,+            ownsNavigationStack: false,+            showsSky: showsSky+        ) {+            worksList()+        }+    }++    private func worksList() -> some View {         WorksView(             snapshot: model.worksSnapshot,             duplicateWorkload: model.todayPresentation.duplicateWorkload,@@ -173,6 +183,11 @@ struct AppScreens {             // `series-and-related-works` asks that the list's selection clear             // while a series screen is showing.             selectedWorkID: isWide ? navigation.markedWorkID : nil,+            // Req 6.1 is the iPad's hardware keyboard as well as the Mac's menu+            // bar, and a narrow Split View is the compact tree — so ⌘F reaches+            // the search field on both. Per tab, though Today has had no field+            // since `launch-to-today` Req 5.1: the token is `AppNavigation`'s+            // shape, and a request made on another tab must not focus this one.             searchFocusRequest: navigation.searchFocusRequest(for: .works),             showsSky: showsSky,             // `showWork` clears the other routes this column can be showing. In@@ -355,7 +370,25 @@ struct AppScreens {      // MARK: - Stats +    /// Behind the same gate (Req 4.2): `StatsView` never derives over zero+    /// works, so the only states it gains are the gate's two.+    ///+    /// The compact tab has no stack around it and the screen supplies its own,+    /// which the gate's states would otherwise be drawn without — hence+    /// `ownsNavigationStack` here and not on Works.     func stats() -> some View {+        WorksLoadGate(+            state: model.worksLoad,+            retry: { Task { await model.retryWorksLoad() } },+            title: AppTab.stats.title,+            ownsNavigationStack: !isWide,+            showsSky: showsSky+        ) {+            statsPage()+        }+    }++    private func statsPage() -> some View {         StatsView(             presentation: model.todayPresentation,             works: model.worksSnapshot.works,
Asterism/Asterism/Layout/NavigationActions.swift Modified +21 / -7
diff --git a/Asterism/Asterism/Layout/NavigationActions.swift b/Asterism/Asterism/Layout/NavigationActions.swiftindex b007777b..91f371f5 100644--- a/Asterism/Asterism/Layout/NavigationActions.swift+++ b/Asterism/Asterism/Layout/NavigationActions.swift@@ -14,10 +14,17 @@ import SwiftUI struct NavigationActions: Equatable {     // MARK: - The facts -    /// The three facts every closure below is a function of, kept so the value+    /// The four facts every closure below is a function of, kept so the value     /// can be *compared* (see the `Equatable` note at the foot of this type).     let tab: AppTab     let isWide: Bool+    /// Whether the works snapshot has published (`launch-to-today` Q22).+    ///+    /// Behind the works-load gate the Works list — and with it the search field+    /// ⌘F focuses — does not exist, so the command would put the cursor in+    /// nothing. A *fact* rather than a question asked of the gate, for the+    /// reason the other three are: the enablement is decided once, here.+    let worksLoaded: Bool     /// What ⇧⌘E would export, or nil where there is nothing to export.     ///     /// The subject rather than a `hasSelection` flag, because the flag is@@ -30,7 +37,8 @@ struct NavigationActions: Equatable {      /// ⌘N. Works only: there is nothing to make on the other two.     private(set) var newWork: (() -> Void)?-    /// ⌘F. The two tabs with a list; Stats has no search field.+    /// ⌘F. The Works list, once it has loaded, and nowhere else: Stats has no+    /// search field and Today has had none since `launch-to-today` Req 5.1.     private(set) var find: (() -> Void)?     /// ⇧⌘E. The selected note or work — so a list *and* a subject.     private(set) var export: (() -> Void)?@@ -60,6 +68,7 @@ struct NavigationActions: Equatable {     init(         tab: AppTab,         isWide: Bool,+        worksLoaded: Bool,         subject: MarkdownExportModel.Subject?,         newWork: @escaping () -> Void,         find: @escaping () -> Void,@@ -70,10 +79,14 @@ struct NavigationActions: Equatable {     ) {         self.tab = tab         self.isWide = isWide+        self.worksLoaded = worksLoaded         self.subject = subject         let hasList = Self.hasList(tab)         self.newWork = tab == .works ? newWork : nil-        self.find = hasList ? find : nil+        self.find = tab == .works && worksLoaded ? find : nil+        // Req 5.2 names Export apart from Find deliberately: the two shared+        // `hasList` until Today lost its search field, and leaving them joined+        // would have disabled ⇧⌘E on the tab whose rows it exports.         self.export = hasList && subject != nil ? export : nil         self.toggleSidebar = isWide ? toggleSidebar : nil         self.selectTab = selectTab@@ -82,18 +95,19 @@ struct NavigationActions: Equatable {      /// Equal when the *facts* are equal.     ///-    /// The closures are pure functions of the three above — the initializer is+    /// The closures are pure functions of the four above — the initializer is     /// the proof — so nothing else can differ between two values that agree     /// about them. Without this, `focusedSceneValue` had no way to tell one     /// body pass's actions from the last's and republished the scene value on     /// every update of the window; with it, it republishes when the reader     /// actually moves.     static func == (lhs: NavigationActions, rhs: NavigationActions) -> Bool {-        lhs.tab == rhs.tab && lhs.isWide == rhs.isWide && lhs.subject == rhs.subject+        lhs.tab == rhs.tab && lhs.isWide == rhs.isWide && lhs.worksLoaded == rhs.worksLoaded+            && lhs.subject == rhs.subject     } -    /// Whether this tab draws a list a command can act on. Stats is one region-    /// (Req 1.2, Q5) with no rows and no search field.+    /// Whether this tab draws a list ⇧⌘E can act on. Stats is one region+    /// (Req 1.2, Q5) with no rows.     private static func hasList(_ tab: AppTab) -> Bool {         switch tab {         case .today, .works: true
Asterism/Asterism/Layout/WorksLoadGate.swift Added +114 / -0
diff --git a/Asterism/Asterism/Layout/WorksLoadGate.swift b/Asterism/Asterism/Layout/WorksLoadGate.swiftnew file mode 100644index 00000000..62508443--- /dev/null+++ b/Asterism/Asterism/Layout/WorksLoadGate.swift@@ -0,0 +1,114 @@+import ConstellationKit+import SwiftUI++/// What Works and Stats show while the works snapshot is still being read, and+/// when reading it failed (`launch-to-today` Decision 3).+///+/// `bootstrap()` publishes Today from its own read and shows the app, so+/// `.ready` no longer means the works snapshot exists. Every surface that reads+/// it would otherwise have to tell "not loaded yet" from "empty": the Works+/// list has a settled-empty state, Stats derives over the works it is given,+/// and both would report an absent snapshot as a fact about the library. The+/// audit found five such readers, so the state is answered **once**, here, at+/// the screen boundary — `WorksView` and `StatsView` are built only in+/// ``AppLibraryModel/WorksLoadState/loaded`` and are unchanged by this feature+/// (Req 3.3).+///+/// **Only the gate's own two states carry chrome.** Those two screens own+/// theirs, so while one of them is on screen the title, the sky and — on the+/// compact Stats tab — the `NavigationStack` come from the screen, and while+/// the gate is showing they come from here instead.+struct WorksLoadGate<Content: View>: View {+    let state: AppLibraryModel.WorksLoadState+    /// Req 3.6's action. Clears the fault as well as the error, so a retry that+    /// succeeds is the same publication every other refresh makes (Req 3.7).+    let retry: () -> Void+    /// The tab's name, for the gate's own states. Where a tree heads the screen+    /// itself — the compact Works stack, either tree's wide column — that title+    /// is set outside this view and wins, which is what it is for.+    let title: String+    /// Whether the gate's own states need a stack of their own.+    ///+    /// True for the compact Stats tab alone: the tab has no stack around it and+    /// `StatsView` supplies its own (`AppScreens.swift`), so without this the+    /// error would be drawn with no navigation bar and the reader would lose+    /// the heading between the two states. Everywhere else the tree already+    /// provides one and a second would draw a second bar.+    let ownsNavigationStack: Bool+    /// `ipad-and-mac-layouts` Req 3.1, passed through exactly as the gated+    /// screens take it: false in the wide tree, where the window paints one sky.+    let showsSky: Bool+    @ViewBuilder let content: () -> Content++    var body: some View {+        switch state {+        case .loaded:+            content()+        case .loading:+            gateScreen(loadingState)+        case .failed:+            gateScreen(failedState)+        }+    }++    // MARK: - The two states++    /// Req 3.2's indicator, on `ContentView`'s `app-loading` shape — the same+    /// presentation the reader has just come through. Req 3.2 asks for the+    /// `Opening library…` *presentation*, which is read as the shape rather+    /// than the string, so the label names what is actually still being read.+    /// Q3 chose the indicator over skeleton rows; it did not decide the wording.+    private var loadingState: some View {+        ProgressView("Loading works…")+            .accessibilityIdentifier("works-loading")+    }++    /// Req 3.6's error, on `ContentView`'s `app-unavailable` shape, the+    /// `minHitTarget` frame included.+    ///+    /// Unconditionally offered, unlike that one's Retry: a read that threw is+    /// exactly the case another attempt can answer differently (Q8), and every+    /// later refresh is such an attempt whether or not the reader taps this.+    private var failedState: some View {+        ContentUnavailableView {+            Label("Works Unavailable", systemImage: "exclamationmark.triangle")+                // On the state's own title rather than on the whole view, for+                // the reason `WorksView.filterEmptyBranch` records: a+                // container's identifier is pushed down onto every element+                // inside it, and on the whole state it takes `works-load-retry`+                // off the button below — leaving Req 3.6's one control+                // addressable only by its label.+                .accessibilityIdentifier("works-load-failed")+        } description: {+            Text("The library's works could not be loaded.")+        } actions: {+            Button("Retry", action: retry)+                .frame(+                    minWidth: AsterismLayout.minHitTarget,+                    minHeight: AsterismLayout.minHitTarget+                )+                .accessibilityIdentifier("works-load-retry")+        }+    }++    // MARK: - The chrome the gated screens own++    @ViewBuilder+    private func gateScreen(_ state: some View) -> some View {+        if ownsNavigationStack {+            NavigationStack { decorated(state) }+        } else {+            decorated(state)+        }+    }++    /// The frame is load-bearing rather than decoration: both states size to+    /// their content, and `screenSky` is a background, so without it the sky+    /// would be a patch the size of the label instead of the screen behind it.+    private func decorated(_ state: some View) -> some View {+        state+            .frame(maxWidth: .infinity, maxHeight: .infinity)+            .navigationTitle(title)+            .screenSky(showsSky)+    }+}
Asterism/Asterism/UITestLaunchSupport.swift Modified +29 / -0
diff --git a/Asterism/Asterism/UITestLaunchSupport.swift b/Asterism/Asterism/UITestLaunchSupport.swiftindex 34cb422c..3db62376 100644--- a/Asterism/Asterism/UITestLaunchSupport.swift+++ b/Asterism/Asterism/UITestLaunchSupport.swift@@ -373,6 +373,35 @@ enum UITestLaunchSupport {     }()     #endif +    /// `launch-to-today` Q17: how this launch's first works load behaves.+    /// Absent means it reads the library, which is what every production launch+    /// and every other UI test does.+    static let worksLoadKey = "ASTERISM_UI_TEST_WORKS_LOAD"++    #if DEBUG || ASTERISM_PERFORMANCE_TESTING+    /// Whether this launch's works read should throw.+    ///+    /// **It holds until Retry clears it**, which is what `fail-until-retry`+    /// names: the launch tail makes an attempt of its own after the first, so a+    /// fail-once fault would be spent before a test could reach the Works tab.+    ///+    /// The *answer* rather than the fault closure itself, because the model's+    /// parameter is implicitly `@Sendable` and a closure handed back from here+    /// is converted into it with a data-race warning — written at the call site+    /// it simply takes that type. Gated with the rest of the scripted behaviour:+    /// a shipping build has no business carrying a way to break its own read.+    static func worksReadFailsUntilRetry(+        environmentProvider: any ProcessEnvironmentProviding = SystemProcessEnvironment()+    ) -> Bool {+        environmentProvider.environment[worksLoadKey] == "fail-until-retry"+    }++    /// What the injected fault throws. Its text reaches no screen — the gate+    /// says the same sentence whichever of the refresh's reads threw (Q15) —+    /// so it carries only enough to be recognisable in a log.+    struct InjectedWorksReadFailure: Error {}+    #endif+     static func request(         environmentProvider: any ProcessEnvironmentProviding = SystemProcessEnvironment(),         temporaryDirectory: URL = FileManager.default.temporaryDirectory
Asterism/Asterism/ViewModels/AppLibraryModel.swift Modified +353 / -100
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex ce459c34..6980a6fc 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -43,17 +43,26 @@ public final class AppLibraryModel {     public private(set) var todayGroups: [DatedEntryGroup] = []     public private(set) var todayPresentation: TodayPresentation = TodayPresentation(groups: [], actionableCount: 0)     public private(set) var worksSnapshot: WorksSnapshot = WorksSnapshot(works: [], unattachedEntries: [])-    /// Every scheduled work and the weekdays any of them is due on-    /// (`update-schedule` Q28), derived in Core from `worksSnapshot` and-    /// published in the same block as it.-    ///-    /// A published value rather than a derivation in the view: the Today screen-    /// reads it on every body pass, and `TodaySchedule.build` is O(works +-    /// entries) over the whole library.+    /// Every scheduled work and the weekdays any of them is due on, taken from+    /// the presentation of the same publication (`launch-to-today` Decision 2,+    /// superseding `update-schedule` Q28): the rows and the schedule are one+    /// observation under one lock, and Today needs nothing from+    /// `worksSnapshot`.+    ///+    /// **A stored mirror of `todayPresentation.schedule`**, assigned by both+    /// publishers. Since Decision 2 moved the build into the presentation the+    /// two can only ever be equal, so this holds no information the+    /// presentation does not — it stays a stored property only because every+    /// Today view reads it under this name. Collapsing it to a computed+    /// property over `todayPresentation` is a known simplification, deliberately+    /// not taken in the same change that moved the build.     public private(set) var todaySchedule: TodaySchedule = TodaySchedule(         works: [], dueWeekdays: [], catchingUp: [])     /// Every Work's display title by id, published with the snapshot it is-    /// derived from.+    /// derived from — and, at launch, from `TodayPresentation.workTitles`+    /// before there is a works snapshot. The two maps are equal by contract+    /// (`launch-to-today` Q16), which is what lets a restored selection be+    /// pruned against the first publication (Req 3.5).     ///     /// `multi-site-works` Req 5.5's "Not the same work" pill names the *other*     /// Work in the set, which may be any row in the library. Derived here@@ -70,6 +79,22 @@ public final class AppLibraryModel {     /// once per keystroke of the search field. Internal rather than `public`     /// because `WorksFilterOptions` is an app-layer presentation type.     private(set) var worksFilterOptions: WorksFilterOptions = .empty+    /// Whether the works snapshot has been published since the library opened+    /// (`launch-to-today` Decision 3).+    ///+    /// `bootstrap()` shows Today from `publishToday()` alone, so `.ready` no+    /// longer means `worksSnapshot` has been read: an empty snapshot is *not+    /// loaded yet* until this says `.loaded`, and the Works and Stats screens+    /// sit behind it. `.failed` means the first full refresh threw, whichever of+    /// its reads it was (Q15); it stays until an attempt succeeds, and every+    /// later `refreshAll()` is such an attempt (Req 3.7).+    public enum WorksLoadState: Equatable, Sendable {+        case loading+        case loaded+        case failed+    }++    public private(set) var worksLoad: WorksLoadState = .loading     /// What every site in the library is called, published with the snapshots of     /// the cycle that read it (`site-display-names` Q2).     ///@@ -97,8 +122,10 @@ public final class AppLibraryModel {     /// comparison of the whole library to decide whether to do a full pass. And     /// zero means *no refresh has completed*: both snapshots initialise empty,     /// so an unread library and an empty one are otherwise the same values.-    /// Production reaches `.ready` only after `refreshAll()`, so a zero-    /// generation in a ready app means that refresh threw.+    /// Production reaches `.ready` only after `publishToday()` or its+    /// `refreshAll()` fallback, so a zero generation in a ready app means+    /// neither published. A launch bumps it twice: once for Today, once for the+    /// first works load (`launch-to-today` Decision 3).     public private(set) var snapshotGeneration: Int = 0     /// The calendar the published cycle was built under (`update-schedule` Q44,     /// Q74).@@ -247,6 +274,16 @@ public final class AppLibraryModel {     /// The resolved configuration after successful bootstrap.     private var resolvedConfiguration: LibraryConfiguration?     private var repository: (any LibraryProviding)?+    /// Which open of the library this is, advanced by every teardown+    /// (`launch-to-today` Q19).+    ///+    /// A cycle captures it at entry and may publish only while it is unchanged,+    /// so a read started against a repository that has since been torn down+    /// publishes nothing into the library that replaced it (Req 3.8). A counter+    /// rather than reference identity: `any LibraryProviding` is not+    /// class-bound, and teardown clears the reference only after awaiting the+    /// shutdown, where the counter moves before that suspension.+    private var repositoryEpoch = 0     /// Retains the concrete repository for backup export (conforms to BackupV14SnapshotProviding).     private var backupRepository: (any BackupV14SnapshotProviding)?     /// A pre-bootstrap failure used to fail closed on invalid debug launch input.@@ -254,6 +291,12 @@ public final class AppLibraryModel {     /// Seeds only a fresh, explicit temporary configuration used by UI tests.     /// Cleared after seeding so a later in-process bootstrap cannot seed twice.     private var uiTestFixture: UITestFixtureKind?+    /// Failure injection for the works load (`launch-to-today` Q17): called+    /// immediately before `works()` in `refreshAll()`, and held until+    /// `retryWorksLoad()` clears it — a fail-once fault would be cleared by the+    /// launch tail's own retry before a test reached the Works tab. Production+    /// passes nil.+    private var worksReadFault: (@MainActor () throws -> Void)?      /// The run's rule suggestions (`rule-suggestion`). Built at bootstrap over     /// the repository that opened, so it is nil until the library is ready and@@ -336,7 +379,8 @@ public final class AppLibraryModel {         configuration: LibraryConfiguration,         uiTestFixture: UITestFixtureKind,         capabilities: AsterismCapabilities = .current,-        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current }+        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current },+        worksReadFault: (@MainActor () throws -> Void)? = nil     ) {         // One read through the seam, seeding both published values (Q39, Q44).         let calendar = calendarSource()@@ -351,6 +395,7 @@ public final class AppLibraryModel {         self.locator = SystemSharedContainerLocator()         self.startupFailureMessage = nil         self.uiTestFixture = uiTestFixture+        self.worksReadFault = worksReadFault         subscribeToTemporalChanges()     } @@ -435,6 +480,15 @@ public final class AppLibraryModel {         }     } +    /// What the last launch spent, as the `LaunchToToday` signposts and the+    /// notice line were built from it (`launch-to-today` Req 1.2).+    ///+    /// Kept on the model rather than only in the log, because Req 1.1 is an+    /// *ordering* claim — the store does not open until an in-flight+    /// background-export pass has stopped — and neither a signpost nor a log+    /// line is readable from a test.+    private(set) var launchRecord: LaunchPhaseRecord?+     /// Attempts to open the library; transitions to ready or unavailable.     ///     /// Any repository this model already holds is shut down first (Q43). A@@ -450,6 +504,11 @@ public final class AppLibraryModel {         bootstrapInFlight = true         defer { bootstrapInFlight = false }         state = .loading+        // Req 1.1's interval, started where the launch starts and ended wherever+        // `state` leaves `.loading` below. The wait for a pass is inside it: it+        // is time the reader spends looking at the opening screen.+        var launch = LaunchMeasurement()+        launch.begin(.exportPassWait)         // The foreground *pre-empts* a pass rather than waiting for it: a reader         // who opens the app should see the library, not a spinner for the length         // of a grant (Req 1.7). A loop rather than one await, because the main@@ -459,10 +518,12 @@ public final class AppLibraryModel {             pass.cancel()             _ = await pass.value         }+        launch.end(.exportPassWait)         assert(backgroundSession == nil, "a pre-empted pass releases its own session")         await teardownRepository()         if let startupFailureMessage {             state = .unavailable(message: startupFailureMessage)+            launchRecord = launch.finish(.unavailable)             Self.logger.error("Library bootstrap blocked by invalid launch configuration")             return         }@@ -487,11 +548,17 @@ public final class AppLibraryModel {             // `data-model-cleanups` Decision 2 retired that generation, so the             // pass has no production caller left and survives as test support             // only (`SiteRelationshipPopulationPass`).+            launch.begin(.storeOpen)             var repo = try await LibraryRepository.openForApp(                 configuration,                 capabilities: capabilities,                 mirroring: mirroringOpenHooks             ).repository+            // Ends before the seeding below, which belongs to no phase: a+            // UI-test root is reseeded and sometimes re-opened, and charging+            // that to the store open would make a fixture's launch look like a+            // reader's (design, §Measurement).+            launch.end(.storeOpen)              if let uiTestFixture {                 try await seedUITestFixture(uiTestFixture, in: repo)@@ -526,14 +593,30 @@ public final class AppLibraryModel {             self.suggestions = Self.makeSuggestionCoordinator(library: repo)             self.characterExtraction = Self.makeCharacterExtractionCoordinator(library: repo)             interruptedImport = await repo.interruptedImport()-            // Before `refreshAll()`, so a capture this pass commits is in the-            // first snapshots rather than waiting for the next activation, and-            // before `scheduleLaunchReconcile()` below, so reconciliation cannot+            // Before `publishToday()`, so a capture this pass commits is in the+            // first publication rather than waiting for the next activation, and+            // before `scheduleLaunchTail()` below, so reconciliation cannot             // race the pass's identity check. `state` is still `.loading` here,             // so the guard is the certified repository rather than the state.+            launch.begin(.captureDrain)             await openPendingCaptureQueue(configuration: configuration, repository: repo)-            await refreshAll()+            launch.end(.captureDrain)+            // `launch-to-today` Decision 3: Today is shown from its own read, and+            // the works snapshot follows in the launch tail. A Today publication+            // that threw or was abandoned — a day change during the open is+            // enough — falls back to the full refresh the app used to open with.+            // If that publishes nothing either, `.ready` shows what it always+            // showed in that case and the launch tail is the next attempt (Q20).+            // Which of the three happened is the launch's outcome, and the only+            // way a fallback is distinguishable from a plain launch afterwards.+            launch.begin(.todayReads)+            var outcome = LaunchPhaseRecord.Outcome.published+            if await publishToday() == nil {+                outcome = await refreshAll() == nil ? .nothing : .fellBack+            }+            launch.end(.todayReads)             state = .ready+            launchRecord = launch.finish(outcome)             // Both of these belong *after* the open, and for the same reason:             // the monitor observes a container that only exists once             // certification has published the marker (Q35), and the launch@@ -543,7 +626,7 @@ public final class AppLibraryModel {                 configuration: configuration, mirroring: await repo.mirroring)             // After the monitor, because it parks on it (Req 2.4).             armExportOwedClearing()-            scheduleLaunchReconcile()+            scheduleLaunchTail()             // `character-extraction` Req 1.1: a cold launch *is* the app becoming             // active, but `didBecomeActive` fires while this is still opening —             // `handleActivation()` sees a library that is not ready yet and@@ -558,8 +641,10 @@ public final class AppLibraryModel {             // The one failure that has always been reported as a sentence of             // its own rather than as a description of an error.             state = .unavailable(message: error.message)+            launchRecord = launch.finish(.unavailable)         } catch {             state = .unavailable(message: String(describing: error))+            launchRecord = launch.finish(.unavailable)             Self.logger.error("Library bootstrap failed: \(String(describing: error), privacy: .public)")         }     }@@ -589,6 +674,10 @@ public final class AppLibraryModel {     /// reason — a pass still running against the old repository has nothing to     /// say about the library the next open publishes.     private func teardownRepository() async {+        // Before the first suspension below (`launch-to-today` Q19): a cycle+        // still reading the repository this releases finds its epoch stale at+        // the publish gate, however the awaits here interleave with it.+        repositoryEpoch &+= 1         // Defensive (Decision 1). A pass releases its own session on every path,         // so this can only find one if the model was torn down between an         // `acquire()` and its `release()`; `release()` is idempotent, so a@@ -599,8 +688,14 @@ public final class AppLibraryModel {         exportOwedClearingTask?.cancel()         exportOwedClearingTask = nil         stopSyncObservation()-        launchReconcileTask?.cancel()-        launchReconcileTask = nil+        launchTask?.cancel()+        launchTask = nil+        // The next open starts from "not loaded yet", not from whatever the+        // released library last reported. The works snapshot and the filter+        // options need no reset: the gate hides every reader of them until the+        // next `.loaded`.+        worksLoad = .loading+        workTitlesByID = [:]         duplicateFollowUpTask?.cancel()         duplicateFollowUpTask = nil         // The queued trigger and the chain count go with the repository they@@ -1042,6 +1137,54 @@ public final class AppLibraryModel {         }     } +    /// Publishes Today's values alone, from the one read they all come from+    /// (`launch-to-today` Decision 3).+    ///+    /// `bootstrap()`'s only caller, and the whole of Req 2.1: the Today screen+    /// draws from `todayPresentation` and the schedule and titles the same+    /// presentation now carries (Decision 2), so nothing on it waits for+    /// `works()` — the largest single read at launch. `worksSnapshot` and+    /// `worksFilterOptions` are deliberately not written: `worksLoad` still says+    /// `.loading`, and the gate hides every reader of them until the launch+    /// tail's `refreshAll()` publishes.+    ///+    /// Returns the generation it published, or nil where it published nothing —+    /// the same contract `refreshAll()` keeps, which is what lets `bootstrap()`+    /// fall back on the one answer.+    @discardableResult+    private func publishToday() async -> Int? {+        guard let repo = repository else { return nil }+        let cycle = enterCycle()+        do {+            let presentation = try await repo.todayPresentation(calendar: cycle.calendar)+            // Beside the presentation for `refreshAll`'s reason: the name a+            // reader sees belongs to the same cycle as the rows it names.+            let siteNames = SiteNames(try await repo.siteNames())+            let groups = presentation.groups.map {+                DatedEntryGroup(day: $0.day, entries: $0.rows.map(\.entry))+            }+            guard canPublish(cycle) else { return nil }+            // No `await` from here to the end of the block, as below.+            todayPresentation = presentation+            todayGroups = groups+            todaySchedule = presentation.schedule+            self.siteNames = siteNames+            // Q16: the presentation's map is unfiltered, so it is the map the+            // works snapshot would have produced — which is what lets the Mac's+            // restored-selection prune run against this publication (Req 3.5).+            workTitlesByID = presentation.workTitles+            self.calendar = cycle.calendar+            currentDay = CivilDay(Date(), calendar: cycle.calendar)+            snapshotGeneration += 1+            thumbnailLoader.update(generation: snapshotGeneration)+            return snapshotGeneration+        } catch {+            Self.logger.error(+                "The launch Today publication failed: \(String(describing: error), privacy: .public)")+            return nil+        }+    }+     /// Replaces all cached snapshots from the repository, publishing them     /// together or not at all (`stats-page` Q37).     ///@@ -1063,21 +1206,15 @@ public final class AppLibraryModel {     @discardableResult     public func refreshAll() async -> Int? {         guard let repo = repository else { return nil }+        // Outside the `do`, because the catch below has to know which library+        // and which generation this cycle entered against.+        let cycle = enterCycle()         do {-            // Q60: the counter turns last-writer-wins into a claim this method-            // has to keep. Two cycles can overlap — the launch reconcile, a sync-            // arrival and an activation each schedule one independently, and the-            // main actor is free across both reads below — so without this the-            // slower cycle could resume after the faster one published and-            // overwrite it with an *older* pair under a strictly higher-            // generation. `StatsView` keys its derivation on that `Int`, so it-            // would cache the stale derivation and never correct it.-            let entered = snapshotGeneration-            let calendar = calendarSource()-            // Q44: what this cycle is *about*, captured before the first read-            // and held to at the publish gate below.-            let enteredCalendarKey = CalendarKey(calendar)-            let presentation = try await repo.todayPresentation(calendar: calendar)+            let presentation = try await repo.todayPresentation(calendar: cycle.calendar)+            // Q17's injection point, immediately before the read it stands for.+            // Production passes nil; a UI-test launch and `AppLibraryModelTests`+            // pass a closure that throws.+            try worksReadFault?()             let works = try await repo.works()             // `site-display-names` Q2: the name every screen calls a site by,             // read here beside the snapshots so the lookup a reader sees belongs@@ -1089,61 +1226,17 @@ public final class AppLibraryModel {             let groups = presentation.groups.map {                 DatedEntryGroup(day: $0.day, entries: $0.rows.map(\.entry))             }-            // Another cycle published while this one was reading: abandon this-            // pair rather than publish it over one that landed later.-            //-            // What this guarantees is narrower than it first looks, and the-            // narrower statement is the true one: a cycle that entered at-            // generation *n* can never overwrite a cycle that already published-            // at *n+1*. It does **not** order two cycles that entered at the-            // same generation — the repository is an actor, so their reads-            // serialise in an order this method cannot see, and the first to-            // reach the publish wins even if the loser holds the fresher read.-            // A higher generation therefore means *published later*, not-            // *read later*. The residue is a write-then-refresh path-            // (`runDuplicatePass`, `handleSyncArrivals`, `runLaunchReconcile`)-            // whose refresh loses this race and leaves a just-committed change-            // unshown until the next one — a stale screen, self-correcting on-            // the following refresh. It introduces no *new* mixing of moments:-            // the values published are still one cycle's, and the reads inside-            // a cycle remain separate store instants exactly as Q13 already-            // discloses.-            //-            // A re-read loop would close it, and is deliberately not taken: a-            // CloudKit hydration republishes dozens of times (Q14 records ~45-            // transactions for 3,000 entries), so retrying until the counter-            // holds still is exactly the shape that does not terminate under-            // the load it would matter most in.-            guard entered == snapshotGeneration else {-                // `.notice`, not `.debug`: Q60 claims this is diagnosable, and-                // `.debug` is not persisted in the unified log. Matches the-                // precedent this file already sets for a deliberate give-up.-                Self.logger.notice(-                    "Snapshot refresh abandoned: generation moved \(entered, privacy: .public) → \(self.snapshotGeneration, privacy: .public)")-                return nil-            }-            // Q44's second gate, and it is unconditional rather than a retry.-            // The calendar moved while this cycle was reading, so every value it-            // holds — the day buckets, the schedule, the day it would call-            // "today" — describes a calendar that is no longer in force. The-            // temporal cycle entered *after* the change is the one that-            // publishes; abandoning here is what keeps a stale `calendar` or-            // `currentDay` from reaching a view for even one cycle.-            guard enteredCalendarKey == CalendarKey(calendarSource()) else {-                Self.logger.notice(-                    "Snapshot refresh abandoned: the calendar moved while it was reading")-                return nil-            }+            guard canPublish(cycle) else { return nil }             // No `await` from here to the end of the block: a reader observes             // every value of one cycle, never most of this one beside one of the             // last.             todayPresentation = presentation             todayGroups = groups             worksSnapshot = works-            // Q28: one cycle's works snapshot and one cycle's schedule, so the-            // strip's dots and the releases section can never describe a-            // different moment from the rows beside them.-            todaySchedule = TodaySchedule.build(works: works.works, calendar: calendar)+            // Decision 2, superseding Q28: the schedule is the presentation's+            // own, built under the same lock as the rows rather than derived+            // here from the snapshot beside them.+            todaySchedule = presentation.schedule             self.siteNames = siteNames             workTitlesByID = Dictionary(                 works.works.map { ($0.id, $0.displayTitle) }, uniquingKeysWith: { first, _ in first })@@ -1155,8 +1248,12 @@ public final class AppLibraryModel {             // Q44: published in the same block as the snapshots they describe,             // so a reader never holds one cycle's rows beside another cycle's             // idea of what day it is.-            self.calendar = calendar-            currentDay = CivilDay(Date(), calendar: calendar)+            self.calendar = cycle.calendar+            currentDay = CivilDay(Date(), calendar: cycle.calendar)+            // Decision 3: the works snapshot has been read, so the Works and+            // Stats screens may draw. Inside the publish block, beside the+            // snapshot the gate stands in front of.+            worksLoad = .loaded             snapshotGeneration += 1             // `work-thumbnails` Req 1.8: a slot's load is keyed on this, so a             // cover whose bytes arrived after its record did is asked for again@@ -1166,10 +1263,123 @@ public final class AppLibraryModel {             return snapshotGeneration         } catch {             Self.logger.error("Snapshot refresh failed: \(String(describing: error), privacy: .public)")+            // Req 3.6: a *first* load that threw has no earlier content behind+            // it, so the gate needs something to show — where a later failure+            // leaves the previous cycle standing and is only logged, as it+            // always was. Req 3.8: and a read that threw because a teardown shut+            // its repository down says nothing about the library that replaced+            // it, so the epoch has to be the one this cycle entered against.+            if worksLoad != .loaded, cycle.epoch == repositoryEpoch {+                worksLoad = .failed+            }             return nil         }     } +    // MARK: - The publish gate (`stats-page` Q60, `update-schedule` Q44, Q19)++    /// What a publishing cycle captured before its first read, and what the gate+    /// below holds it to.+    ///+    /// One type for `publishToday()` and `refreshAll()` both, so the two launch+    /// publications cannot drift apart in what abandons them+    /// (`launch-to-today` Decision 3).+    private struct PublicationCycle {+        /// The calendar every read of this cycle is made under, and the one it+        /// publishes. Read once through the seam, never again.+        let calendar: Calendar+        /// Q44's comparison, and nothing else — two `Calendar` values differ for+        /// reasons a reader never sees.+        let calendarKey: CalendarKey+        /// Q60's counter as it stood before the first read.+        let generation: Int+        /// Q19's counter: which open of the library this cycle is about.+        let epoch: Int+    }++    private func enterCycle() -> PublicationCycle {+        let calendar = calendarSource()+        return PublicationCycle(+            calendar: calendar,+            calendarKey: CalendarKey(calendar),+            generation: snapshotGeneration,+            epoch: repositoryEpoch)+    }++    /// Whether `cycle` may still publish the values it read.+    ///+    /// **Q60.** The counter turns last-writer-wins into a claim a publishing+    /// method has to keep. Two cycles can overlap — the launch tail, a sync+    /// arrival and an activation each schedule one independently, and the main+    /// actor is free across every read — so without this the slower cycle could+    /// resume after the faster one published and overwrite it with an *older*+    /// pair under a strictly higher generation. `StatsView` keys its derivation+    /// on that `Int`, so it would cache the stale derivation and never correct+    /// it.+    ///+    /// What that guarantees is narrower than it first looks, and the narrower+    /// statement is the true one: a cycle that entered at generation *n* can+    /// never overwrite a cycle that already published at *n+1*. It does **not**+    /// order two cycles that entered at the same generation — the repository is+    /// an actor, so their reads serialise in an order this cannot see, and the+    /// first to reach the publish wins even if the loser holds the fresher read.+    /// A higher generation therefore means *published later*, not *read later*.+    /// The residue is a write-then-refresh path (`runDuplicatePass`,+    /// `handleSyncArrivals`, `runLaunchReconcile`) whose refresh loses this race+    /// and leaves a just-committed change unshown until the next one — a stale+    /// screen, self-correcting on the following refresh. It introduces no *new*+    /// mixing of moments: the values published are still one cycle's, and the+    /// reads inside a cycle remain separate store instants exactly as Q13+    /// already discloses.+    ///+    /// A re-read loop would close it, and is deliberately not taken: a CloudKit+    /// hydration republishes dozens of times (Q14 records ~45 transactions for+    /// 3,000 entries), so retrying until the counter holds still is exactly the+    /// shape that does not terminate under the load it would matter most in.+    ///+    /// **Q44**, and it is unconditional rather than a retry. The calendar moved+    /// while this cycle was reading, so every value it holds — the day buckets,+    /// the schedule, the day it would call "today" — describes a calendar that is+    /// no longer in force. The temporal cycle entered *after* the change is the+    /// one that publishes; abandoning here is what keeps a stale `calendar` or+    /// `currentDay` from reaching a view for even one cycle.+    ///+    /// **Q19.** The library this cycle read has been released, so what it holds+    /// describes a store this model no longer has (Req 3.8). A counter rather+    /// than reference identity, for the reason `repositoryEpoch` gives.+    private func canPublish(_ cycle: PublicationCycle) -> Bool {+        guard cycle.generation == snapshotGeneration else {+            // `.notice`, not `.debug`: Q60 claims this is diagnosable, and+            // `.debug` is not persisted in the unified log. Matches the+            // precedent this file already sets for a deliberate give-up.+            Self.logger.notice(+                "Snapshot publication abandoned: generation moved \(cycle.generation, privacy: .public) → \(self.snapshotGeneration, privacy: .public)")+            return false+        }+        guard cycle.calendarKey == CalendarKey(calendarSource()) else {+            Self.logger.notice(+                "Snapshot publication abandoned: the calendar moved while it was reading")+            return false+        }+        guard cycle.epoch == repositoryEpoch else {+            Self.logger.notice(+                "Snapshot publication abandoned: the library it read has been released")+            return false+        }+        return true+    }++    /// Req 3.6's Retry, from the gate in front of Works and Stats.+    ///+    /// The only caller that clears the injected fault (Q17): every other caller+    /// of `refreshAll()` is already a retry (Req 3.7) and none of them resets+    /// `.failed` first, so the error stays until an attempt succeeds.+    func retryWorksLoad() async {+        worksReadFault = nil+        worksLoad = .loading+        await refreshAll()+    }+     /// Provides a detail model for a specific entry.     ///     /// The mutation closure schedules a duplicate pass as well as the refresh@@ -1944,8 +2154,9 @@ public final class AppLibraryModel {     /// than spinning.     static let duplicateFollowUpChainLimit = 3 -    /// Q45's once-per-launch pass, scheduled after the open publishes Recent.-    private var launchReconcileTask: Task<Void, Never>?+    /// The launch tail: the first works load, and Q45's once-per-launch+    /// reconcile behind it (`launch-to-today` Decision 4).+    private var launchTask: Task<Void, Never>?     private var launchReconcileStarted = false     /// Whether that pass has run to completion. Read by tests to pin the one     /// thing its scheduling has to guarantee: the open does not wait for it.@@ -2055,15 +2266,50 @@ public final class AppLibraryModel {         }     } -    /// Schedules the once-per-launch reconcile (Q45).+    /// Schedules the launch tail: the first works load, then the once-per-launch+    /// reconcile (Q45, `launch-to-today` Decision 4).     ///     /// A task rather than an await: the caller is the tail of `bootstrap()`, and-    /// the open's 2 s budget (Req 9.1) does not pay for merge work whose-    /// worst case is a 5,000-record re-pin. Nothing blocks on it (Req 6.4).-    private func scheduleLaunchReconcile() {+    /// the open's 2 s budget (Req 9.1) does not pay for the works read or for+    /// merge work whose worst case is a 5,000-record re-pin. Nothing blocks on+    /// it (Req 6.4).+    ///+    /// The reconcile follows the load because the two compete for the exclusive+    /// lock and only one of them has a reader waiting on it:+    /// `CrossProcessLibraryLock` polls a non-blocking lock with no writer+    /// fairness, so a reconcile that won it first could time the works read out+    /// from under the Works tab. An attempt abandoned at the calendar gate+    /// leaves `worksLoad == .loading` with no publisher of its own at that+    /// instant, so one further attempt is made (Q21); two is the bound, and the+    /// reconcile then runs whatever the state (Req 3.10).+    ///+    /// The guards are Req 3.8's: teardown cancels this task without awaiting it+    /// and the re-opening `bootstrap()` assigns its repository before its own+    /// drain, so without them a torn-down tail would take an exclusive-lock pass+    /// inside the new open and consume its once-per-launch flag.+    ///+    /// **Internal, not private, as a test seam** — the same reason+    /// `runLaunchReconcile()`, `launchReconcileCompleted` and+    /// `waitForLaunchTail()` are: the teardown and ordering cases drive the tail+    /// against the injected repository, which `bootstrap()` cannot reach without+    /// a real store. Do not tidy it back to `private`.+    ///+    /// **Known gap, deliberately left for a decision**: the first `refreshAll()`+    /// below runs before any guard, so a tail cancelled before it first resumes+    /// still issues one full library read. The design's listing is written this+    /// way and task 6 implemented it verbatim; tightening it is a change to an+    /// approved listing and wants a decision-log entry, not a quiet edit.+    func scheduleLaunchTail() {         launchReconcileStarted = false         launchReconcileCompleted = false-        launchReconcileTask = Task { [weak self] in await self?.runLaunchReconcile() }+        let epoch = repositoryEpoch+        launchTask = Task { [weak self] in+            await self?.refreshAll()+            guard let self, !Task.isCancelled, self.repositoryEpoch == epoch else { return }+            if self.worksLoad == .loading { await self.refreshAll() }+            guard !Task.isCancelled, self.repositoryEpoch == epoch else { return }+            await self.runLaunchReconcile()+        }     }      /// The launch pass itself. Runs at most once per open.@@ -2072,12 +2318,18 @@ public final class AppLibraryModel {         launchReconcileStarted = true         do {             let outcome = try await repo.reconcileAfterSync()-            // An empty pass wrote nothing and the open published Recent moments-            // ago, so re-deriving over it would repeat the open's read for no-            // change. A pass that moved custody, re-pinned records, resolved a-            // duplicate set or published reader workload changed what the screen-            // is built from, so it refreshes — `isEmpty` covers both halves.-            if !outcome.isEmpty { await refreshDiagnosesAndSnapshots() }+            // An empty pass wrote nothing and the tail published moments ago, so+            // re-deriving over it would repeat that read for no change. A pass+            // that moved custody, re-pinned records, resolved a duplicate set or+            // published reader workload changed what the screen is built from, so+            // it refreshes — `isEmpty` covers both halves.+            //+            // A first works load that failed is the other reason to refresh+            // (Decision 4): the pass has released the lock, and this is the+            // attempt Req 3.7 owes the reader who has an error on Works.+            if !outcome.isEmpty || worksLoad != .loaded {+                await refreshDiagnosesAndSnapshots()+            }         } catch {             Self.logger.error(                 "Launch reconciliation failed: \(String(describing: error), privacy: .public)")@@ -2195,7 +2447,7 @@ public final class AppLibraryModel {     }      /// Test seam: awaits the scheduled pass **and any successor it schedules**,-    /// mirroring `waitForLaunchReconcile()`.+    /// mirroring `waitForLaunchTail()`.     ///     /// The loop is what makes it a seam for the whole chain rather than for one     /// link of it; it terminates because the chain is bounded.@@ -2229,9 +2481,10 @@ public final class AppLibraryModel {         startDuplicatePass(awaitingQuiescence: false)     } -    /// Test seam: awaits the scheduled launch pass.-    func waitForLaunchReconcile() async {-        await launchReconcileTask?.value+    /// Test seam: awaits the scheduled launch tail — the first works load, the+    /// one further attempt it may make, and the reconcile behind them.+    func waitForLaunchTail() async {+        await launchTask?.value     }      /// Whether this build asked to mirror — the *declaration*, not the outcome.
Asterism/Asterism/ViewModels/LaunchMeasurement.swift Added +167 / -0
diff --git a/Asterism/Asterism/ViewModels/LaunchMeasurement.swift b/Asterism/Asterism/ViewModels/LaunchMeasurement.swiftnew file mode 100644index 00000000..d1255b34--- /dev/null+++ b/Asterism/Asterism/ViewModels/LaunchMeasurement.swift@@ -0,0 +1,167 @@+import AsterismCore+import Foundation+import OSLog++/// What one launch spent, and how it ended (`launch-to-today` Reqs 1.1, 1.2).+///+/// A plain value, and deliberately not a handful of signpost handles: the+/// `LaunchToToday` intervals and the notice line are both built from this one+/// thing, so what a launch did is assertable without a signposter and without+/// the unified log — neither of which a test can read.+///+/// `nonisolated` for `CalendarKey`'s reason: every member would otherwise be+/// main-actor bound under this target's default isolation, and the stdlib+/// conformances with them.+nonisolated struct LaunchPhaseRecord: Equatable, Sendable {++    /// The phases of a launch, in the order `bootstrap()` runs them.+    ///+    /// They do not tile the interval and are not meant to: a UI-test fixture+    /// seeding sits between `storeOpen` and `captureDrain` and belongs to+    /// neither, as does the teardown of a repository this model already held.+    /// The total is measured, never summed.+    enum Phase: String, CaseIterable, Sendable {+        /// Pre-empting an in-flight background-export pass, which Req 1.1 names+        /// as part of the launch rather than as something before it.+        case exportPassWait = "ExportPassWait"+        case storeOpen = "StoreOpen"+        case captureDrain = "CaptureDrain"+        /// `publishToday()`, and the `refreshAll()` fallback where it published+        /// nothing.+        case todayReads = "TodayReads"+    }++    /// How the launch ended, at the moment `state` left `.loading`.+    enum Outcome: String, CaseIterable, Sendable {+        /// `publishToday()` published Today: the path Req 2.1 describes.+        case published+        /// It did not, and the `refreshAll()` fallback published instead.+        case fellBack+        /// Neither published. `.ready` then shows what it always showed in that+        /// case and the launch tail is the next attempt (Q20), which is exactly+        /// why this outcome is worth naming.+        case nothing+        /// The open failed, so the reader has the unavailable screen.+        case unavailable+    }++    /// Where a phase sat in the launch and what it cost. `start` is measured+    /// from the launch's own start, which is what makes the *order* of the+    /// phases — and the gaps between them — readable from the record alone.+    struct Span: Equatable, Sendable {+        let start: Duration+        let duration: Duration+        var end: Duration { start + duration }+    }++    private(set) var outcome: Outcome?+    /// The whole interval, measured rather than summed, and nil until the+    /// launch ends.+    private(set) var total: Duration?++    private var spans: [Phase: Span] = [:]+    private var open: [Phase: Duration] = [:]++    func span(_ phase: Phase) -> Span? { spans[phase] }++    mutating func begin(_ phase: Phase, at elapsed: Duration) {+        open[phase] = elapsed+    }++    /// Closes `phase`. A phase that was never begun records nothing rather than+    /// a span starting at the launch's start, which would read as a phase that+    /// ran when it did not.+    mutating func end(_ phase: Phase, at elapsed: Duration) {+        guard let start = open.removeValue(forKey: phase) else { return }+        spans[phase] = Span(start: start, duration: elapsed - start)+    }++    mutating func finish(_ outcome: Outcome, at elapsed: Duration) {+        self.outcome = outcome+        total = elapsed+    }++    /// The notice line's body: the outcome, the four phases and the total, in+    /// milliseconds.+    ///+    /// Numbers and one word, so the line is readable in `Personal` builds too —+    /// a launch says nothing about what the reader has captured, and the split+    /// `PipelineLog` draws does not have to be drawn here.+    var logLine: String {+        let phases = Phase.allCases+            .map { "\($0.rawValue) \(Self.describe(spans[$0]?.duration))" }+            .joined(separator: ", ")+        return "Launch to Today: \(outcome?.rawValue ?? "unfinished")"+            + " in \(Self.describe(total)) (\(phases))"+    }++    /// A phase that never ended, or a launch that never did, is reported as+    /// absent rather than as zero: the two say different things to whoever is+    /// reading a launch that went wrong.+    private static func describe(_ duration: Duration?) -> String {+        guard let duration else { return "n/a" }+        return "\(PipelineLog.milliseconds(duration)) ms"+    }+}++/// A launch being measured: the signpost intervals as they are emitted, and the+/// record they are written into.+///+/// One `OSSignposter` on `M2PerformanceSignposts`' subsystem and category, so a+/// launch sits in the same Instruments track as the `TodayPresentation` read it+/// contains. Not gated on the configuration — `Personal` is the build whose+/// launch time means anything (design, §Measurement).+struct LaunchMeasurement {+    private static let signposter = OSSignposter(+        subsystem: M2PerformanceSignposts.subsystem,+        category: M2PerformanceSignposts.category)+    private static let logger = Logger(subsystem: "me.nore.ig.Asterism", category: "Launch")++    private let startedAt: ContinuousClock.Instant+    private let signpostID: OSSignpostID+    private let interval: OSSignpostIntervalState+    private var openIntervals: [LaunchPhaseRecord.Phase: OSSignpostIntervalState] = [:]+    private(set) var record = LaunchPhaseRecord()++    init() {+        startedAt = .now+        signpostID = Self.signposter.makeSignpostID()+        interval = Self.signposter.beginInterval("LaunchToToday", id: signpostID)+    }++    mutating func begin(_ phase: LaunchPhaseRecord.Phase) {+        openIntervals[phase] = Self.signposter.beginInterval(Self.name(of: phase), id: signpostID)+        record.begin(phase, at: elapsed)+    }++    mutating func end(_ phase: LaunchPhaseRecord.Phase) {+        guard let state = openIntervals.removeValue(forKey: phase) else { return }+        Self.signposter.endInterval(Self.name(of: phase), state)+        record.end(phase, at: elapsed)+    }++    /// Ends the launch interval and writes the one line that makes a launch+    /// readable in Console without Instruments. `.notice`, not `.debug`: a+    /// launch has to survive in the log to be looked up afterwards.+    mutating func finish(_ outcome: LaunchPhaseRecord.Outcome) -> LaunchPhaseRecord {+        record.finish(outcome, at: elapsed)+        Self.signposter.endInterval(+            "LaunchToToday", interval, "\(outcome.rawValue, privacy: .public)")+        let line = record.logLine+        Self.logger.notice("\(line, privacy: .public)")+        return record+    }++    private var elapsed: Duration { startedAt.duration(to: .now) }++    /// `OSSignposter` takes a `StaticString`, which a raw value is not, so the+    /// four names are spelled twice and this is where the two spellings meet.+    private static func name(of phase: LaunchPhaseRecord.Phase) -> StaticString {+        switch phase {+        case .exportPassWait: "ExportPassWait"+        case .storeOpen: "StoreOpen"+        case .captureDrain: "CaptureDrain"+        case .todayReads: "TodayReads"+        }+    }+}
Asterism/Asterism/Views/TodayView.swift Modified +21 / -33
diff --git a/Asterism/Asterism/Views/TodayView.swift b/Asterism/Asterism/Views/TodayView.swiftindex 074d9baa..6ea8c712 100644--- a/Asterism/Asterism/Views/TodayView.swift+++ b/Asterism/Asterism/Views/TodayView.swift@@ -95,10 +95,6 @@ struct TodayView: View {     /// tree, where the entry is a pushed screen and there is no list beside it     /// to mark.     let selectedEntryID: UUID?-    /// `ipad-and-mac-layouts` Req 6.1: ⌘F. A token watched for a *change*, like-    /// the actionable filter above — focusing an already-focused field is a-    /// real request, so a `Bool` could not express the second one.-    let searchFocusRequest: Int     /// Req 3.1: false in the wide tree, where the window paints one sky behind     /// every column and a second layer here would be a column painting its own.     let showsSky: Bool@@ -110,9 +106,6 @@ struct TodayView: View {      @State private var showingActionableOnly = false     @State private var showingDuplicatesOnly = false-    /// Req 3.1's query, beside the banner filters because it composes with them-    /// rather than replacing them (3.2, Q6).-    @State private var searchQuery = ""      init(         presentation: TodayPresentation,@@ -131,7 +124,6 @@ struct TodayView: View {         conflictCount: Int = 0,         actionableFilterRequest: Int = 0,         selectedEntryID: UUID? = nil,-        searchFocusRequest: Int = 0,         showsSky: Bool = true,         onSelect: @escaping (UUID) -> Void,         onTeach: ((UUID) -> Void)? = nil,@@ -156,7 +148,6 @@ struct TodayView: View {         self.conflictCount = conflictCount         self.actionableFilterRequest = actionableFilterRequest         self.selectedEntryID = selectedEntryID-        self.searchFocusRequest = searchFocusRequest         self.showsSky = showsSky         self.onSelect = onSelect         self.onTeach = onTeach@@ -170,10 +161,6 @@ struct TodayView: View {         self.onPruneSelection = onPruneSelection     } -    private var searchFilter: RecentSearchFilter {-        RecentSearchFilter(query: searchQuery)-    }-     /// Which day is shown (Q32), resolved by the selection itself so that this     /// screen and `AppNavigation` cannot answer differently.     private var selectedDay: CivilDay { selection.day(currentDay: currentDay) }@@ -197,7 +184,6 @@ struct TodayView: View {             calendar: calendar,             showingActionableOnly: showingActionableOnly,             showingDuplicatesOnly: showingDuplicatesOnly,-            searchFilter: searchFilter,             conflictCount: conflictCount,             // Req 10.1's prune is the wide tree's (Q43); the phone passes no             // closure and has no use for the sets.@@ -206,9 +192,10 @@ struct TodayView: View {      var body: some View {         let plan = displayPlan-        // Req 4.1's order as Q76 and Q78 left it, top to bottom: the search-        // field, the week widget, the banners, then the sections. No-        // page title and no date caption — the strip names the day.+        // Req 4.1's order as Q76 and Q78 left it, top to bottom: the week+        // widget, the banners, then the sections — the search field that led+        // them went with `launch-to-today` Req 5.1. No page title and no date+        // caption — the strip names the day.         //         // The banner region sits **above** the empty-library branch (Q15). Two         // Site rows with no Entries yet — the first-sync shape — produce a@@ -229,7 +216,7 @@ struct TodayView: View {         // title and the headers lose it (and the caption went with Q78). What         // each tree puts on its own chrome is the tree's: the compact one sets         // an empty inline title so the bar collapses rather than leaving a-        // large-title gap above the search field, and the wide one heads its+        // large-title gap above the week widget, and the wide one heads its         // list column with the tab's name. Neither is derived from a day any         // more.         // Requirement 8.1's fixed layer. On the screen's own root rather than@@ -238,15 +225,8 @@ struct TodayView: View {         // never reaches the screen (verified in the simulator — pure black).         // In the wide tree the window owns it instead (Req 3.1).         .screenSky(showsSky)-        // On the VStack, not the List: the List is swapped out for the empty-        // branches, and a search field attached to it would go with them.-        //-        // Through the seam rather than `.searchable` directly (design §Platform-        // seams): macOS has no in-content `SearchFieldPlacement` at all, so the-        // Mac draws `ColumnSearchField` under the column title instead. Both-        // arms own the `@FocusState` that ⌘F moves focus with.-        .listSearch(-            text: $searchQuery, prompt: "Search notes", focusRequest: searchFocusRequest)+        // No search field (`launch-to-today` Req 5.1, Decision 1): Today is a+        // dashboard. The filter stays in the plan, unreachable until T-2347.         .onChange(of: presentation.actionableCount) { _, newCount in             if newCount == 0 {                 showingActionableOnly = false@@ -282,7 +262,7 @@ struct TodayView: View {     /// above it (Q69).     ///     /// The accessibility sizes, and only there: at `AccessibilityXXXL` the-    /// search field, the week row, the wrapped strip and a banner want more+    /// week row, the wrapped strip and a banner want more     /// height than the window has, so a fixed `VStack` compresses them into     /// each other and leaves the `List` a sliver no gesture can empty. Below     /// that the chrome fits, and staying fixed is what keeps the day selector@@ -590,11 +570,16 @@ struct TodayView: View {         }     } -    /// Req 3.4's message. Distinct from `emptyBranch`, which describes a library-    /// with nothing in it — this one describes a query with nothing behind it,-    /// and the difference matters to a reader who has just typed.+    /// `update-schedule` Req 3.4's message, describing a query with nothing+    /// behind it rather than a library with nothing in it (`emptyBranch`).+    ///+    /// **Unreachable since `launch-to-today` Req 5.1 took the search field off+    /// Today**: the plan's `searchFilter` now defaults to the inactive filter+    /// and this view is its only production caller, so no `.searchMiss` is+    /// produced. Kept beside the filter it belongs to, which Req 5.4 holds for+    /// T-2347; it renders again the moment a query can reach the plan.     private var searchEmptyBranch: some View {-        ContentUnavailableView.search(text: searchQuery)+        ContentUnavailableView.search             .accessibilityIdentifier("recent-search-empty")     } @@ -993,7 +978,10 @@ struct TodayDisplayPlan {         calendar: Calendar,         showingActionableOnly: Bool,         showingDuplicatesOnly: Bool,-        searchFilter: RecentSearchFilter,+        /// Defaulted to the inactive filter since `launch-to-today` Req 5.1 took+        /// the field off Today: the view passes none, and the path stays for+        /// T-2347 and the tests that drive it (Req 5.4).+        searchFilter: RecentSearchFilter = RecentSearchFilter(query: ""),         conflictCount: Int,         /// Whether ``visibility`` is wanted at all — true exactly when the         /// caller passed an `onPruneSelection`. Defaulted false so a test that
Asterism/AsterismTests/AppLibraryModelBackgroundExportTests.swift Modified +31 / -0
diff --git a/Asterism/AsterismTests/AppLibraryModelBackgroundExportTests.swift b/Asterism/AsterismTests/AppLibraryModelBackgroundExportTests.swiftindex 8c9fbace..a758b69c 100644--- a/Asterism/AsterismTests/AppLibraryModelBackgroundExportTests.swift+++ b/Asterism/AsterismTests/AppLibraryModelBackgroundExportTests.swift@@ -373,6 +373,37 @@ struct AppLibraryModelBackgroundExportTests {         #expect(model.backgroundSession == nil)     } +    /// `launch-to-today` Req 1.1: the launch interval covers the wait for an+    /// in-flight pass, and nothing opens the store until that pass has stopped.+    ///+    /// Asserted on the phase record the notice line is built from, because the+    /// *order* is what the requirement claims and the record is the only place+    /// it is visible from outside — a signpost is not readable from a test.+    @Test("The launch record puts the export-pass wait before the store open")+    func theLaunchRecordPutsTheExportWaitBeforeTheStoreOpen() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        let configuration = configuration(mirroring: true, at: root)+        try mark(configuration)++        let model = AppLibraryModel(configuration: configuration)+        model.mirroringOpenHooks = countingHooks(ContainerFactoryLog())++        let pass = Task { await model.runBackgroundExport() }+        _ = try #require(await coldMonitor(of: model))+        await model.bootstrap()+        _ = await pass.value++        let record = try #require(model.launchRecord)+        let wait = try #require(record.span(.exportPassWait))+        let open = try #require(record.span(.storeOpen))+        let total = try #require(record.total)+        #expect(wait.duration > .zero, "a pass was in flight, so the wait cost something")+        #expect(open.start >= wait.end, "and the store waited for it")+        #expect(total >= open.end, "the interval covers both")+        #expect(record.outcome == .published)+    }+     @Test("A pass arriving during a bootstrap skips as opening")     func aPassDuringABootstrapSkipsAsOpening() async throws {         let root = tempRoot()
Asterism/AsterismTests/AppLibraryModelTests.swift Modified +458 / -15
diff --git a/Asterism/AsterismTests/AppLibraryModelTests.swift b/Asterism/AsterismTests/AppLibraryModelTests.swiftindex 77d99eab..fb7efafb 100644--- a/Asterism/AsterismTests/AppLibraryModelTests.swift+++ b/Asterism/AsterismTests/AppLibraryModelTests.swift@@ -35,6 +35,9 @@ struct AppLibraryModelTests {         )         let model = AppLibraryModel(configuration: config)         await model.bootstrap()+        // The works snapshot arrives in the launch tail now, so an assertion+        // about an *empty library* has to wait for the load that says so.+        await model.waitForLaunchTail()         #expect(model.state == .ready)         #expect(model.todayGroups.isEmpty)         #expect(model.worksSnapshot.works.isEmpty)@@ -42,6 +45,43 @@ struct AppLibraryModelTests {         try? FileManager.default.removeItem(at: root)     } +    /// `launch-to-today` Req 1.2: one launch is enough to say where its time+    /// went, so every phase it ran has to be on the record it leaves behind.+    @Test("A launch that publishes Today records its four phases and that outcome")+    @MainActor func aLaunchRecordsItsPhasesAndOutcome() async throws {+        let root = FileManager.default.temporaryDirectory+            .appending(path: "asterism-launch-record-\(UUID())")+        defer { try? FileManager.default.removeItem(at: root) }+        let model = AppLibraryModel(configuration: LibraryConfiguration(rootDirectory: root))++        await model.bootstrap()+        await model.waitForLaunchTail()++        let record = try #require(model.launchRecord)+        #expect(record.outcome == .published)+        for phase in LaunchPhaseRecord.Phase.allCases {+            #expect(record.span(phase) != nil, "\(phase.rawValue) ran, so it is on the record")+        }+        let total = try #require(record.total)+        let reads = try #require(record.span(.todayReads))+        #expect(total >= reads.end, "the interval ends where `state` leaves `.loading`")+    }++    /// Req 1.1's other end: a launch that never reached a store still ends, and+    /// the outcome is what says so.+    @Test("A launch that cannot open the library records the unavailable outcome")+    @MainActor func anUnavailableLaunchRecordsThatOutcome() async throws {+        let model = AppLibraryModel(+            appGroupIdentifier: Self.fixtureAppGroup, locator: FailingLocator())++        await model.bootstrap()++        let record = try #require(model.launchRecord)+        #expect(record.outcome == .unavailable)+        #expect(record.span(.storeOpen) == nil, "no store was opened to time")+        #expect(record.total != nil)+    }+     /// The two model coordinators are built over the repository that just     /// opened, and `ContentView` reaches them through this model on every     /// resign-active and memory warning — whether or not a library is open. A@@ -199,6 +239,7 @@ struct AppLibraryModelTests {         try? seedReadyLibrary(for: config)         let model = AppLibraryModel(configuration: config)         await model.bootstrap()+        await model.waitForLaunchTail()         #expect(model.state == .ready)          // Initially empty@@ -685,17 +726,28 @@ struct AppLibraryModelSyncArrivalTests {      // MARK: - The launch reconcile (Q45) +    /// The tail's works load runs first and is the only thing that clears+    /// `worksLoad` (`launch-to-today` Decision 4), so a case about what the+    /// *outcome* makes the reconcile do has to stand behind one — otherwise the+    /// refresh it sees is the one a failed load is owed (Req 3.7).+    private static func loadedModel(_ mock: MockLibraryProvider) async -> AppLibraryModel {+        let model = AppLibraryModel(readyRepository: mock)+        await model.refreshAll()+        mock.callLog.removeAll()+        return model+    }+     @Test("The launch reconcile runs once per launch and skips the refresh when it changed nothing")     func launchReconcileRunsOnceAndSkipsAnEmptyPass() async {         let mock = MockLibraryProvider()-        let model = AppLibraryModel(readyRepository: mock)+        let model = await Self.loadedModel(mock)          await model.runLaunchReconcile()         await model.runLaunchReconcile()          #expect(mock.reconcileAfterSyncCallCount == 1)-        // The open published Recent moments before; re-reading it for a pass-        // that wrote nothing would repeat the open's work for no change.+        // The tail published moments before; re-reading for a pass that wrote+        // nothing would repeat that work for no change.         #expect(mock.callLog == ["reconcileAfterSync"])         #expect(model.launchReconcileCompleted)     }@@ -707,7 +759,7 @@ struct AppLibraryModelSyncArrivalTests {         outcome.site.consolidatedHostnames = ["example.test"]         outcome.site.repinnedRecords = 3         mock.reconcileAfterSyncResult = .success(outcome)-        let model = AppLibraryModel(readyRepository: mock)+        let model = await Self.loadedModel(mock)          await model.runLaunchReconcile() @@ -725,12 +777,12 @@ struct AppLibraryModelSyncArrivalTests {          // Ready, with Recent published, and the reconcile has not run: the open         // does not pay for it, and nothing waits on it (Req 6.4). The pass-        // cannot have completed here — its first step is a call into the-        // repository actor, which suspends.+        // cannot have completed here — the tail's first works load comes before+        // it (`launch-to-today` Decision 4), and that read suspends.         #expect(model.state == .ready)         #expect(!model.launchReconcileCompleted) -        await model.waitForLaunchReconcile()+        await model.waitForLaunchTail()          #expect(model.launchReconcileCompleted)         #expect(model.state == .ready)@@ -1001,10 +1053,12 @@ struct AppLibraryModelSnapshotPublicationTests {         #expect(model.snapshotGeneration == 1)     } -    /// Q28's claim, asserted: the schedule is derived from the same cycle's-    /// works snapshot and published in the same block as the presentation, so a-    /// reader never holds one cycle's rows beside another cycle's dots.-    @Test("The schedule publishes in the same cycle as the presentation")+    /// `launch-to-today` Decision 2, superseding Q28: the schedule is the+    /// presentation's own, built under the same lock as the rows rather than+    /// derived in the app from the works snapshot beside them — so a reader never+    /// holds one cycle's rows beside another cycle's dots, and Today needs+    /// nothing from `works()`.+    @Test("The schedule published is the presentation's own")     func theScheduleAndThePresentationPublishTogether() async {         let mock = MockLibraryProvider()         var calendar = Calendar(identifier: .gregorian)@@ -1017,19 +1071,20 @@ struct AppLibraryModelSnapshotPublicationTests {          let scheduled = TestFixtures.makeWork(             displayTitle: "Scheduled Work", releaseDays: [.monday, .thursday])+        let schedule = TodaySchedule.build(works: [scheduled], calendar: calendar)+        mock.todayPresentationResult = .success(+            TodayPresentation(groups: [], actionableCount: 0, schedule: schedule))         mock.worksResult = .success(             WorksSnapshot(works: [scheduled], unattachedEntries: []))          await model.refreshAll()          #expect(model.snapshotGeneration == 1)-        // The same cycle's works snapshot, and the schedule derived from it.+        // One cycle's works snapshot, and that cycle's presentation's schedule.         #expect(model.worksSnapshot.works.map(\.id) == [scheduled.id])+        #expect(model.todaySchedule == schedule)         #expect(model.todaySchedule.works.map(\.id) == [scheduled.id])         #expect(model.todaySchedule.dueWeekdays == Set([.monday, .thursday]))-        #expect(-            model.todaySchedule-                == TodaySchedule.build(works: model.worksSnapshot.works, calendar: calendar))     }      /// Q44's gate: the cycle read the library under one calendar and the@@ -1090,6 +1145,394 @@ struct AppLibraryModelSnapshotPublicationTests {     } } +// MARK: - The two launch publications and the launch tail (`launch-to-today`)++/// A works read that fails on demand (Q17), passed as the init parameter a+/// UI-test launch resolves its environment key to.+///+/// Counted rather than a plain flag: the launch tail retries an attempt that was+/// abandoned and the reconcile retries one that failed, so "fail the first+/// attempt and no other" is a case of its own.+@MainActor+private final class WorksReadFault {+    struct Faulted: Error {}++    var remaining: Int++    init(failures: Int) { remaining = failures }++    func fire() throws {+        guard remaining > 0 else { return }+        remaining -= 1+        throw Faulted()+    }+}++/// A calendar that moves partway through a launch, for the one publication with+/// no seam inside it to move it from.+///+/// `publishToday()` reads the source twice — once at entry, once at the abandon+/// gate — and the model's construction reads it once before either, so three+/// reads span the launch publication and a count says where the change lands.+/// The case's own assertions are what confirm it landed there.+@MainActor+private final class MovingCalendarSource {+    private let before: Calendar+    private let after: Calendar+    private var readsLeft: Int++    init(before: Calendar, after: Calendar, readsBeforeTheChange: Int) {+        self.before = before+        self.after = after+        readsLeft = readsBeforeTheChange+    }++    func read() -> Calendar {+        guard readsLeft > 0 else { return after }+        readsLeft -= 1+        return before+    }+}++/// Decisions 3 and 4: `bootstrap()` publishes Today from its own read and leaves+/// the works snapshot to the launch tail, which loads it and only then runs the+/// reconcile.+///+/// The cases that need a library drive a real `bootstrap()` over a disposable+/// root through the debug initializer — the path `ContentView` takes for a+/// UI-test launch, and the only one that reaches `publishToday()`. The cases+/// about *when* a cycle may publish drive the injected repository instead, which+/// is the only read with a seam inside it.+@Suite("AppLibraryModel launch")+@MainActor+struct AppLibraryModelLaunchTests {++    private static func temporaryRoot() -> URL {+        FileManager.default.temporaryDirectory.appending(path: "asterism-launch-\(UUID())")+    }++    /// The `.untaught` fixture is one capture and one work — enough for a works+    /// snapshot that is distinguishable from the empty default, and cheap.+    private static func launchedModel(+        at root: URL,+        fixture: UITestFixtureKind = .untaught,+        calendarSource: @escaping @MainActor () -> Calendar = { Calendar.current },+        worksReadFault: (@MainActor () throws -> Void)? = nil+    ) -> AppLibraryModel {+        AppLibraryModel(+            configuration: LibraryConfiguration(rootDirectory: root),+            uiTestFixture: fixture,+            calendarSource: calendarSource,+            worksReadFault: worksReadFault)+    }++    // MARK: - The two publications++    /// Req 2.1 and Req 3.1: Today is on screen from its own read, and the works+    /// snapshot follows with no reader action.+    @Test("Today is ready before the works snapshot loads, and the tail loads it")+    func todayIsReadyBeforeTheWorksSnapshotLoads() async {+        let root = Self.temporaryRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        let model = Self.launchedModel(at: root)++        await model.bootstrap()++        // The tail is scheduled here and has not run a line of itself:+        // `bootstrap()` suspends nowhere after scheduling it, so this is exactly+        // the state a reader is handed at launch.+        #expect(model.state == .ready)+        #expect(model.worksLoad == .loading)+        #expect(model.snapshotGeneration == 1)+        #expect(!model.todayGroups.isEmpty, "Today drew from its own read")+        #expect(+            model.worksSnapshot.works.isEmpty,+            "not loaded yet — the gate is what tells this from an empty library (Req 3.3)")++        await model.waitForLaunchTail()++        #expect(model.state == .ready)+        #expect(model.worksLoad == .loaded)+        #expect(model.snapshotGeneration == 2, "one publication for Today, one for the works load")+        #expect(!model.worksSnapshot.works.isEmpty)+    }++    /// Q16 and Req 2.3: the schedule and the title map published at launch are+    /// the ones the works load republishes, so nothing on Today moves when it+    /// lands and a restored selection resolves the same way against either.+    @Test("The schedule and the work titles are the same at both launch publications")+    func theScheduleAndTitlesAreTheSameAtBothPublications() async throws {+        let root = Self.temporaryRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        // The fixture with a schedule worth comparing: two works due on a day,+        // one kept off it by its status, one being caught up on.+        let model = Self.launchedModel(at: root, fixture: .today)++        await model.bootstrap()++        let scheduleAtLaunch = model.todaySchedule+        let titlesAtLaunch = model.workTitlesByID+        #expect(!scheduleAtLaunch.works.isEmpty)+        #expect(!scheduleAtLaunch.catchingUp.isEmpty)+        #expect(titlesAtLaunch.count == 4)++        await model.waitForLaunchTail()++        #expect(model.worksLoad == .loaded)+        #expect(model.todaySchedule == scheduleAtLaunch)+        #expect(model.workTitlesByID == titlesAtLaunch)+        // Req 3.5's prune resolves a restored work against the map it finds, and+        // there is only one map to find at either publication.+        let restored = try #require(model.worksSnapshot.works.first?.id)+        #expect(titlesAtLaunch[restored] != nil)+        #expect(model.workTitlesByID[restored] == titlesAtLaunch[restored])+    }++    /// Req 2.5: the day moved between the two launch publications, and the works+    /// snapshot arriving afterwards describes the new one rather than restoring+    /// the earlier one.+    @Test("A calendar change between the two publications carries into the works publication")+    func aCalendarChangeBetweenThePublicationsCarriesForward() async {+        let root = Self.temporaryRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        var before = Calendar(identifier: .gregorian)+        before.timeZone = TimeZone(identifier: "Europe/Amsterdam") ?? .gmt+        var after = before+        after.timeZone = TimeZone(identifier: "Asia/Tokyo") ?? .gmt+        let inForce = CalendarInForce(before)+        let model = Self.launchedModel(at: root, calendarSource: { inForce.calendar })++        await model.bootstrap()+        #expect(model.calendar == before)++        // The zone changes while the tail is scheduled and has read nothing.+        inForce.calendar = after+        await model.waitForLaunchTail()++        #expect(model.worksLoad == .loaded)+        #expect(model.calendar == after)+        #expect(model.currentDay == CivilDay(Date(), calendar: after))+    }++    /// Q20: a Today publication abandoned at the calendar gate falls back to the+    /// full refresh the app used to open with, before `.ready`.+    @Test("An abandoned Today publication falls back to the full refresh before ready")+    func anAbandonedTodayPublicationFallsBackToTheFullRefresh() async {+        let root = Self.temporaryRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        var before = Calendar(identifier: .gregorian)+        before.timeZone = TimeZone(identifier: "Europe/Amsterdam") ?? .gmt+        var after = before+        after.timeZone = TimeZone(identifier: "Asia/Tokyo") ?? .gmt+        // The model's construction and the Today publication's entry read the+        // old calendar; the gate's read — the third — reads the new one.+        let source = MovingCalendarSource(before: before, after: after, readsBeforeTheChange: 2)+        let model = Self.launchedModel(at: root, calendarSource: { source.read() })++        await model.bootstrap()++        #expect(model.state == .ready)+        // Only a full refresh sets `.loaded`, so this is what says the Today+        // publication was abandoned and the fallback published in its place.+        #expect(model.worksLoad == .loaded)+        #expect(model.snapshotGeneration == 1, "one publication reached the reader, not two")+        #expect(model.calendar == after)+        #expect(!model.worksSnapshot.works.isEmpty)+    }++    // MARK: - A failed first load (Reqs 3.6, 3.7)++    @Test("A faulted works read fails the load and leaves Today standing")+    func aFaultedWorksReadFailsTheLoad() async {+        let root = Self.temporaryRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        let fault = WorksReadFault(failures: .max)+        let model = Self.launchedModel(at: root, worksReadFault: { try fault.fire() })++        await model.bootstrap()+        #expect(model.worksLoad == .loading)++        await model.waitForLaunchTail()++        #expect(model.worksLoad == .failed)+        #expect(model.worksSnapshot.works.isEmpty)+        #expect(model.state == .ready)+        #expect(!model.todayGroups.isEmpty, "Today is unaffected by the works read (Req 3.6)")+    }++    /// The Retry action, and the one caller that clears the injected fault (Q17).+    @Test("Retrying the works load clears the fault and reaches loaded")+    func retryClearsTheFaultAndLoads() async {+        let root = Self.temporaryRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        let fault = WorksReadFault(failures: .max)+        let model = Self.launchedModel(at: root, worksReadFault: { try fault.fire() })+        await model.bootstrap()+        await model.waitForLaunchTail()+        #expect(model.worksLoad == .failed)++        await model.retryWorksLoad()++        #expect(model.worksLoad == .loaded)+        #expect(!model.worksSnapshot.works.isEmpty)+    }++    /// Req 3.7's other half: every later refresh is an attempt, and none of them+    /// resets `.failed` first — a successful one is what clears it.+    @Test("An unrelated later refresh clears the failure")+    func anUnrelatedRefreshClearsTheFailure() async {+        let root = Self.temporaryRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        let fault = WorksReadFault(failures: .max)+        let model = Self.launchedModel(at: root, worksReadFault: { try fault.fire() })+        await model.bootstrap()+        await model.waitForLaunchTail()+        #expect(model.worksLoad == .failed)++        // Whatever made the read fail has gone, and the refresh is an ordinary+        // one: an activation's, an arrival's, a committed change's.+        fault.remaining = 0+        await model.refreshAll()++        #expect(model.worksLoad == .loaded)+        #expect(!model.worksSnapshot.works.isEmpty)+    }++    /// Decision 4: `runLaunchReconcile()` refreshes when the first load failed,+    /// so a failure is retried once the pass has released the lock — even when+    /// the pass itself changed nothing.+    @Test("A first load that failed is retried by the reconcile behind it")+    func theLaunchTailRetriesAFailedFirstLoad() async {+        let root = Self.temporaryRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        let fault = WorksReadFault(failures: 1)+        let model = Self.launchedModel(at: root, worksReadFault: { try fault.fire() })++        await model.bootstrap()+        await model.waitForLaunchTail()++        #expect(fault.remaining == 0, "the first attempt is the one that was faulted")+        #expect(model.worksLoad == .loaded)+        #expect(!model.worksSnapshot.works.isEmpty)+    }++    // MARK: - A library released mid-load (Req 3.8)++    @Test("A read abandoned by a teardown publishes nothing and is not a failure")+    func anAbandonedReadPublishesNothingAndIsNotAFailure() async {+        let mock = MockLibraryProvider()+        mock.worksResult = .success(+            WorksSnapshot(+                works: [TestFixtures.makeWork(displayTitle: "Released Library Work")],+                unattachedEntries: []))+        let model = AppLibraryModel(readyRepository: mock)+        // The re-open lands inside the read, which is the window Req 3.8 names.+        // This model resolves no configuration, so the second bootstrap releases+        // the library and then fails — nothing publishes over the abandoned read+        // to mask it.+        mock.duringTodayPresentation = { [model] in await model.bootstrap() }++        await model.refreshAll()++        #expect(model.snapshotGeneration == 0)+        #expect(model.worksSnapshot.works.isEmpty)+        #expect(model.worksLoad == .loading, "abandoned, not failed")+    }++    /// Decision 4's guards: a cancelled tail does not take the exclusive lock+    /// inside the open that replaced it, and does not consume its once-per-launch+    /// flag.+    @Test("A torn-down launch tail runs no reconcile")+    func aTornDownLaunchTailRunsNoReconcile() async {+        let mock = MockLibraryProvider()+        let model = AppLibraryModel(readyRepository: mock)+        mock.duringTodayPresentation = { [model] in await model.bootstrap() }++        model.scheduleLaunchTail()+        await model.waitForLaunchTail()++        #expect(mock.reconcileAfterSyncCallCount == 0)+        #expect(!model.launchReconcileCompleted)+        #expect(model.worksLoad == .loading)+    }++    // MARK: - The tail's order (Reqs 3.9, 3.10)++    @Test("The launch reconcile follows the first works load")+    func theReconcileFollowsTheFirstWorksLoad() async {+        let mock = MockLibraryProvider()+        let model = AppLibraryModel(readyRepository: mock)++        model.scheduleLaunchTail()+        await model.waitForLaunchTail()++        // Order, not merely occurrence: the reader can be waiting on Works and+        // the reconcile's worst case is a 5,000-record re-pin under the+        // exclusive lock.+        #expect(mock.callLog == ["todayPresentation", "works", "siteNames", "reconcileAfterSync"])+        #expect(model.worksLoad == .loaded)+        #expect(model.launchReconcileCompleted)+    }++    /// Q21: an attempt abandoned at the calendar gate has published nothing and+    /// has no publisher of its own at that instant, so the tail makes one further+    /// attempt — and the reconcile still follows it. Two attempts is the bound.+    @Test("An attempt abandoned at the calendar gate is retried before the reconcile")+    func theTailRetriesOnceAfterACalendarAbandon() async {+        let mock = MockLibraryProvider()+        var before = Calendar(identifier: .gregorian)+        before.timeZone = TimeZone(identifier: "Europe/Amsterdam") ?? .gmt+        var after = before+        after.timeZone = TimeZone(identifier: "Asia/Tokyo") ?? .gmt+        let inForce = CalendarInForce(before)+        let model = AppLibraryModel(readyRepository: mock, calendarSource: { inForce.calendar })+        // Captured by value: the hook is `@Sendable`, and a `var` reached+        // through it is an error under the Swift 6 language mode.+        mock.duringTodayPresentation = { [after] in inForce.calendar = after }++        model.scheduleLaunchTail()+        await model.waitForLaunchTail()++        #expect(+            mock.callLog == [+                "todayPresentation", "works", "siteNames",+                "todayPresentation", "works", "siteNames",+                "reconcileAfterSync",+            ])+        #expect(model.worksLoad == .loaded)+        #expect(model.snapshotGeneration == 1, "the abandoned attempt published nothing")+    }++    /// Req 3.9: a refresh entering during the first works load and the load+    /// itself cannot both publish, and the older pair never replaces the newer.+    @Test("Two refreshes entered at the same generation during the first load publish once")+    func onlyOneOfTwoOverlappingRefreshesPublishes() async {+        let mock = MockLibraryProvider()+        let olderWorks = WorksSnapshot(+            works: [TestFixtures.makeWork(displayTitle: "Older Work")], unattachedEntries: [])+        let newerWorks = WorksSnapshot(+            works: [TestFixtures.makeWork(displayTitle: "Newer Work")], unattachedEntries: [])+        mock.worksResult = .success(olderWorks)+        let model = AppLibraryModel(readyRepository: mock)+        // A committed change refreshes while the first works load sits inside its+        // own presentation read. The store is put back afterwards, because the+        // overtaken cycle reads *after* this hook returns and what it would+        // publish has to be the older pair for the assertion to mean anything.+        mock.duringTodayPresentation = { [mock] in+            mock.worksResult = .success(newerWorks)+            await model.refreshAll()+            mock.worksResult = .success(olderWorks)+        }++        model.scheduleLaunchTail()+        await model.waitForLaunchTail()++        #expect(model.snapshotGeneration == 1, "exactly one of the two published")+        #expect(model.worksSnapshot == newerWorks)+        #expect(model.worksLoad == .loaded)+    }+}+ // MARK: - Preserved captures: drain invocation and the report's lifecycle  /// The app half of `pending-capture-queue`: where the drain runs, what the pass
Asterism/AsterismTests/CrossViewRefreshTests.swift Modified +9 / -0
diff --git a/Asterism/AsterismTests/CrossViewRefreshTests.swift b/Asterism/AsterismTests/CrossViewRefreshTests.swiftindex 5396f596..dcf37300 100644--- a/Asterism/AsterismTests/CrossViewRefreshTests.swift+++ b/Asterism/AsterismTests/CrossViewRefreshTests.swift@@ -23,6 +23,11 @@ private func publishV3ReadyForTests(for config: LibraryConfiguration) {  /// Tests for cross-view refresh: mutations in detail models trigger /// AppLibraryModel snapshot reload.+///+/// Every case here awaits `waitForLaunchTail()` after its bootstrap: the works+/// snapshot is published by the launch tail now (`launch-to-today` Decision 3),+/// and a tail still reading while the case mutates the store from a second+/// repository would leave what is asserted up to the interleaving. @Suite("CrossViewRefresh") struct CrossViewRefreshTests { @@ -33,6 +38,7 @@ struct CrossViewRefreshTests {         publishV3ReadyForTests(for: config)         let appModel = AppLibraryModel(configuration: config)         await appModel.bootstrap()+        await appModel.waitForLaunchTail()         #expect(appModel.state == .ready)          // Capture initial Recent snapshot@@ -51,6 +57,7 @@ struct CrossViewRefreshTests {         publishV3ReadyForTests(for: config)         let appModel = AppLibraryModel(configuration: config)         await appModel.bootstrap()+        await appModel.waitForLaunchTail()         #expect(appModel.state == .ready)         #expect(appModel.todayGroups.isEmpty) @@ -80,6 +87,7 @@ struct CrossViewRefreshTests {         publishV3ReadyForTests(for: config)         let appModel = AppLibraryModel(configuration: config)         await appModel.bootstrap()+        await appModel.waitForLaunchTail()          let repo = try! await LibraryRepository.openForExtension(config).repository         // Create two entries; first capture is older@@ -114,6 +122,7 @@ struct CrossViewRefreshTests {         publishV3ReadyForTests(for: config)         let appModel = AppLibraryModel(configuration: config)         await appModel.bootstrap()+        await appModel.waitForLaunchTail()          let repo = try! await LibraryRepository.openForExtension(config).repository         // Create an entry and assign it to a new work
Asterism/AsterismTests/IntegrationSafetyNetTests.swift Modified +5 / -0
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex 9d67d960..f26924e5 100644--- a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift+++ b/Asterism/AsterismTests/IntegrationSafetyNetTests.swift@@ -27,6 +27,10 @@ struct IntegrationSafetyNetTests {         let personalApp = AppLibraryModel(configuration: fixture.personalConfiguration)         await developmentApp.bootstrap()         await personalApp.bootstrap()+        // The works snapshot asserted below arrives in the launch tail+        // (`launch-to-today` Decision 3), and the capture happens between.+        await developmentApp.waitForLaunchTail()+        await personalApp.waitForLaunchTail()         #expect(developmentApp.state == .ready)         #expect(personalApp.state == .ready) @@ -206,6 +210,7 @@ struct IntegrationSafetyNetTests {                 )                  await app.bootstrap()+                await app.waitForLaunchTail()                 #expect(app.state == .ready)                 #expect(app.capabilities == capabilities) 
Asterism/AsterismTests/LaunchPhaseRecordTests.swift Added +117 / -0
diff --git a/Asterism/AsterismTests/LaunchPhaseRecordTests.swift b/Asterism/AsterismTests/LaunchPhaseRecordTests.swiftnew file mode 100644index 00000000..913f8136--- /dev/null+++ b/Asterism/AsterismTests/LaunchPhaseRecordTests.swift@@ -0,0 +1,117 @@+import Foundation+import Testing+@testable import Asterism++/// `launch-to-today` Reqs 1.1 and 1.2: the value a launch's signpost intervals+/// and its notice line are both built from.+///+/// Asserted here rather than through the log, which is the whole reason the+/// record is a plain value: nothing in the unified log is readable from a test,+/// and neither is a signpost. The durations are handed in rather than measured,+/// so the suite says nothing about how fast a launch is.+@Suite("Launch phase record")+struct LaunchPhaseRecordTests {+    private typealias Phase = LaunchPhaseRecord.Phase+    private typealias Outcome = LaunchPhaseRecord.Outcome++    /// One launch's worth of phases, with a 45 ms gap between the store open+    /// and the drain where a UI-test fixture seeding would sit.+    private func launch(endingIn outcome: Outcome = .published) -> LaunchPhaseRecord {+        var record = LaunchPhaseRecord()+        record.begin(.exportPassWait, at: .zero)+        record.end(.exportPassWait, at: .milliseconds(12))+        record.begin(.storeOpen, at: .milliseconds(14))+        record.end(.storeOpen, at: .milliseconds(355))+        record.begin(.captureDrain, at: .milliseconds(400))+        record.end(.captureDrain, at: .milliseconds(405))+        record.begin(.todayReads, at: .milliseconds(405))+        record.end(.todayReads, at: .milliseconds(1_217))+        record.finish(outcome, at: .milliseconds(1_218))+        return record+    }++    @Test("The phases are the launch's four, in the order bootstrap runs them")+    func thePhasesAreTheLaunchsFour() {+        #expect(+            Phase.allCases.map(\.rawValue)+                == ["ExportPassWait", "StoreOpen", "CaptureDrain", "TodayReads"])+    }++    @Test("Every phase records where it began and what it cost")+    func everyPhaseRecordsItsPlaceAndItsCost() throws {+        let record = launch()++        let open = try #require(record.span(.storeOpen))+        #expect(open.start == .milliseconds(14))+        #expect(open.duration == .milliseconds(341))+        #expect(open.end == .milliseconds(355))+        #expect(record.span(.exportPassWait)?.duration == .milliseconds(12))+        #expect(record.span(.captureDrain)?.duration == .milliseconds(5))+        #expect(record.span(.todayReads)?.duration == .milliseconds(812))+        #expect(record.total == .milliseconds(1_218))+    }++    /// The phases do not tile the interval, and the record must not pretend they+    /// do: a UI-test seeding belongs to none of them, so the total is measured+    /// rather than summed and the gap stays visible between two spans.+    @Test("The seeding between the store open and the drain belongs to no phase")+    func theSeedingGapBelongsToNoPhase() throws {+        let record = launch()++        let open = try #require(record.span(.storeOpen))+        let drain = try #require(record.span(.captureDrain))+        let total = try #require(record.total)+        let spent = Phase.allCases.compactMap { record.span($0)?.duration }+            .reduce(Duration.zero, +)++        #expect(drain.start - open.end == .milliseconds(45))+        #expect(spent < total, "the gap is the launch's, not any phase's")+    }++    @Test("The line carries the outcome, the four phases and the total in milliseconds")+    func theLineCarriesTheNumbersAndTheOutcome() {+        #expect(+            launch(endingIn: .fellBack).logLine == """+                Launch to Today: fellBack in 1218 ms (ExportPassWait 12 ms, \+                StoreOpen 341 ms, CaptureDrain 5 ms, TodayReads 812 ms)+                """)+    }++    @Test("Every outcome names itself in the line", arguments: LaunchPhaseRecord.Outcome.allCases)+    func everyOutcomeNamesItself(_ outcome: LaunchPhaseRecord.Outcome) {+        let record = launch(endingIn: outcome)++        #expect(record.outcome == outcome)+        #expect(record.logLine.contains("Launch to Today: \(outcome.rawValue) in"))+    }++    /// A launch that ended unavailable left a phase open. Reporting that as+    /// zero would read as a store that opened instantly; it is reported as+    /// absent instead.+    @Test("A phase that never ended has no span, and the line says so")+    func anUnendedPhaseIsAbsentRatherThanZero() {+        var record = LaunchPhaseRecord()+        record.begin(.exportPassWait, at: .zero)+        record.end(.exportPassWait, at: .milliseconds(3))+        record.begin(.storeOpen, at: .milliseconds(3))+        record.finish(.unavailable, at: .milliseconds(900))++        #expect(record.span(.storeOpen) == nil)+        #expect(+            record.logLine == """+                Launch to Today: unavailable in 900 ms (ExportPassWait 3 ms, \+                StoreOpen n/a, CaptureDrain n/a, TodayReads n/a)+                """)+    }++    @Test("A launch that has not ended has no outcome and no total")+    func anUnfinishedLaunchHasNeitherOutcomeNorTotal() {+        var record = LaunchPhaseRecord()+        record.begin(.exportPassWait, at: .zero)+        record.end(.exportPassWait, at: .milliseconds(7))++        #expect(record.outcome == nil)+        #expect(record.total == nil)+        #expect(record.logLine.hasPrefix("Launch to Today: unfinished in n/a"))+    }+}
Asterism/AsterismTests/NavigationActionsTests.swift Modified +49 / -8
diff --git a/Asterism/AsterismTests/NavigationActionsTests.swift b/Asterism/AsterismTests/NavigationActionsTests.swiftindex ea599995..9082e0c5 100644--- a/Asterism/AsterismTests/NavigationActionsTests.swift+++ b/Asterism/AsterismTests/NavigationActionsTests.swift@@ -8,26 +8,35 @@ import Testing /// /// `NavigationActions` is where that rule lives, as six optional closures — nil /// is the disabled state, so a command can never be enabled with nothing to do.-/// The gating is a pure function of the tab, the width and whether anything is-/// selected, which is what this suite pins.+/// The gating is a pure function of the tab, the width, whether the works+/// snapshot has loaded and whether anything is selected, which is what this+/// suite pins. @Suite("Navigation actions") @MainActor struct NavigationActionsTests {      /// The actions for one state of the app, with every closure a no-op: what     /// is under test is which of them exist.+    ///+    /// `worksLoaded` defaults to true, which is what every state but the first+    /// seconds of a launch looks like — so the cases below that do not mention+    /// the works load read exactly as they did before `launch-to-today`.     private static func actions(-        tab: AppTab, isWide: Bool = true, hasSelection: Bool = false+        tab: AppTab, isWide: Bool = true, worksLoaded: Bool = true, hasSelection: Bool = false     ) -> NavigationActions {-        actions(tab: tab, isWide: isWide, subject: hasSelection ? .entry(entryID) : nil)+        actions(+            tab: tab, isWide: isWide, worksLoaded: worksLoaded,+            subject: hasSelection ? .entry(entryID) : nil)     }      private static func actions(-        tab: AppTab, isWide: Bool = true, subject: MarkdownExportModel.Subject?+        tab: AppTab, isWide: Bool = true, worksLoaded: Bool = true,+        subject: MarkdownExportModel.Subject?     ) -> NavigationActions {         NavigationActions(             tab: tab,             isWide: isWide,+            worksLoaded: worksLoaded,             subject: subject,             newWork: {},             find: {},@@ -59,15 +68,38 @@ struct NavigationActionsTests {      // MARK: - Find (⌘F) -    @Test("Find belongs to the two tabs that have a list")-    func findNeedsAList() {-        #expect(Self.actions(tab: .today).find != nil)+    /// `launch-to-today` Req 5.2, Q7: Today lost its search field, so Find is+    /// the Works tab's alone — and Export must **not** follow it off Today,+    /// which is why the two stopped sharing `hasList`.+    @Test("Find belongs to the Works tab and nowhere else")+    func findIsWorksOnly() {         #expect(Self.actions(tab: .works).find != nil)+        #expect(Self.actions(tab: .today).find == nil)         // Req 6.2 names this one outright: Stats has no list, so there is no         // search field for ⌘F to put the cursor in.         #expect(Self.actions(tab: .stats).find == nil)     } +    /// `launch-to-today` Q22: behind the works-load gate the search field does+    /// not exist, so ⌘F would focus nothing. New Work is a sheet `ContentView`+    /// presents and needs nothing from the snapshot, so it stays.+    @Test("Find on Works waits for the works load; New Work does not")+    func findWaitsForTheWorksLoad() {+        #expect(Self.actions(tab: .works, worksLoaded: false).find == nil)+        #expect(Self.actions(tab: .works, worksLoaded: true).find != nil)+        #expect(Self.actions(tab: .works, worksLoaded: false).newWork != nil)+    }++    /// Req 5.2's other half: Export is a function of the list and the subject+    /// and of nothing else, so neither the Today tab nor an unfinished works+    /// load may take it away.+    @Test("Export is available on Today, and on Works before the load finishes")+    func exportIgnoresFindsGating() {+        #expect(Self.actions(tab: .today, hasSelection: true).export != nil)+        #expect(+            Self.actions(tab: .works, worksLoaded: false, hasSelection: true).export != nil)+    }+     // MARK: - Export (⇧⌘E)      @Test("Export needs a list and something selected in it")@@ -205,6 +237,7 @@ struct NavigationActionsTests {         let actions = NavigationActions(             tab: .works,             isWide: true,+            worksLoaded: true,             subject: .work(Self.workID),             newWork: { log.calls.append("newWork") },             find: { log.calls.append("find") },@@ -245,6 +278,14 @@ struct NavigationActionsTests {         #expect(base != Self.actions(tab: .today, isWide: true, subject: .work(Self.workID)))         #expect(base != Self.actions(tab: .works, isWide: false, subject: .work(Self.workID)))         #expect(base != Self.actions(tab: .works, isWide: true, subject: nil))+        // The works load is a gating fact like the other three: without it in+        // `==`, ⌘F stays disabled on Works for as long as the window's scene+        // value goes unrepublished after the snapshot arrives.+        #expect(+            base+                != Self.actions(+                    tab: .works, isWide: true, worksLoaded: false,+                    subject: .work(Self.workID)))         // The defect a `hasSelection` flag would have hidden: both are "a work         // is selected on Works", and they export different documents.         #expect(base != Self.actions(tab: .works, isWide: true, subject: .work(UUID())))
Asterism/AsterismTests/TodayFixtureSeedingTests.swift Modified +3 / -0
diff --git a/Asterism/AsterismTests/TodayFixtureSeedingTests.swift b/Asterism/AsterismTests/TodayFixtureSeedingTests.swiftindex 717a8121..2db9177f 100644--- a/Asterism/AsterismTests/TodayFixtureSeedingTests.swift+++ b/Asterism/AsterismTests/TodayFixtureSeedingTests.swift@@ -161,6 +161,9 @@ private struct SeededTodayLibrary {             configuration: LibraryConfiguration(rootDirectory: root),             uiTestFixture: .today)         await model.bootstrap()+        // The works snapshot these cases read is published by the launch tail,+        // not by the open (`launch-to-today` Decision 3).+        await model.waitForLaunchTail()         launchDayCandidates = [before, CivilDay(Date(), calendar: calendar)]         #expect(model.state == .ready)     }
Asterism/AsterismUITests/SearchUITests.swift Modified +18 / -89
diff --git a/Asterism/AsterismUITests/SearchUITests.swift b/Asterism/AsterismUITests/SearchUITests.swiftindex 2c2081a1..98d12898 100644--- a/Asterism/AsterismUITests/SearchUITests.swift+++ b/Asterism/AsterismUITests/SearchUITests.swift@@ -1,11 +1,16 @@ import XCTest -/// Search on Recent and Works (Reqs 3, 4), driven from app launch.+/// Search on Works (Req 4), driven from app launch — and its absence from Today+/// (`launch-to-today` Req 5.1). /// /// The filters themselves are pure structs with their own unit tests; what only /// a journey can prove is that the field is reachable, that typing into it /// narrows the list the reader is looking at, and that a query with nothing-/// behind it produces the empty state rather than a blank list (3.4, 4.3).+/// behind it produces the empty state rather than a blank list (4.3).+///+/// Today's three search journeys went with its field (`launch-to-today`+/// Decision 1). `RecentSearchFilter` and the plan's search path keep their unit+/// tests until T-2347 gives note search a home. /// /// `seeded-composed` is the fixture with a taught Work in it: two `id.test` /// entries under the Work "Real Work", plus one untaught `composed.test` entry@@ -31,10 +36,6 @@ final class SearchUITests: XCTestCase {         app.launch()     } -    private var recentRows: XCUIElementQuery {-        app.elements(withIdentifierPrefix: "recent-entry-")-    }-     private var workRows: XCUIElementQuery {         app.elements(withIdentifierPrefix: "work-row-")     }@@ -48,93 +49,21 @@ final class SearchUITests: XCTestCase {         field.typeText(query)     } -    /// Req 3.5's clear. The field keeps focus, so the next query can be typed-    /// straight after without re-tapping.-    private func clearQuery() {-        let field = app.searchFields.firstMatch-        guard field.exists else { return }-        let clear = field.buttons.firstMatch-        if clear.exists, clear.isHittable {-            clear.tap()-        } else {-            field.tap()-        }-    }--    // MARK: - Recent (Req 3)--    func testRecentSearchNarrowsRowsAndRestoresThemWhenCleared() {-        launch("seeded-composed")-        waitFor(app.collectionViews["recent-list"], "Recent publishes the seeded library", timeout: 60)-        XCTAssertEqual(recentRows.count, 3, "The fixture seeds three entries")--        // Matches the two taught entries on their Work title, and nothing else:-        // the untaught row's cleaned capture title is `TtH - Story - Real Title`.-        type("Real Work")-        let narrowed = expectation(-            for: NSPredicate(format: "count == 2"), evaluatedWith: recentRows)-        XCTAssertEqual(-            XCTWaiter().wait(for: [narrowed], timeout: 15), .completed,-            "Typing a work title narrows Recent to that work's entries")--        // Req 3.5: clearing restores the prior list rather than a fresh read.-        clearQuery()-        let restored = expectation(-            for: NSPredicate(format: "count == 3"), evaluatedWith: recentRows)-        XCTAssertEqual(-            XCTWaiter().wait(for: [restored], timeout: 15), .completed,-            "Clearing the query restores every row")-    }+    // MARK: - Today (`launch-to-today` Req 5.1) -    func testRecentSearchWithNoMatchesShowsItsOwnEmptyState() {+    /// Today is a dashboard and carries no search field. The list is pulled+    /// down first because iOS may present a `.searchable` field collapsed until+    /// then — so a field that was still there would be showing by the time the+    /// count is taken. Works sits behind its own tab and is not in the tree.+    func testTodayPresentsNoSearchField() {         launch("seeded-composed")-        waitFor(app.collectionViews["recent-list"], "Recent publishes the seeded library", timeout: 60)--        type("zzqqxx")-        waitFor(-            app.anyElement("recent-search-empty"),-            "Req 3.4: a query with nothing behind it gets a message, not a blank list")-        XCTAssertFalse(-            app.anyElement("recent-empty").exists,-            "The message describes the query, not an empty library")-    }--    /// Req 3.2 / Q6: search runs **after** the banner filter, so both conditions-    /// apply. The divergent fixture is the only shape with a banner to compose-    /// with — two entries on one conservative key with different notes, beside a-    /// healthy row the filter excludes.-    func testRecentSearchComposesWithTheDuplicateFilter() {-        launch("seeded-tolerated-divergentEntrySet")-        waitFor(app.collectionViews["recent-list"], "The library opens", timeout: 60)-        XCTAssertEqual(recentRows.count, 3, "Both members of the set plus the healthy row")--        waitFor(app.buttons["duplicate-banner"], "Recent shows the duplicate banner").tap()-        let filtered = expectation(-            for: NSPredicate(format: "count == 2"), evaluatedWith: recentRows)-        XCTAssertEqual(-            XCTWaiter().wait(for: [filtered], timeout: 15), .completed,-            "The banner filters Recent to the set")+        let list = waitFor(+            app.collectionViews["recent-list"], "Today publishes the seeded library", timeout: 60)+        waitFor(app.anyElement("today-week-range"), "…on a day, with its chrome") -        // Note text is one of the searched fields (3.1), and only one member's-        // note says "this device".-        type("this device")-        let narrowed = expectation(-            for: NSPredicate(format: "count == 1"), evaluatedWith: recentRows)+        list.swipeDown()         XCTAssertEqual(-            XCTWaiter().wait(for: [narrowed], timeout: 15), .completed,-            "The query narrows within the filtered set")-        XCTAssertEqual(-            app.buttons.matching(identifier: "resolve-duplicate-pill").count, 1,-            "The surviving row is still a member of the set")--        // The healthy row matches the query but not the filter: both conditions-        // hold, so the result is empty rather than the banner's filter lapsing.-        clearQuery()-        type("Healthy")-        waitFor(-            app.anyElement("recent-search-empty"),-            "A row the banner excluded is not resurrected by matching the query")-        XCTAssertEqual(recentRows.count, 0, "Nothing satisfies both conditions")+            app.searchFields.count, 0, "Req 5.1: Today presents no search field")     }      // MARK: - Works (Req 4)
Asterism/AsterismUITests/TodayUITests.swift Modified +25 / -36
diff --git a/Asterism/AsterismUITests/TodayUITests.swift b/Asterism/AsterismUITests/TodayUITests.swiftindex f298802e..b74aa0a1 100644--- a/Asterism/AsterismUITests/TodayUITests.swift+++ b/Asterism/AsterismUITests/TodayUITests.swift@@ -199,28 +199,6 @@ final class TodayUITests: XCTestCase {             file: file, line: line)     } -    // MARK: - Search--    /// `searchField(in:)` is shared with the other journey suites-    /// (`UIJourneySupport`) and carries the collapsed-field and-    /// not-yet-hittable guards.-    private func type(_ query: String, file: StaticString = #filePath, line: UInt = #line) {-        let field = searchField(in: app, file: file, line: line)-        field.tap()-        field.typeText(query)-    }--    private func clearQuery() {-        let field = app.searchFields.firstMatch-        guard field.exists else { return }-        let clear = field.buttons.firstMatch-        if clear.exists, clear.isHittable {-            clear.tap()-        } else {-            field.tap()-        }-    }-     // MARK: - The original journeys (unchanged behaviour, `seeded-m1`)      func testTwoTabStructure() {@@ -744,30 +722,41 @@ final class TodayUITests: XCTestCase {         XCTAssertEqual(recentRows.count, 0, "…and nothing was noted then")     } -    // MARK: - Req 3.3 — search spans every day+    // MARK: - `launch-to-today` Req 5.3 — a banner filter spans every day -    /// While a query is active the screen spans every day: the week row, the-    /// strip and the releases section all go, and Recent's own day groups come-    /// back. Clearing restores the day.-    func testSearchHidesTheDayChromeAndClearingBringsItBack() {-        launchToday()-        waitFor(app.anyElement("today-section-releases"), "The day opens with its releases section")+    /// While a banner filter is active the screen spans every day: the week+    /// row, the strip and the releases section all go, and Recent's own day+    /// groups come back. Clearing restores the day. The search journey carried+    /// this coverage until Today lost its field (`launch-to-today` Decision 1).+    ///+    /// `seeded-tolerated-divergentEntrySet` because `seeded-today` has no+    /// banner: its site is taught and it holds no duplicate set. The releases+    /// section is drawn on the current day whether or not anything is due.+    func testABannerFilterHidesTheDayChromeAndClearingBringsItBack() {+        launch("seeded-tolerated-divergentEntrySet")+        waitFor(app.collectionViews["recent-list"], "The library opens", timeout: 60)+        waitFor(app.anyElement("today-week-range"), "The day opens with its week row")+        waitFor(app.anyElement("today-section-releases"), "…and its releases section") -        type("Kite")+        let banner = waitFor(app.buttons["duplicate-banner"], "Today shows the duplicate banner")+        banner.tap()         waitUntilGone(             app.anyElement("today-section-releases"),-            "Req 3.3: release rows are never search results", timeout: 15)+            "Req 5.3: the releases sections go while a banner filters", timeout: 15)+        XCTAssertFalse(+            app.anyElement("today-section-catching-up").exists, "Req 5.3: both of them")         XCTAssertFalse(-            app.anyElement("today-week-range").exists, "Req 3.3: the week row goes with it")+            app.anyElement("today-week-range").exists, "Req 5.3: the week row goes with them")         XCTAssertFalse(-            stripCell(daysFromLaunch: 0).exists, "Req 3.3: and the strip")+            stripCell(daysFromLaunch: 0).exists, "Req 5.3: and the strip")         waitFor(             app.anyElement("recent-section-header"),-            "Req 3.3: the results are grouped and headed as Recent groups them")+            "Req 5.3: the filtered rows are grouped and headed as Recent groups them") -        clearQuery()+        // The banner is its own clear: it reads `Show All` while it filters.+        banner.tap()         waitFor(-            app.anyElement("today-week-range"), "Req 3.3: clearing brings the day back",+            app.anyElement("today-week-range"), "Req 5.3: clearing brings the day back",             timeout: 15)         waitFor(stripCell(daysFromLaunch: 0), "…with its strip")         waitFor(app.anyElement("today-section-releases"), "…and its releases section")
Asterism/AsterismUITests/WideLayoutUITests.swift Modified +40 / -16
diff --git a/Asterism/AsterismUITests/WideLayoutUITests.swift b/Asterism/AsterismUITests/WideLayoutUITests.swiftindex 3fefc96c..6c4fad8d 100644--- a/Asterism/AsterismUITests/WideLayoutUITests.swift+++ b/Asterism/AsterismUITests/WideLayoutUITests.swift@@ -406,23 +406,26 @@ final class WideLayoutUITests: XCTestCase {      // MARK: - `entry-to-work-link` — the detail column's route to the work -    /// The title card's work name, from the Recent pane's detail column-    /// (`entry-to-work-link`, Test Plan's iPad bullet). Requirement 2's-    /// out-of-tab clause in the wide tree: the entry was opened from Recent, so-    /// the name selects the **Works pane** showing that one work, rather than-    /// pushing anything onto the stack the entry came from.+    /// The title card's work name, from the Today pane's detail column+    /// (`entry-to-work-link`, Test Plan's iPad bullet), **as `update-schedule`+    /// Q77 left it**: from Today the work replaces Today's own stack at the+    /// root and the pane does not change.     ///-    /// This is the assumption the smolspec's Risks section records — that-    /// `showWork` selects the Works pane and the detail column renders-    /// `worksPath.last`, as the chapter case above relies on — asserted rather-    /// than assumed: `works-list` beside the pane's detail column is what "the-    /// window is on Works" means here, and the work laid out *inside* that-    /// column is what tells this route from Req 1.7's push across the pane.+    /// This case used to assert the out-of-tab clause — that the name selects+    /// the Works pane, `works-list` beside the detail column being what "the+    /// window is on Works" meant. `update-schedule` gave Today a stack of its+    /// own and made `AppNavigation.openWork(_:fromEntry:)` keep a Today route on+    /// Today (`showWork(_:on: .today)`, pinned by+    /// `AppNavigationTests.openWorkFromTodayStaysOnToday`), so the Works pane is+    /// no longer where the work lands and the old assertion has been failing+    /// since that merge. What the wide tree owes the route is unchanged: the+    /// work fills the **detail column** rather than being pushed across the pane+    /// (Req 1.7's shape), and the entry it was opened from is left behind.     ///     /// `seeded-composed` again, and for the same reason the phone journeys use     /// it: its two `id.test` chapters are composed-taught and carry the work     /// `Real Work`, which is what makes the card name anything at all.-    func testTheWorkNameInTheDetailColumnOpensTheWorkOnTheWorksPane() {+    func testTheWorkNameInTheDetailColumnOpensTheWorkOnTodaysPane() {         launch("seeded-composed", orientation: .landscapeLeft)         waitForLibrary() @@ -440,9 +443,6 @@ final class WideLayoutUITests: XCTestCase {         waitFor(app.anyElement("entry-detail-work-title"), "The card names the work")         waitFor(app.buttons["entry-detail-work-title"], "…and it is a control").tap() -        waitFor(-            app.collectionViews["works-list"],-            "The name switches the window to the Works pane", timeout: 20)         let detailColumn = waitFor(             app.anyElement("wide-detail-column"), "The detail column is laid out")         let heading = waitFor(@@ -452,7 +452,19 @@ final class WideLayoutUITests: XCTestCase {         assertInsideColumn(heading, column: detailColumn, what: "The opened work")         waitUntilGone(             app.anyElement("entry-detail-note-editor"),-            "…and the pane the entry was read in is left behind")+            "…and the entry it was read from is left behind")++        // Q77's half: the pane is unchanged and the list column is still the+        // day, so Back returns to the selected day rather than to a works list.+        XCTAssertTrue(+            app.anyElement("sidebar-today").isSelected,+            "Q77: a work opened from Today stays on Today's pane")+        XCTAssertFalse(+            app.collectionViews["works-list"].exists,+            "…so the Works pane is not selected behind it")+        waitFor(+            app.anyElement("today-week-range"),+            "…and the list column is still the day the entry was read on")     }      /// The entry title out of a Recent row's accessibility label, which@@ -984,6 +996,18 @@ final class WideLayoutUITests: XCTestCase {         app.elements(withIdentifierPrefix: "today-strip-")     } +    /// `launch-to-today` Req 5.1, the wide tree's case: the list column carries+    /// no search field. `SearchUITests` holds the phone's.+    /// The list is pulled down first, since iPadOS may keep a `.searchable`+    /// field collapsed until then.+    func testTodayPresentsNoSearchField() {+        launchToday()++        app.collectionViews["recent-list"].swipeDown()+        XCTAssertEqual(+            app.searchFields.count, 0, "Req 5.1: Today presents no search field")+    }+     /// Req 10.1's first two clauses: a release row selects its work into the     /// detail column the way a Works row does, a noted row selects its entry,     /// and selecting either kind clears the other.
Asterism/AsterismUITests/WorksLoadGateUITests.swift Added +80 / -0
diff --git a/Asterism/AsterismUITests/WorksLoadGateUITests.swift b/Asterism/AsterismUITests/WorksLoadGateUITests.swiftnew file mode 100644index 00000000..7ec066d4--- /dev/null+++ b/Asterism/AsterismUITests/WorksLoadGateUITests.swift@@ -0,0 +1,80 @@+import XCTest++/// The works-load gate (`launch-to-today` Reqs 3.2, 3.4, 3.6, 3.7).+///+/// Today is published from its own read at launch and the works snapshot+/// arrives behind it, so Works and Stats sit behind a gate that shows a+/// progress indicator, or — when the load failed — an error with Retry. The+/// loading arm is not what this suite is about: over a seeded fixture it is+/// gone before the tab is reachable, and a test that raced it would be a test+/// of the fixture's size. The **failed** arm is reachable on demand, through+/// `ASTERISM_UI_TEST_WORKS_LOAD=fail-until-retry` (Q17), and it holds until+/// Retry clears it — so one launch can be walked across both gated tabs and+/// back.+final class WorksLoadGateUITests: XCTestCase {+    private var app: XCUIApplication!++    override func setUp() {+        continueAfterFailure = false+        XCUIDevice.shared.orientation = .portrait+        app = XCUIApplication()+        terminateAndWaitForExit(app)+    }++    override func tearDown() {+        if let app {+            terminateAndWaitForExit(app)+        }+        app = nil+    }++    /// Reqs 3.6, 3.7 end to end: a failed first works load leaves Today alone,+    /// says so on both gated tabs, and is cleared by the Retry the gate offers.+    @MainActor+    func testAFailedWorksLoadIsShownOnWorksAndStatsAndClearedByRetry() {+        launchWithAFailingWorksLoad()++        // Req 3.6's first clause. Today is published from its own read, so the+        // failure of the works load is not a failure of the screen the reader+        // is looking at.+        waitFor(app.collectionViews["recent-list"], "Today lists the seeded library")++        selectTab(.works, in: app)+        waitFor(app.anyElement("works-load-failed"), "Works says the works could not be loaded")+        // Req 3.3: not an empty library, and not a list at all.+        XCTAssertFalse(+            app.collectionViews["works-list"].exists,+            "The works list must not be built behind the gate")++        selectTab(.stats, in: app)+        waitFor(app.anyElement("works-load-failed"), "Stats says the same thing Works does")+        XCTAssertFalse(+            app.anyElement("stats-total-notes").exists,+            "Req 4.2: no statistic is derived over a snapshot that never arrived")++        // Req 3.7: the Retry clears the fault, and the attempt behind it+        // publishes the snapshot the gate was waiting on.+        selectTab(.works, in: app)+        let retry = waitFor(app.buttons["works-load-retry"], "The gate offers a Retry")+        retry.tap()+        waitFor(+            app.collectionViews["works-list"], "Retry brings up the works list", timeout: 60)+        waitUntilGone(app.anyElement("works-load-failed"), "…and takes the error with it")++        // Req 3.4: the other gated tab needs no action of its own — one+        // publication opens both.+        selectTab(.stats, in: app)+        waitFor(app.anyElement("stats-total-notes"), "Stats draws its totals after the retry")+    }++    /// The same fixture every Today suite launches on, with the works read+    /// faulted. `fail-until-retry` rather than a fail-once fault: the launch+    /// tail retries on its own, and a fault cleared by that retry would be gone+    /// before this suite reached the Works tab (Q17).+    private func launchWithAFailingWorksLoad() {+        app.launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = "seeded-m1"+        app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+        app.launchEnvironment["ASTERISM_UI_TEST_WORKS_LOAD"] = "fail-until-retry"+        app.launch()+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift Modified +57 / -13
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swiftindex a33ded94..fff1f50a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift@@ -157,13 +157,11 @@ struct M4ToleratedScalePerformanceTests {     /// Catching up section (`catch-up-mode`), each row's second line and the     /// strip's dots — against the same 2 s budget, over the same fixture.     ///-    /// **`works()` is read once, outside the timed closure** (Q41). It is a-    /// separately published value with a performance arm of its own-    /// (`works-snapshot-*`), and timing it here would make this arm a second-    /// measurement of that read rather than a measurement of Today's own work.-    /// What is inside the interval is exactly what `refreshAll` adds for Today:-    /// the entry publication, one `TodaySchedule.build` over the snapshot, and-    /// two `TodayDayPlan.build`s.+    /// **`works()` is not read at all** (`launch-to-today` Decision 2, which+    /// supersedes Q41's read outside the timed closure). The schedule is built+    /// inside `todayPresentation`, from the rows that read already holds, so the+    /// 2 s budget now covers it: what is inside the interval is the entry+    /// publication with its schedule, and two `TodayDayPlan.build`s.     ///     /// **Two days, both real over this fixture** (Req 10.5): 1970-01-02 as the     /// current day, which is the releases-first arm with the shifted entries'@@ -179,19 +177,17 @@ struct M4ToleratedScalePerformanceTests {          var calendar = Calendar(identifier: .gregorian)         calendar.timeZone = try #require(TimeZone(identifier: "UTC"))-        let snapshot = try await repository.works()         let currentDay = CivilDay(             Date(timeIntervalSince1970: LibraryRepository.m4FixtureNoteShift), calendar: calendar)         let pastDay = currentDay.adding(days: -1, calendar: calendar)          let measured = try await measureDistributionAsync(iterations: iterations) {             let presentation = try await repository.todayPresentation(calendar: calendar)-            let schedule = TodaySchedule.build(works: snapshot.works, calendar: calendar)             _ = TodayDayPlan.build(-                day: currentDay, currentDay: currentDay, schedule: schedule,+                day: currentDay, currentDay: currentDay, schedule: presentation.schedule,                 presentation: presentation, calendar: calendar)             _ = TodayDayPlan.build(-                day: pastDay, currentDay: currentDay, schedule: schedule,+                day: pastDay, currentDay: currentDay, schedule: presentation.schedule,                 presentation: presentation, calendar: calendar)         } @@ -201,14 +197,14 @@ struct M4ToleratedScalePerformanceTests {         // schedule layer is actually under it: a library with no scheduled works         // would meet the budget by doing nothing, and the number would say         // nothing about Today.-        let schedule = TodaySchedule.build(works: snapshot.works, calendar: calendar)+        let presentation = try await repository.todayPresentation(calendar: calendar)+        let schedule = presentation.schedule         #expect(schedule.works.count == LibraryRepository.m4FixtureScheduledWorkCount)         #expect(schedule.dueWeekdays == Set(ReleaseDay.allCases))         // `catch-up-mode` Q12, for the same reason: the Catching up section is         // inside the measured interval, and an empty one would cost nothing and         // prove nothing.         #expect(schedule.catchingUp.count == LibraryRepository.m4FixtureCatchUpWorkCount)-        let presentation = try await repository.todayPresentation(calendar: calendar)         let current = TodayDayPlan.build(             day: currentDay, currentDay: currentDay, schedule: schedule,             presentation: presentation, calendar: calendar)@@ -230,6 +226,54 @@ struct M4ToleratedScalePerformanceTests {         #expect(past.placement == .notedFirst)     } +    // MARK: - `launch-to-today` Req 1.3 — the reads before the first Today publication++    /// Req 1.3, reported: the repository reads the reader waits on between the+    /// store opening and Today being drawable, over the same fixture and with+    /// the same injected calendar as `todayPublication` (Q45 of+    /// `update-schedule`).+    ///+    /// **Two arms, in the order `AppLibraryModel.refreshAll()` makes the reads.**+    /// `launch-reads-full` is `todayPresentation` + `works` + `siteNames`, which+    /// is what `bootstrap()` awaits before `.ready` today. `launch-reads-today`+    /// is `todayPresentation` + `siteNames`, which is what it will await once+    /// Today stops depending on the works snapshot. `launch-reads-full` before+    /// the change against `launch-reads-today` after it is the launch saving+    /// (Req 1.4); `launch-reads-full` after it is what the background works load+    /// costs.+    ///+    /// **No budget and no ceiling** (Q4 of that spec): no time-to-first-Today+    /// number exists yet, so a bound drawn now would be a guess. The arm exists+    /// to record a band a later budget can be set from. It is the repository's+    /// share only — the store open, the pending-capture drain and the app-side+    /// derivations are the `LaunchToToday` signpost's to report, not this arm's.+    @Test("The repository reads before the first Today publication (launch-to-today Req 1.3)")+    func launchReads() async throws {+        let store = try await M4PerformanceStore(state: nil)+        let repository = try await store.openApp()++        var calendar = Calendar(identifier: .gregorian)+        calendar.timeZone = try #require(TimeZone(identifier: "UTC"))++        let full = try await measureDistributionAsync(iterations: iterations) {+            _ = try await repository.todayPresentation(calendar: calendar)+            _ = try await repository.works()+            _ = try await repository.siteNames()+        }+        reportPerformance("launch-reads-full", full)++        let today = try await measureDistributionAsync(iterations: iterations) {+            _ = try await repository.todayPresentation(calendar: calendar)+            _ = try await repository.siteNames()+        }+        reportPerformance("launch-reads-today", today)++        // A reported arm still has to be a measurement of something: an empty+        // fixture would make both figures the cost of three no-op reads.+        let works = try await repository.works().works+        #expect(works.count == LibraryRepository.m4FixtureWorkCount)+    }+     // MARK: - Req 5.4 — capture rule application in every state from 1.1      /// **The three states, named rather than `allCases`.** Req 5.4 is
Packages/AsterismCore/Tests/AsterismCoreTests/TodayScheduleEquivalenceTests.swift Added +412 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/TodayScheduleEquivalenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayScheduleEquivalenceTests.swiftnew file mode 100644index 00000000..d2b15bc9--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/TodayScheduleEquivalenceTests.swift@@ -0,0 +1,412 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++/// `launch-to-today` Req 2.3 and Decision 2: the schedule `todayPresentation`+/// builds from its own rows is the schedule the works snapshot amounts to.+///+/// The presentation snapshots only the work groups `TodaySchedule.admits`+/// lets through, and takes their entries from the Entry rows it already holds+/// rather than through `work.entries`. Both are shortcuts around `works()`,+/// and each fixture here is a shape where a shortcut could come out different:+/// a group whose carrier is not its representative, a pair the reader has told+/// apart, an Entry whose rows sit under two works, a work the two tests of+/// `admits` would both claim, a work with nothing under it, and no works at+/// all. The M4 fixture is the same claim at the size the budget is drawn over.+@Suite("Today's schedule without the works snapshot", .serialized)+struct TodayScheduleEquivalenceTests {++    /// Gregorian UTC, never `Calendar.current`: the noted days are civil days,+    /// and the M4 fixture's entries are one day in some zones and two in others.+    private static var calendar: Calendar {+        var calendar = Calendar(identifier: .gregorian)+        calendar.timeZone = TimeZone(identifier: "UTC")!+        return calendar+    }++    /// The claim itself, over whatever `repository` holds.+    @discardableResult+    private static func expectEquivalent(+        _ repository: LibraryRepository, sourceLocation: SourceLocation = #_sourceLocation+    ) async throws -> TodaySchedule {+        let presentation = try await repository.todayPresentation(calendar: calendar)+        let works = try await repository.works().works+        #expect(+            presentation.schedule == TodaySchedule.build(works: works, calendar: calendar),+            sourceLocation: sourceLocation)+        return presentation.schedule+    }++    // MARK: - Schedule equivalence (Req 2.3)++    @Test("The M4 composed fixture")+    func m4ComposedFixture() async throws {+        let root = FileManager.default.temporaryDirectory+            .appending(+                path: "asterism-today-schedule-m4-\(UUID().uuidString)", directoryHint: .isDirectory)+        defer { try? FileManager.default.removeItem(at: root) }+        let configuration = LibraryConfiguration(rootDirectory: root)+        try FileManager.default.createDirectory(+            at: configuration.storeURL.deletingLastPathComponent(),+            withIntermediateDirectories: true)+        let container = try LibraryRepository.openContainer(at: configuration.storeURL)+        let repository = LibraryRepository.makeRepository(+            configuration, container, .m4, SystemRepositoryClock(), ModelContextSaveStrategy())+        try await repository.seedM4PerformanceFixture()++        let schedule = try await Self.expectEquivalent(repository)++        // Equal and empty would prove nothing about the prefilter.+        #expect(schedule.works.count == LibraryRepository.m4FixtureScheduledWorkCount)+        #expect(schedule.catchingUp.count == LibraryRepository.m4FixtureCatchUpWorkCount)+        #expect(schedule.works.contains { !$0.notedDays.isEmpty })+    }++    /// The prefilter asks the **carrier**, because that is the row a snapshot's+    /// statuses come from. Asking the representative would admit or drop this+    /// group on the wrong row's say-so.+    @Test("A same-UUID split work group whose rows disagree on reading status")+    func splitWorkGroupDisagreeingOnReadingStatus() async throws {+        let library = try ScheduleFixture()+        let shared = UUID()+        try library.seed { store in+            store.insertSite(hostname: "split.example")+            let reading = store.insertWork(+                id: shared, hostname: "split.example", title: "Serial", offset: 0,+                releaseDays: [.monday, .thursday])+            let behind = store.insertWork(+                id: shared, hostname: "split.example", title: "Serial", offset: 5,+                readingStatus: .catchingUp, releaseDays: [.monday, .thursday])+            // Entries under each row, on two days: the group's noted days are+            // the union across every row (Req 5.5).+            store.insertEntry(+                hostname: "split.example", key: "a", title: "One", offset: 0, work: reading)+            store.insertEntry(+                hostname: "split.example", key: "b", title: "Two", offset: 90_000, work: behind)+        }+        let repository = try await library.openForApp()++        let schedule = try await Self.expectEquivalent(repository)++        // One group, in exactly one of the two lists, with both rows' entries.+        let listed = schedule.works + schedule.catchingUp+        #expect(listed.map(\.id) == [shared])+        #expect(listed.first?.notedDays.count == 2)+    }++    /// A dismissed pair is two works, not one set, so `canonicalWorkIDs` does+    /// not unify them — and the Entry split across them is torn under both+    /// reads alike.+    @Test("A dismissed cross-site pair")+    func dismissedCrossSitePair() async throws {+        let library = try ScheduleFixture()+        let sharedEntry = UUID()+        try library.seed { store in+            store.insertSite(hostname: "first.example")+            store.insertSite(hostname: "second.example")+            let first = store.insertWork(+                hostname: "first.example", title: "The Same Title", offset: 0,+                releaseDays: [.tuesday])+            let second = store.insertWork(+                hostname: "second.example", title: "The Same Title", offset: 10,+                readingStatus: .catchingUp)+            store.insertDistinctPair(first.id, second.id)+            store.insertEntry(+                hostname: "first.example", key: "a", title: "One", offset: 0, work: first)+            store.insertEntry(+                hostname: "second.example", key: "b", title: "Two", offset: 90_000, work: second)+            store.insertEntry(+                id: sharedEntry, hostname: "first.example", key: "c", title: "Three",+                offset: 180_000, work: first)+            store.insertEntry(+                id: sharedEntry, hostname: "first.example", key: "c", title: "Three",+                offset: 180_000, work: second)+        }+        let repository = try await library.openForApp()++        let schedule = try await Self.expectEquivalent(repository)++        #expect(schedule.works.count == 1)+        #expect(schedule.catchingUp.count == 1)+    }++    /// Under each work the Entry group is built from the rows pointing at+    /// *that* work only — a fragment, by design of the works snapshot — so the+    /// bucket by `row.work?.id` has to hand each work the same fragment.+    @Test("A split entry group whose rows point at two different works")+    func splitEntryGroupAcrossTwoWorks() async throws {+        let library = try ScheduleFixture()+        let sharedEntry = UUID()+        try library.seed { store in+            store.insertSite(hostname: "split.example")+            let left = store.insertWork(+                hostname: "split.example", title: "Left", offset: 0, releaseDays: [.friday])+            let right = store.insertWork(+                hostname: "split.example", title: "Right", offset: 10, releaseDays: [.friday])+            // The two rows disagree about the day they were last shared on and+            // about the chapter, so a fragment and the whole group read apart.+            store.insertEntry(+                id: sharedEntry, hostname: "split.example", key: "one", title: "AAA",+                offset: 0, work: left, chapterTitle: "left chapter")+            store.insertEntry(+                id: sharedEntry, hostname: "split.example", key: "one", title: "AAA",+                offset: 90_000, work: right, chapterTitle: "right chapter")+        }+        let repository = try await library.openForApp()++        let schedule = try await Self.expectEquivalent(repository)++        #expect(schedule.works.count == 2)+        #expect(schedule.works.allSatisfy { $0.notedDays.count == 1 })+    }++    /// The order-of-tests case `admits` documents, through the store: release+    /// days and a finished work status do not move a catch-up work anywhere.+    @Test("A finished catching-up work that carries release days")+    func finishedCatchingUpWorkWithReleaseDays() async throws {+        let library = try ScheduleFixture()+        try library.seed { store in+            store.insertSite(hostname: "done.example")+            let work = store.insertWork(+                hostname: "done.example", title: "Finished Story", offset: 0,+                workStatus: .finished, readingStatus: .catchingUp,+                releaseDays: [.saturday, .sunday])+            store.insertEntry(+                hostname: "done.example", key: "a", title: "One", offset: 0, work: work)+        }+        let repository = try await library.openForApp()++        let schedule = try await Self.expectEquivalent(repository)++        #expect(schedule.works.isEmpty)+        #expect(schedule.dueWeekdays.isEmpty)+        #expect(schedule.catchingUp.map(\.title) == ["Finished Story"])+    }++    @Test("A scheduled work with no entries")+    func scheduledWorkWithNoEntries() async throws {+        let library = try ScheduleFixture()+        try library.seed { store in+            store.insertSite(hostname: "bare.example")+            store.insertWork(+                hostname: "bare.example", title: "Unread", offset: 0, releaseDays: [.wednesday])+            // An unattached Entry, so the bucketing has a row with no work to+            // step over.+            store.insertEntry(hostname: "bare.example", key: "a", title: "Loose", offset: 0)+        }+        let repository = try await library.openForApp()++        let schedule = try await Self.expectEquivalent(repository)++        #expect(schedule.works.map(\.title) == ["Unread"])+        #expect(schedule.works.first?.notedDays.isEmpty == true)+    }++    @Test("An empty library")+    func emptyLibrary() async throws {+        let library = try ScheduleFixture()+        try library.seed { _ in }+        let repository = try await library.openForApp()++        let schedule = try await Self.expectEquivalent(repository)++        #expect(schedule == TodaySchedule(works: [], dueWeekdays: [], catchingUp: []))+    }++    // MARK: - Work titles (Q16)++    /// The map is **unfiltered**. The fold the rows read drops a blank title;+    /// this one must not, or a restored selection would be pruned or kept+    /// depending on which publication the prune ran against.+    @Test("workTitles is the works snapshot's id-to-title map, blank titles included")+    func workTitlesMatchTheWorksSnapshot() async throws {+        let library = try ScheduleFixture()+        let shared = UUID()+        var blankID = UUID()+        try library.seed { store in+            store.insertSite(hostname: "titles.example")+            store.insertWork(hostname: "titles.example", title: "Named", offset: 0)+            blankID = store.insertWork(hostname: "titles.example", title: "", offset: 10).id+            // A split group: one title for the group, and it is the carrier's.+            store.insertWork(id: shared, hostname: "titles.example", title: "Serial", offset: 20)+            store.insertWork(+                id: shared, hostname: "titles.example", title: "Serial", offset: 25,+                notes: "kept")+        }+        let repository = try await library.openForApp()++        let presentation = try await repository.todayPresentation(calendar: Self.calendar)+        let works = try await repository.works().works++        let expected = Dictionary(uniqueKeysWithValues: works.map { ($0.id, $0.displayTitle) })+        #expect(presentation.workTitles == expected)+        #expect(presentation.workTitles.count == 3)+        #expect(presentation.workTitles[blankID] == "")+    }++    // MARK: - `TodaySchedule.admits`++    /// The whole table, spelled rather than computed: a computed expectation+    /// would be a second copy of the predicate agreeing with the first.+    @Test(+        "admits puts a work in one list or in neither",+        arguments: [+            // The scheduled predicate, clause by clause.+            AdmitsCase(.reading, .ongoing, [.monday], .scheduled),+            AdmitsCase(.reading, .ongoing, [], nil),+            AdmitsCase(.reading, .finished, [.monday], nil),+            AdmitsCase(.reading, .hiatus, [.monday], nil),+            AdmitsCase(.finished, .finished, [.monday], nil),+            AdmitsCase(.abandoned, .ongoing, [.monday], nil),+            // Catching up is claimed **first**, whatever else the work carries:+            // the case `build` documents is the one with release days, which+            // must never be swallowed by the scheduled list.+            AdmitsCase(.catchingUp, .ongoing, [.monday], .catchingUp),+            AdmitsCase(.catchingUp, .ongoing, [], .catchingUp),+            AdmitsCase(.catchingUp, .finished, [.saturday, .sunday], .catchingUp),+            AdmitsCase(.catchingUp, .hiatus, [], .catchingUp),+        ])+    func admitsTable(_ row: AdmitsCase) {+        #expect(+            TodaySchedule.admits(+                readingStatus: row.readingStatus, workStatus: row.workStatus,+                releaseDays: row.releaseDays) == row.expected)+    }++    struct AdmitsCase: Sendable, CustomTestStringConvertible {+        let readingStatus: ReadingStatus+        let workStatus: WorkStatus+        let releaseDays: [ReleaseDay]+        let expected: TodaySchedule.Bucket?++        init(+            _ readingStatus: ReadingStatus, _ workStatus: WorkStatus,+            _ releaseDays: [ReleaseDay], _ expected: TodaySchedule.Bucket?+        ) {+            self.readingStatus = readingStatus+            self.workStatus = workStatus+            self.releaseDays = releaseDays+            self.expected = expected+        }++        var testDescription: String {+            "\(readingStatus.rawValue) / \(workStatus.rawValue) / "+                + "\(releaseDays.map(\.rawValue).joined(separator: ","))"+        }+    }+}++// MARK: - Fixture++/// A fixed-path library seeded through plain `insert`/`save` and then opened+/// the way the app opens it — the `PublicationFixture` shape, because a split+/// group is not reachable through the validating commit path.+private final class ScheduleFixture {+    static let epoch = Date(timeIntervalSince1970: 1_800_000_000)++    let directory: URL+    let configuration: LibraryConfiguration++    init() throws {+        directory = FileManager.default.temporaryDirectory+            .appending(path: "AsterismTodaySchedule-\(UUID())", directoryHint: .isDirectory)+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        configuration = LibraryConfiguration(rootDirectory: directory)+        try FileManager.default.createDirectory(+            at: configuration.storeURL.deletingLastPathComponent(),+            withIntermediateDirectories: true)+    }++    func seed(_ body: (ScheduleSeedStore) throws -> Void) throws {+        let container = try LibraryRepository.openContainer(at: configuration.storeURL)+        let store = ScheduleSeedStore(context: ModelContext(container))+        try body(store)+        try store.context.save()+        try SiteRelationshipPopulationPass.run(context: store.context)+        withExtendedLifetime(container) {}+        try LibraryRepository.publishReadiness(at: configuration.readinessMarkerURL)+    }++    func openForApp() async throws -> LibraryRepository {+        let (_, repository) = try await LibraryRepository.openForApp(+            configuration, capabilities: .multiSite,+            clock: FixedRepositoryClock(Self.epoch),+            saveStrategy: ModelContextSaveStrategy())+        return repository+    }++    deinit {+        try? FileManager.default.removeItem(at: directory)+    }+}++private final class ScheduleSeedStore {+    let context: ModelContext++    init(context: ModelContext) { self.context = context }++    @discardableResult+    func insertSite(hostname: String) -> Site {+        let site = Site(hostname: hostname)+        site.mode = .untaught+        context.insert(site)+        return site+    }++    @discardableResult+    func insertEntry(+        id: UUID = UUID(), hostname: String, key: String, title: String,+        offset: TimeInterval, work: Work? = nil, chapterTitle: String? = nil+    ) -> Entry {+        let rawURL = "https://\(hostname)/read/\(key)"+        let entry = Entry(+            id: id, captureTitle: title, captureTitleSource: .host, rawURLString: rawURL,+            hostname: hostname, entryIdentityKey: rawURL,+            timestamp: ScheduleFixture.epoch.addingTimeInterval(offset))+        entry.conservativeIdentityKey = rawURL+        entry.lastSharedAt = ScheduleFixture.epoch.addingTimeInterval(offset)+        context.insert(entry)+        if let work {+            entry.work = work+            entry.editCitations { $0.workAssignment = .manual }+        }+        if let chapterTitle {+            entry.chapterTitle = chapterTitle+            entry.editCitations { $0.chapterTitle = .manual }+        }+        return entry+    }++    /// Seeded Works carry a parsed title and parsed provenance, so they read as+    /// the *parsed* Work the fixture means rather than as one carrying an+    /// authored title (Q75 of `duplicate-reconciliation`).+    @discardableResult+    func insertWork(+        id: UUID = UUID(), hostname: String, title: String, offset: TimeInterval,+        notes: String = "", workStatus: WorkStatus = .ongoing,+        readingStatus: ReadingStatus = .reading, releaseDays: [ReleaseDay] = []+    ) -> Work {+        let work = Work.create(+            in: context, id: id, title: title, hostname: hostname,+            site: try? LibraryRepository.fetchSites(hostname: hostname, context: context).first,+            timestamp: ScheduleFixture.epoch.addingTimeInterval(offset))+        work.lastParsedTitle = title+        work.titleProvenance = .parsed+        work.genericNotes = notes+        work.workStatus = workStatus+        work.readingStatus = readingStatus+        work.releaseDays = releaseDays+        return work+    }++    /// A reader's "not the same work" over an unordered pair.+    func insertDistinctPair(_ a: UUID, _ b: UUID) {+        let sorted = WorkDistinctPair.sortedIDs(a, b)+        context.insert(+            WorkDistinctPair(+                id: UUID(), lowerWorkID: sorted.lower, higherWorkID: sorted.higher,+                recordedAt: ScheduleFixture.epoch))+    }+}
CHANGELOG.md Modified +106 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d9407d8..9c5654c0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ### Fixed +- **The wide layout's work-name route asserts the rule that replaced+  it.** `WideLayoutUITests`' work-name case still expected a tap on an+  entry's work title to switch the window to the Works pane. Today grew+  its own stack in `update-schedule` (Q77), so the work opens on Today+  instead, and the case had asserted superseded behaviour ever since+  without being carried across. The app was right; the test now checks+  Q77's rule. This also explains the failure+  `specs/catch-up-mode/verification-run.md` recorded as unexplained.+ - **The advisory store-version read waits for a closing connection   instead of giving up.** Releasing a SwiftData container closes its   SQLite connection a moment later, and while that close folds the@@ -148,6 +157,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ### Removed +- **Today has no search field (`specs/launch-to-today/`, Decision 1).**+  Today is a dashboard, and its search field is gone from `TodayView`+  with the state and the ⌘F focus token that served it. The filter+  itself stays in `TodayDisplayPlan`, defaulted to inactive and+  unreachable until T-2347 moves note search to Works (Req 5.4). The+  three Recent search UI tests and the day-chrome search test went with+  the field; Today is now asserted to present no search field on the+  phone and the iPad, and the day-chrome coverage is carried by a banner+  filter instead.+ - **Schema V9 is retired (T-2308).** The owner confirmed every device is   on readiness marker 10, which is the precondition for dropping the   generation below it. The migration plan is now V10 to V11 with a@@ -161,6 +180,37 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ### Added +- **The launch reports how long it took and where the time went+  (`specs/launch-to-today/`, Req 1.1 and 1.2).** `bootstrap()` now emits+  one `LaunchToToday` signpost interval with four children — the wait+  for an in-flight background-export pass, the store open, the+  pending-capture drain and the Today reads — and one notice line+  carrying the outcome and the five durations in milliseconds, for+  example `Launch to Today: published in 1218 ms (ExportPassWait 12 ms,+  StoreOpen 341 ms, CaptureDrain 5 ms, TodayReads 812 ms)`. Both are+  built from one small value type, so what they report is testable+  without OSLog, and the total is measured rather than summed because+  UI-test seeding sits between two of the phases. The line carries+  numbers and one word of outcome, no reader content, so it is readable+  in `Personal` builds too; it is not configuration-gated. No launch+  budget is set from it yet — that waits for a reading taken on a phone.++- **A `launchReads` performance arm, and the launch figures before+  `launch-to-today` changes anything (`specs/launch-to-today/`, phase+  1).** `M4ToleratedScalePerformanceTests` gains one test with two+  reported, unbudgeted arms over the M4 fixture: `launch-reads-full`+  times `todayPresentation` + `works` + `siteNames`, which is what+  launch awaits today, and `launch-reads-today` times the same without+  `works`, which is what it will await once Today stops depending on the+  works snapshot. One `make test-performance-m4` run at the commit+  before any Core change measured **2.57 s** and **0.77 s** (medians),+  so the works snapshot is about 70% of the repository reads the reader+  waits on. The host was heavily loaded, so these are a reading and not+  a band; the final verification re-measures before and after in one+  session (Req 1.4). The target is now 46 tests in 7 suites; that run+  exited 0 with nine known issues, `dedupe-links-noop` having met its+  budget (`specs/launch-to-today/verification-run.md` §1).+ - **Catch-up mode: a `Catching up` reading status and a `Catching up`   section on Today (`specs/catch-up-mode/`).** A reader behind on a story   has no reason to wait for its release day. The reading status control@@ -936,6 +986,62 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ### Changed +- **Launch publishes Today first and loads the works snapshot behind+  it (`specs/launch-to-today/`, Decisions 3 and 4).** `bootstrap()` now+  opens with `publishToday()` — the Today read alone, with the schedule+  and the title map that came with it — and reaches `.ready` from that,+  falling back to the full refresh only when the Today publication+  throws or is abandoned. The works snapshot arrives afterwards in a+  launch tail, which retries once and only then runs the once-per-launch+  reconcile: the two compete for the exclusive lock and only the works+  read has a reader waiting on it. A new `worksLoad` state says whether+  that snapshot has been published, so an empty snapshot is no longer+  read as an empty library; `retryWorksLoad()` is the reader's way back+  from a failure, and every later refresh is a retry too. A+  `repositoryEpoch` stops a read started against a torn-down library+  from publishing into the one that replaced it, and the overlap,+  calendar and epoch guards are now one gate both publications pass+  through.++  Works and Stats sit behind one `WorksLoadGate`, which shows progress+  while the snapshot is being read and an error with Retry when the read+  threw. Answering it once at the screen boundary is what keeps the five+  readers of that snapshot from reporting "not loaded yet" as a fact+  about the library — an empty Works list, or Stats derived over no+  works. `WorksView` and `StatsView` are built only once it has loaded+  and are otherwise unchanged. ⌘F is now the Works tab's alone and waits+  for the load, since the search field it focuses is behind the gate;+  ⇧⌘E no longer shares that predicate, so Export stays available on+  Today.++  Measured over the 5,000-entry fixture, the repository reads the reader+  waits on before Today is drawable fell from **2.497 s to 0.852 s —+  1.645 s, or 65.9%**. The works read itself did not get cheaper (2.435 s+  after, −2.5%); it moved off the path the reader waits on. Both sides+  were measured twelve minutes apart on one busy host, so the pair is a+  like-for-like comparison and not a band, and it is repository read time+  rather than time-to-first-Today — the store open, the capture drain and+  the app-side work are what the new launch signpost reports+  (`specs/launch-to-today/verification-run.md` §4).++- **Today's schedule is built inside the Today read+  (`specs/launch-to-today/`, Decision 2, superseding `update-schedule`+  Q28).** `todayPresentation` now returns the Releasing and Catching up+  schedule and an unfiltered work-title map beside the rows, from the+  Entry rows it already holds: `TodaySchedule.admits` is the one+  spelling of the bucket test, only the work groups it admits are+  snapshotted, and their entries come from one bucketing of the rows by+  `work.id`, so nothing on the path traverses `work.entries`. The result+  equals `TodaySchedule.build(works: works().works, …)` over seven+  fixtures, including split groups, a dismissed pair and an empty+  library (`TodayScheduleEquivalenceTests`). Nothing in the app reads+  the new fields yet. Measured after the change, `todayPublication` is+  0.90 s against its 2 s budget (0.75 s before, the schedule build now+  being inside it), so the design's fallback was not needed. `works()`+  also stopped building entry snapshots it discarded for a group's+  representative and carrier (`specs/launch-to-today/verification-run.md`+  §2).+ - **Share sheet character chips (T-2317).** Both capture sheets drew a   work's cast as one text row, `Characters: Alice (Al, Ally), Bob`, so a   reader writing a chapter note could not see what they had written down
CLAUDE.md Modified +10 / -8
diff --git a/CLAUDE.md b/CLAUDE.mdindex 720ba6fa..bf615291 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -68,7 +68,7 @@ invocations where a target exists. - `make test-quick` — unit-test bundle only (simulator), preceded by `build-mac`: a macOS compile failure fails it (Req 9.1). The Mac build is never installed or launched. `SKIP_MAC=1` drops that dependency loudly and owes a clean `make build-mac` before the push. - `make test` / `make test-ui` — full suites (simulator, iPhone); they skip the iPad-only suites by name - `make test-ui-ipad` — the wide-layout and wide-layout-accessibility suites on `IPAD_SIMULATOR` (simulator, safe)-- `make test-performance-m4` — M4 Core budgets, host only, no device, safe to run. **~21 minutes** (1,093 s of test time measured 2026-08-28, 1,120 s over 28 tests on 2026-08-30 after `character-ranking` added its own, and **1,120.6 s over 32 tests on 2026-09-05** after T-1910 added four Work-bearing preview arms — all quiet-host runs, all `EXIT=0` with the same eight known issues, so the 21 minutes still holds and the four added arms cost no measurable wall time. T-2093 took the settling pass from ~7.3 s to ~1.7 s per sample; three contended runs on 2026-09-05 measured 1,136 s, 1,237 s and 1,085 s over the same 32 tests, all `EXIT=0` with **seven** known issues. A *loaded* run of those same 32 tests took 1,380 s and breached a regression ceiling on an untouched arm; that is host contention, not a band. Add a ~190 s release build to any of them): most of it is the worst-case single-hostname consolidation in `M4ScalePerformanceTests` (5 samples, each paying its own ~40 s divert before a ~40 s measurement) and the Req 10.1 settling pass (10 samples, each re-seeding 1,350 duplicate rows plus an untimed observation pass). The V4→V5 migration measurement is **gone** — `retire-migration-chain` deleted the pass it timed along with the suite. **The target exits 0 on a quiet host**, with the accepted breaches reported as `withKnownIssue` known issues rather than failures — **ten** since `work-thumbnails` (four before `multi-site-works`, nine after it, eight after `drop-superseded-columns`, seven after T-2093, eight after `series-and-related-works`, nine after `work-creators`), and **eleven on a loaded host**, because `creator-converge-noop` is wrapped `isIntermittent` and only records when the host is busy. Three are long-standing: Req 5.5's three diagnosis re-derivations. Three are Req 5.4's capture-projection arms (0.093–0.102 s pre-V8 → 0.160–0.170 s at V9 → 0.169–0.176 s at V10 → **0.179–0.205 s at V12** → 0.158–0.164 s at V13 on a quieter host, the one on a path the reader waits on; V12's three new tables and V13's two are empty on that path and cost it nothing the run's own host variance does not explain, still well inside a 250 ms ceiling). The seventh is the **full**-tier no-op reconcile, and V9 recovered most of it: 1.07 s → **0.0296–0.0302 s** once `V8PopulationPass` was deleted with the columns and `MembershipReconciler.heal` was gated on the diagnosis, which is still 3.0× a 10 ms ceiling drawn before the library had a membership table; V10 left it there (0.0301 s), V12 did too (0.0308 s) and so did V13 (0.0302 s). Req 10.1's *observation* pass **retired** with that fall (2.69 s → 1.01 s, back inside its 2 s budget, and 1.02 s at V10), and its **settling** pass retired at T-2093: 88% of that pass was SwiftData maintaining `Site.entries` inside the deletion phase's one `save` (6.42 s before the fix, 0.41 s after; the measured 8.0 ms per deleted row over a 5,000-row Site is supporting evidence, not the arithmetic — only the 250 Entry losers of the 300 deleted rows sit in `Site.entries`), and detaching a chunk's doomed rows from their Site in one rewrite of that array took it from 7.3 s to ~1.6 s, inside its 2 s budget, with the 11 s floor under the known issue gone too (`specs/bugfixes/settling-pass-budget/`, Decision 32). The eighth is `series-and-related-works` Req 14.6's link dedupe, a 10 ms budget measured at 0.0100–0.0112 s over 500 links — the low end is `place-extraction`'s run at 0.010032 s, 0.3% over the budget and the closest it has come to fitting, which would turn a quiet host into a *second* way to be red: the whole-table fetch the phase opens with is 79–83% of that, so the budget sits under what SwiftData charges to materialise the rows (Q59 of that spec). The ninth is `work-creators` Req 11.6's credit dedupe, a 50 ms budget measured at 0.0591–0.0651 s over ~2,000 credits, of which the whole-table fetch is 76% (Q73 of that spec, 130 ms ceiling). The intermittent eleventh is that spec's `creator-converge-noop`, in budget at 0.0081–0.0100 s against 10 ms across five samples and never more than 19% clear of it, so it is asserted `isIntermittent` with a 20 ms ceiling (Q74). The tenth is `work-thumbnails` Q80's **`backup-export-thumbnails` peak**: the real exporter over the covered fixture writes a **51.1 MB** archive and peaks **330–462 MB** over its baseline, past the 400 MB Q61 accepted from an estimate, recorded rather than re-based, with a 600 MB regression ceiling asserted outside the block. It is deliberately **not** `isIntermittent`, which means a run whose peak lands *under* 400 MB fails the target with `Known issue was not recorded` — that fired for the first time on 2026-09-13, on a memory-pressured host at 330.2 MB, and a lower peak there is the allocator reclaiming sooner, not the export getting cheaper (`specs/work-thumbnails/verification-run.md` §2.2). Its sibling `backup-import-thumbnails` **meets** the 400 MB plainly at 63.5–159.2 MB, with a settled baseline of 103–144 MB over five runs on one host (`specs/work-thumbnails/verification-run.md` §4.1), and `thumbnail-bytes-read` (fifty on-demand cover reads, Req 7.2) is reported only, 0.032–0.231 s under the 3 s class ceiling. Its other creator arms are `credits-resolve-and-filter` at 0.0144–0.0154 s under a 20 ms budget, `dedupe-credits-fetch` at 0.0477–0.0496 s reported only, `creator-detail` at 0.0363–0.0376 s under 50 ms, and the two read arms `works-snapshot-creators` (1.75–2.11 s) and `creators-list` (0.274–0.284 s) under the 3 s class ceiling. `series-and-related-works` adds `M4SeriesScalePerformanceTests` and `work-creators` adds `M4CreatorScalePerformanceTests`, so the suite count is 7 and the test count **45** since `update-schedule` added `todayPublication` — Req 10.5's Today composition arm, one more test in `M4ToleratedScalePerformanceTests` and no new suite — on top of the 44 `work-thumbnails` reached by adding three arms and no suite — `thumbnail-bytes-read`, `backup-export-thumbnails` and `backup-import-thumbnails`, all three in `M4DuplicateScalePerformanceTests` and all three reported rather than budgeted, together worth 2.5–4 minutes of the run. It was 41 at `place-extraction`, measured as one run at **1,070 s**; the three runs made on the `work-thumbnails` branch measured **1,896 s, 2,683 s and 5,037 s** on a machine that was never quiet, so they set no band and moved none — two of them disagree with each other by 1.7× on the same arms, and an arm that never opens a store doubled (`specs/work-thumbnails/verification-run.md` §2.3). **A quiet-host run of the covered fixture is still owed**, and since `catch-up-mode` that fixture also holds 66 base works on `catchingUp`, which `WorkAuthoredContent.isBare` counts as authored, so every band below the `todayPublication` arm (0.84 s on a loaded host, `specs/catch-up-mode/verification-run.md`) is unverified against the fixture as it now stands. That arm is `place-ranking-200x50` at **0.0035 s** against a 10 ms budget and a 50 ms ceiling, recorded beside its sibling `character-ranking-200x50` at **0.0037 s** — the ranker is one generic implementation over `RecordRow` and the point of the arm is that the second conformance costs what the first does. The character arm's own number moved up from 0.0023–0.0025 s in the same change, which is the cost of `CharacterRanking` becoming `RecordRanking`; read 0.0037 s as its new resting place, not as a regression. Every one has a regression ceiling asserted *outside* its known-issue block, so a run that drifts further still fails; `RUNS=3` completes all three runs. See `specs/work-thumbnails/verification-run.md` for the current numbers and for what a contended host does to all of them, `specs/place-extraction/verification-run.md` for the last quiet-host band, `specs/work-creators/verification-run.md` and `specs/bugfixes/settling-pass-budget/` for the previous ones, `specs/series-and-related-works/verification-run.md` for the ones before those, `specs/work-and-reading-status/verification-run.md` §4 for the previous ones, `specs/drop-superseded-columns/verification-run.md` and `specs/multi-site-works/verification-run.md` §4 and §7 for the previous ones, and `docs/agent-notes/testing.md` for recording a band.+- `make test-performance-m4` — M4 Core budgets, host only, no device, safe to run. **~21 minutes** (1,093 s of test time measured 2026-08-28, 1,120 s over 28 tests on 2026-08-30 after `character-ranking` added its own, and **1,120.6 s over 32 tests on 2026-09-05** after T-1910 added four Work-bearing preview arms — all quiet-host runs, all `EXIT=0` with the same eight known issues, so the 21 minutes still holds and the four added arms cost no measurable wall time. T-2093 took the settling pass from ~7.3 s to ~1.7 s per sample; three contended runs on 2026-09-05 measured 1,136 s, 1,237 s and 1,085 s over the same 32 tests, all `EXIT=0` with **seven** known issues. A *loaded* run of those same 32 tests took 1,380 s and breached a regression ceiling on an untouched arm; that is host contention, not a band. Add a ~190 s release build to any of them): most of it is the worst-case single-hostname consolidation in `M4ScalePerformanceTests` (5 samples, each paying its own ~40 s divert before a ~40 s measurement) and the Req 10.1 settling pass (10 samples, each re-seeding 1,350 duplicate rows plus an untimed observation pass). The V4→V5 migration measurement is **gone** — `retire-migration-chain` deleted the pass it timed along with the suite. **The target exits 0 on a quiet host**, with the accepted breaches reported as `withKnownIssue` known issues rather than failures — **ten** since `work-thumbnails` (four before `multi-site-works`, nine after it, eight after `drop-superseded-columns`, seven after T-2093, eight after `series-and-related-works`, nine after `work-creators`), and **eleven on a loaded host**, because `creator-converge-noop` is wrapped `isIntermittent` and only records when the host is busy. Three are long-standing: Req 5.5's three diagnosis re-derivations. Three are Req 5.4's capture-projection arms (0.093–0.102 s pre-V8 → 0.160–0.170 s at V9 → 0.169–0.176 s at V10 → **0.179–0.205 s at V12** → 0.158–0.164 s at V13 on a quieter host, the one on a path the reader waits on; V12's three new tables and V13's two are empty on that path and cost it nothing the run's own host variance does not explain, still well inside a 250 ms ceiling). The seventh is the **full**-tier no-op reconcile, and V9 recovered most of it: 1.07 s → **0.0296–0.0302 s** once `V8PopulationPass` was deleted with the columns and `MembershipReconciler.heal` was gated on the diagnosis, which is still 3.0× a 10 ms ceiling drawn before the library had a membership table; V10 left it there (0.0301 s), V12 did too (0.0308 s) and so did V13 (0.0302 s). Req 10.1's *observation* pass **retired** with that fall (2.69 s → 1.01 s, back inside its 2 s budget, and 1.02 s at V10), and its **settling** pass retired at T-2093: 88% of that pass was SwiftData maintaining `Site.entries` inside the deletion phase's one `save` (6.42 s before the fix, 0.41 s after; the measured 8.0 ms per deleted row over a 5,000-row Site is supporting evidence, not the arithmetic — only the 250 Entry losers of the 300 deleted rows sit in `Site.entries`), and detaching a chunk's doomed rows from their Site in one rewrite of that array took it from 7.3 s to ~1.6 s, inside its 2 s budget, with the 11 s floor under the known issue gone too (`specs/bugfixes/settling-pass-budget/`, Decision 32). The eighth is `series-and-related-works` Req 14.6's link dedupe, a 10 ms budget measured at 0.0100–0.0112 s over 500 links — the low end is `place-extraction`'s run at 0.010032 s, 0.3% over the budget and the closest it has come to fitting, which would turn a quiet host into a *second* way to be red: the whole-table fetch the phase opens with is 79–83% of that, so the budget sits under what SwiftData charges to materialise the rows (Q59 of that spec). The ninth is `work-creators` Req 11.6's credit dedupe, a 50 ms budget measured at 0.0591–0.0651 s over ~2,000 credits, of which the whole-table fetch is 76% (Q73 of that spec, 130 ms ceiling). The intermittent eleventh is that spec's `creator-converge-noop`, in budget at 0.0081–0.0100 s against 10 ms across five samples and never more than 19% clear of it, so it is asserted `isIntermittent` with a 20 ms ceiling (Q74). The tenth is `work-thumbnails` Q80's **`backup-export-thumbnails` peak**: the real exporter over the covered fixture writes a **51.1 MB** archive and peaks **330–462 MB** over its baseline, past the 400 MB Q61 accepted from an estimate, recorded rather than re-based, with a 600 MB regression ceiling asserted outside the block. It is deliberately **not** `isIntermittent`, which means a run whose peak lands *under* 400 MB fails the target with `Known issue was not recorded` — that fired for the first time on 2026-09-13, on a memory-pressured host at 330.2 MB, and a lower peak there is the allocator reclaiming sooner, not the export getting cheaper (`specs/work-thumbnails/verification-run.md` §2.2). Its sibling `backup-import-thumbnails` **meets** the 400 MB plainly at 63.5–159.2 MB, with a settled baseline of 103–144 MB over five runs on one host (`specs/work-thumbnails/verification-run.md` §4.1), and `thumbnail-bytes-read` (fifty on-demand cover reads, Req 7.2) is reported only, 0.032–0.231 s under the 3 s class ceiling. Its other creator arms are `credits-resolve-and-filter` at 0.0144–0.0154 s under a 20 ms budget, `dedupe-credits-fetch` at 0.0477–0.0496 s reported only, `creator-detail` at 0.0363–0.0376 s under 50 ms, and the two read arms `works-snapshot-creators` (1.75–2.11 s) and `creators-list` (0.274–0.284 s) under the 3 s class ceiling. `series-and-related-works` adds `M4SeriesScalePerformanceTests` and `work-creators` adds `M4CreatorScalePerformanceTests`, so the suite count is 7 and the test count **46** since `launch-to-today` added `launchReads` — Req 1.3's two reported-only arms, `launch-reads-full` and `launch-reads-today`, one more test in `M4ToleratedScalePerformanceTests` and no new suite — on top of the 45 `update-schedule` reached by adding `todayPublication` — Req 10.5's Today composition arm, likewise one more test in that suite and no new suite — on top of the 44 `work-thumbnails` reached by adding three arms and no suite — `thumbnail-bytes-read`, `backup-export-thumbnails` and `backup-import-thumbnails`, all three in `M4DuplicateScalePerformanceTests` and all three reported rather than budgeted, together worth 2.5–4 minutes of the run. It was 41 at `place-extraction`, measured as one run at **1,070 s**; the three runs made on the `work-thumbnails` branch measured **1,896 s, 2,683 s and 5,037 s** on a machine that was never quiet, so they set no band and moved none — two of them disagree with each other by 1.7× on the same arms, and an arm that never opens a store doubled (`specs/work-thumbnails/verification-run.md` §2.3). **A quiet-host run of the covered fixture is still owed**, and since `catch-up-mode` that fixture also holds 66 base works on `catchingUp`, which `WorkAuthoredContent.isBare` counts as authored, so every band below the `todayPublication` arm (**0.896 s** since `launch-to-today` amended it, see below; 0.84 s on a loaded host before that, `specs/catch-up-mode/verification-run.md`) is unverified against the fixture as it now stands. That arm is `place-ranking-200x50` at **0.0035 s** against a 10 ms budget and a 50 ms ceiling, recorded beside its sibling `character-ranking-200x50` at **0.0037 s** — the ranker is one generic implementation over `RecordRow` and the point of the arm is that the second conformance costs what the first does. The character arm's own number moved up from 0.0023–0.0025 s in the same change, which is the cost of `CharacterRanking` becoming `RecordRanking`; read 0.0037 s as its new resting place, not as a regression. `launch-to-today` added the two `launchReads` arms and **amended** `todayPublication`. The `launchReads` pair is reported with no budget and times the repository reads that stand between the store being open and Today being drawable: `launch-reads-full` (`todayPresentation` + `works` + `siteNames`) at **2.435 s** and `launch-reads-today` (`todayPresentation` + `siteNames`) at **0.852 s**, against 2.497 s for the full arm on the before commit measured twelve minutes earlier on the same host — a **1.645 s, 65.9%** fall in what the reader waits on, with the full arm itself unmoved (−2.5%), so the works read was relocated and not removed (`specs/launch-to-today/verification-run.md` §4). Read them as read time and not as time-to-first-Today: the store open, the capture drain and every app-side derivation sit outside them, and on a real library far fewer than 466 of 1,000 works qualify for Today. `todayPublication` no longer makes its own `works()` read or its own `TodaySchedule.build` call — `todayPresentation` builds the schedule and the work titles inside the read since Decision 2 of that spec — and it measures **0.896 s** median at spread 1.08×, inside its 2 s budget with 1.10 s of headroom, agreeing with the 0.903 s an independent run measured the same day. That whole-target run was 1,272.6 s over the 46 tests, `EXIT=0`, nine known issues. Every one has a regression ceiling asserted *outside* its known-issue block, so a run that drifts further still fails; `RUNS=3` completes all three runs. See `specs/launch-to-today/verification-run.md` for the launch figures and the one like-for-like before/after pair this target has been given, `specs/work-thumbnails/verification-run.md` for the current numbers and for what a contended host does to all of them, `specs/place-extraction/verification-run.md` for the last quiet-host band, `specs/work-creators/verification-run.md` and `specs/bugfixes/settling-pass-budget/` for the previous ones, `specs/series-and-related-works/verification-run.md` for the ones before those, `specs/work-and-reading-status/verification-run.md` §4 for the previous ones, `specs/drop-superseded-columns/verification-run.md` and `specs/multi-site-works/verification-run.md` §4 and §7 for the previous ones, and `docs/agent-notes/testing.md` for recording a band. - `make test-performance-chunks` — host-only calibration sweep of the shared bulk chunk constant (import commits and the reconciler re-pin). No device, safe to run, but gated on `ASTERISM_RUN_CHUNK_SWEEP=1` and **~20 minutes per run**, so it is deliberately *not* part of `make test-performance-m4`. It asserts nothing — a calibration is reported, not budgeted. Re-run it when the bulk write paths change (Q53 and the task 25 section of `specs/cloudkit-mirroring/implementation.md`). - `make test-performance-m4-recent` — **physical device, see above** @@ -258,13 +258,15 @@ over them, membership before the duplicate phase whose re-pointing composes with it. Do not add a reconciler outside this pass or reorder it without a decision. -**Triggers are a closed list.** Launch (after the first Today publication),-the sync-arrival debounce, import completion, a reader action that changes a-set, a committed capture (owner decision 2026-09-09, pending T-2329: today no-capture path schedules a pass, so a duplicate a capture creates waits for the-next launch or arrival), and one bounded self-scheduled follow-up. Never-inside the open path, never awaited on the capture path, never in the share-extension. The arrival tier runs+**Triggers are a closed list.** Launch (after the first works load has+published or failed — `launch-to-today` Decision 4 moved it off the first+Today publication, because the reader waits on that load and nobody waits on+the reconcile), the sync-arrival debounce, import completion, a reader action+that changes a set, a committed capture (owner decision 2026-09-09, pending+T-2329: today no capture path schedules a pass, so a duplicate a capture+creates waits for the next launch or arrival), and one bounded self-scheduled+follow-up. Never inside the open path, never awaited on the capture path,+never in the share extension. The arrival tier runs the cheap phases plus whatever the last scan counted; the full tier gates on the same counters, because a no-op full pass once regressed 1,450× (`duplicate-reconciliation` Decisions 28 and 30). Directory reconcilers run
docs/agent-notes/testing.md Modified +49 / -2
diff --git a/docs/agent-notes/testing.md b/docs/agent-notes/testing.mdindex 68d2ce58..4c875172 100644--- a/docs/agent-notes/testing.md+++ b/docs/agent-notes/testing.md@@ -11,6 +11,25 @@ Before claiming "no new compiler warnings", run the relevant build unwrapped and grep it: `make build-ios 2>&1 | grep -E "warning:|⚠️"` for the app target, `swift build 2>&1 | grep warning:` for the package. +### The release test bundle builds through `swift test`, never `swift build --build-tests`++`swift build --package-path Packages/AsterismCore --build-tests -c release`+**fails deterministically** at `ConstellationKitTests`:++```+unable to resolve Swift module dependency to a compatible module: 'ConstellationKit'+```++It is not a broken tree and not a stale module. `swift build --build-tests` does+not pass `-enable-testing`, and in release that leaves `@testable import+ConstellationKit` with nothing to import; debug is unaffected because+testability is on there by default, which is why the forced-recompile check+above never meets it. `swift test -c release` does pass the flag, and that is+what `make test-performance-m4` builds through. So a release build of the test+bundle — to warm it before a measured run, or to read its warnings — is a+`swift test -c release` run narrowed with `--filter` to one cheap arm, not a+`swift build` (`specs/launch-to-today/verification-run.md` §4.6).+ ## Xcode can miss an AsterismCore edit and report it as an app-target error  Editing a file under `Packages/AsterismCore/Sources/` and then running@@ -94,6 +113,29 @@ investigating. the same way and for the same reason (seen 2026-09-06, T-2308); it belongs to the family above. +## `bootstrap()` no longer publishes the works snapshot; await `waitForLaunchTail()`++Since `launch-to-today` a launch publishes **twice**. `bootstrap()` publishes+Today alone (`publishToday()`: the presentation, the schedule, the site names+and `workTitlesByID`) and returns; the works snapshot arrives from an ordinary+`refreshAll()` running in `launchTask` afterwards, with the launch reconcile+behind it. Two consequences for `AsterismTests`:++- A test that calls `bootstrap()` and then reads `worksSnapshot`,+  `worksFilterOptions` or `worksLoad` gets the pre-load state, not an empty+  library. `await model.waitForLaunchTail()` first — it awaits the first works+  load, the one further attempt it may make and the reconcile+  (`AppLibraryModel.swift`). It is the rename of `waitForLaunchReconcile`, and+  26 call sites gained the await with it, so a neighbouring suite shows the+  shape.+- `snapshotGeneration` bumps **twice** per launch, not once. Anything asserting+  a generation value, or counting `.task(id: snapshotGeneration)` reloads, has+  to count both.++The launch sequence itself — the two publications, `worksLoad`,+`repositoryEpoch` and why the reconcile follows the load — is+`specs/launch-to-today/design.md`.+ ## Adding recorded state to `MockLibraryProvider` needs a lock  `MockLibraryProvider` is `@unchecked Sendable` and its counters are plain@@ -384,9 +426,14 @@ samples and costs no measurable wall time). `work-thumbnails` then added and all three reported rather than budgeted — `thumbnail-bytes-read` (Req 7.2), `backup-export-thumbnails` and `backup-import-thumbnails` (Req 8.6, Q68) — so the test count is **44** — and `update-schedule` added one arm, `todayPublication`-(Req 10.5), and no suite, so the current shape of the target is **45 tests in 7+(Req 10.5), and no suite, so the target was **45 tests in 7 suites**, measured over three runs at 1,175–1,211 s-(`specs/update-schedule/verification-run.md` §5). Measured on their own, filtered, release, two runs+(`specs/update-schedule/verification-run.md` §5) — and `launch-to-today` added+one more, `launchReads` (Req 1.3, two reported-only arms), and no suite, so the+current shape is **46 tests in 7 suites**, measured on a loaded host at 1,239 s,+1,174 s and 1,272.6 s (`specs/launch-to-today/verification-run.md` §1, §2 and+§4.3 — the first and last `EXIT=0` with nine known issues, the middle one+`EXIT=2` on the documented `backup-export-thumbnails` under-peak). Measured on their own, filtered, release, two runs (the second on a busier host, which is what the duration spread is): `thumbnail-bytes-read` **0.055 s / 0.169 s / 0.091 s** median for fifty on-demand reads (1.1–3.4 ms each, against a 3 s class ceiling);
specs/OVERVIEW.md Modified +3 / -2
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 4f0edf22..22d79a5c 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -47,7 +47,7 @@ | [Update Schedule](#update-schedule) | 2026-09-15 | Done — all 30 tasks implemented 2026-09-16; `make test-core` (3,013 tests, zero known issues), `make test-quick`, `make test-ui-ipad` (27/27) green, `make test-performance-m4 RUNS=3` with the ten documented known issues and `todayPublication` at 0.80–0.88 s under a 2 s budget; the owner's device steps in `prerequisites.md` remain | Full spec. A reader-set list of release weekdays on every work under schema V15 with markers `"14"` → `"15"` and the archive at 14/15, set by seven toggles in the editor's Status card and shown on the meta line; the Recent tab becomes **Today**, a week strip over the day's releases and notes with its own typed route stack, inheriting Recent's banners, duplicate sections and search and superseding the 100-row cap; a Works filter finds works with no days. Manual only, no model. | | [Catch-Up Mode](#catch-up-mode) | 2026-09-16 | Done — both phases landed 2026-09-17; four pre-existing UI-test failures recorded in its verification run. Open: the full `make test-performance-m4` has not been run against the fixture with its 66 catch-up works | Smolspec. A fourth reading status, `catchingUp`, for a work the reader is behind on: it shows in a `Catching up` section on Today on the current day and future days whatever its work status or release days, while its release days are parked; no schema bump and no archive generation bump. | | [Share Sheet Character Chips](#share-sheet-character-chips) | 2026-09-18 | In Progress | Smolspec (T-2317). The share sheets' cast text row becomes name-only chips; tapping one opens an inline card with that character's aliases and note, never facts. A cast past two chip rows collapses behind a `+N more` chip (Decision 1). Read-only, no schema change; `FlowLayout` moves into ConstellationKit. Supersedes `share-sheet-characters` Q2 (notes) and Q6 (no pills). |-| [Launch to Today](#launch-to-today) | 2026-09-19 | Planned | Full spec. Today appears without waiting for the works snapshot: its schedule is built inside the Today read (superseding `update-schedule` Q28), the works snapshot loads in the background behind a gate on Works and Stats, and the launch reconcile follows that load. Adds a launch-to-Today measurement with no budget yet, and removes the search field from Today while keeping the filter for T-2347. No schema change. |+| [Launch to Today](#launch-to-today) | 2026-09-19 | Done | Full spec. Today appears without waiting for the works snapshot: its schedule is built inside the Today read (superseding `update-schedule` Q28), the works snapshot loads in the background behind a gate on Works and Stats, and the launch reconcile follows that load. Adds a launch-to-Today measurement with no budget yet, and removes the search field from Today while keeping the filter for T-2347. No schema change. |  --- @@ -792,7 +792,7 @@ Smolspec. Both capture sheets draw the work's cast as chips carrying the main na  ## Launch to Today -**Created:** 2026-09-19 · **Status:** Planned — requirements, design and 15 tasks approved 2026-09-20; Q1–Q23 and Decisions 1–4 in the log. Nothing implemented.+**Created:** 2026-09-19 · **Status:** Done — all 15 tasks implemented 2026-09-20 across seven phases, two streams run in parallel; Q1–Q23 and Decisions 1–4 in the log. Verified in `verification-run.md`: `make test-core` 3,011 tests with zero known issues, `make test-quick` 1,681 passing, `make test-ui-ipad` green, and `make test-ui` at 182 executed with four failures (exit 2). The launch saving comes from two measurements twelve minutes apart on one host — a filtered `swift test` of the two arms at the task 1 commit, then the full `make test-performance-m4` at the final one: `launch-reads-full` 2.497 s before against `launch-reads-today` 0.852 s after, **1.645 s or 65.9%**, with the amended `todayPublication` at 0.896 s inside its 2 s budget, so the design's fallback was never needed. **The host was busy for both, so neither sets a band**; what the pair gives is a like-for-like comparison rather than an absolute (`verification-run.md` §4.1). The runs also found that the wide layout's work-name test had asserted behaviour `update-schedule` Q77 superseded; that three Works filter-menu tests fail on ambiguous accessibility labels (T-2353, not caused by this spec); and one `AccessibilityJourneyUITests` failure that is an artefact of running on `iPhone 18 Pro Max`, with a confirming run on the default simulator still owed. Still the owner's, in `prerequisites.md`: the two device launch readings and the Mac check.  Full spec. Launch awaited a full refresh before showing anything, and the works snapshot was the largest part of it (1.6–2.1 s of roughly 3.1–3.6 s, host release over the 5,000-entry fixture), on Today's path only because the schedule was derived from it. The schedule moves into the Today read, built from rows that read already holds (Decision 2, superseding `update-schedule` Q28). Launch publishes Today alone, then runs an ordinary full refresh in the background as the first works load, with Works and Stats behind one gate view showing progress or an error with Retry (Decision 3). The launch reconcile follows that load rather than the first Today publication, because the repository lock gives the loser a timeout, not a queue (Decision 4). Today loses its search field; the filter stays in the code and T-2347 moves note search to Works (Decision 1, superseding the search clauses of `update-schedule` Q4, Q10 and Req 3.3). A `LaunchToToday` signpost and a reported `launchReads` performance arm are added; a budget is set later from the band (Q4). A day-windowed Today is a recorded follow-up (Q5). The owner's device readings are in `prerequisites.md`. @@ -801,3 +801,4 @@ Full spec. Launch awaited a full refresh before showing anything, and the works - [tasks.md](launch-to-today/tasks.md) - [decision_log.md](launch-to-today/decision_log.md) - [prerequisites.md](launch-to-today/prerequisites.md)+- [verification-run.md](launch-to-today/verification-run.md)
specs/launch-to-today/tasks.md Modified +15 / -15
diff --git a/specs/launch-to-today/tasks.md b/specs/launch-to-today/tasks.mdindex 978db232..369207f9 100644--- a/specs/launch-to-today/tasks.md+++ b/specs/launch-to-today/tasks.md@@ -8,7 +8,7 @@ references:  ## Baseline -- [ ] 1. Add the launchReads performance arm and record the before figures <!-- id:inmfi3k -->+- [x] 1. Add the launchReads performance arm and record the before figures <!-- id:inmfi3k -->   - Add `launchReads` to `Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift`, reported with no budget: `launch-reads-full` times todayPresentation + works + siteNames, `launch-reads-today` times todayPresentation + siteNames   - No AsterismCore or AppLibraryModel change may land before the before figures are recorded. The Today search stream touches neither and may proceed   - Run `make test-performance-m4` (host only, about 21 minutes plus a release build) and record both figures, the host and the commit in a new `specs/launch-to-today/verification-run.md`. Never the `-m4-recent` target@@ -18,7 +18,7 @@ references:  ## Core -- [ ] 2. Write schedule equivalence, work titles and admits tests <!-- id:inmfi3l -->+- [x] 2. Write schedule equivalence, work titles and admits tests <!-- id:inmfi3l -->   - Core tests, Swift Testing, in `Packages/AsterismCore/Tests/AsterismCoreTests/`   - Equivalence: `todayPresentation(calendar:).schedule == TodaySchedule.build(works: works().works, calendar:)` over each fixture: M4 composed; a same-UUID split work group whose rows disagree on reading status; a dismissed cross-site pair; a split entry group whose rows point at two different works; a finished catching-up work that carries release days; a scheduled work with no entries; an empty library   - `presentation.workTitles` equals the id-to-displayTitle map of `works().works`, including a blank-titled work@@ -28,7 +28,7 @@ references:   - Stream: 1   - Requirements: [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4) -- [ ] 3. Build the schedule and work titles inside todayPresentation <!-- id:inmfi3m -->+- [x] 3. Build the schedule and work titles inside todayPresentation <!-- id:inmfi3m -->   - `TodayDayPlan.swift`: extract `TodaySchedule.admits(readingStatus:workStatus:releaseDays:)` and make `build` use it   - `LibraryRepository.swift` near :1955: split `snapshot(_ work:types:series:credits:)` into a fields-only core taking the entry snapshots, with the existing signature passing `work.entryValues`   - `LibraryRepository+Groups.swift`: add the internal overload `snapshot(_ group:entryRows:canonicalWorkIDs:types:series:credits:)`, deriving representative and carrier fields through the core with no entries. No `work.entries` traversal on this path (docs/agent-notes/swiftdata-relationships.md)@@ -39,7 +39,7 @@ references:   - Stream: 1   - Requirements: [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4) -- [ ] 4. Verify the presentation cost against its budget <!-- id:inmfi3n -->+- [x] 4. Verify the presentation cost against its budget <!-- id:inmfi3n -->   - Design Risk 1. Run `make test-performance-m4` and record `todayPublication` and both `launchReads` figures in `verification-run.md` as the post-Core figures   - If `todayPublication` is over its 2 s budget, apply the design's fallback: take each admitted work's notedDays from the EntrySnapshots the row loop already produced instead of snapshotting the bucketed rows again. The task 2 equivalence tests must still pass   - Judge against a quiet host: a loaded run sets no band (CLAUDE.md, Performance measurement)@@ -50,7 +50,7 @@ references:  ## App model -- [ ] 5. Write AppLibraryModel tests for the two launch publications and the launch tail <!-- id:inmfi3o -->+- [x] 5. Write AppLibraryModel tests for the two launch publications and the launch tail <!-- id:inmfi3o -->   - `Asterism/AsterismTests/AppLibraryModelTests.swift`, using the `worksReadFault` init parameter directly   - After bootstrap: `.ready` with `worksLoad == .loading` observable before the tail finishes; after `waitForLaunchTail`: `.loaded`, two generation bumps, non-empty worksSnapshot   - `todaySchedule` and `workTitlesByID` after publishToday equal their values after the following refreshAll; a restored work id resolves against the map at both publications@@ -63,7 +63,7 @@ references:   - Stream: 1   - Requirements: [2.1](requirements.md#2.1), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.3](requirements.md#3.3), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [3.7](requirements.md#3.7), [3.8](requirements.md#3.8), [3.9](requirements.md#3.9), [3.10](requirements.md#3.10), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2) -- [ ] 6. Implement publishToday, the works load state and the launch tail <!-- id:inmfi3p -->+- [x] 6. Implement publishToday, the works load state and the launch tail <!-- id:inmfi3p -->   - `Asterism/Asterism/ViewModels/AppLibraryModel.swift` only; no view change in this task   - `repositoryEpoch`, incremented in `teardownRepository()` before its first suspension; one private gate helper shared by publishToday and refreshAll: Q60 overlap, Q44 calendar, epoch unchanged. No cancellation gate in refreshAll (Q18)   - `WorksLoadState` and `worksLoad`; `.loaded` set inside refreshAll's publish block; catch sets `.failed` only when `worksLoad != .loaded` and the epoch is unchanged@@ -79,7 +79,7 @@ references:  ## Screens -- [ ] 7. Write NavigationActions tests and the works load gate UI test <!-- id:inmfi3q -->+- [x] 7. Write NavigationActions tests and the works load gate UI test <!-- id:inmfi3q -->   - Unit: `NavigationActions` has `find == nil` and `export != nil` on `.today` with a subject; on `.works`, `find` follows a new `worksLoaded` input and `export` does not; `worksLoaded` takes part in `==`   - UI: launch with `ASTERISM_UI_TEST_WORKS_LOAD=fail-until-retry`; `works-load-failed` shows on Works and on Stats, Today's `recent-list` is usable, `works-load-retry` brings up `works-list`   - Identifiers by accessibility id, never by text@@ -87,7 +87,7 @@ references:   - Stream: 1   - Requirements: [3.2](requirements.md#3.2), [3.4](requirements.md#3.4), [3.6](requirements.md#3.6), [3.7](requirements.md#3.7), [5.2](requirements.md#5.2) -- [ ] 8. Implement WorksLoadGate, its wiring and the Find availability change <!-- id:inmfi3r -->+- [x] 8. Implement WorksLoadGate, its wiring and the Find availability change <!-- id:inmfi3r -->   - New `Asterism/Asterism/Layout/WorksLoadGate.swift`: takes state, retry, navigation title, `showsSky` and content. Loading matches ContentView's `app-loading` presentation; failed matches its `app-unavailable` block including the minHitTarget frame. Identifiers `works-loading`, `works-load-failed`, `works-load-retry`   - The gate applies `.screenSky(showsSky)` and the title to its own states, and supplies the NavigationStack on compact Stats, which StatsView otherwise owns (`AppScreens.swift:368`)   - Wrap `AppScreens.works()` and `AppScreens.stats()`; check the wide layout columns as well as the compact tabs@@ -99,14 +99,14 @@ references:  ## Today search -- [ ] 9. Rewrite the Today search UI tests for a Today without a search field <!-- id:inmfi3s -->+- [x] 9. Rewrite the Today search UI tests for a Today without a search field <!-- id:inmfi3s -->   - Remove `SearchUITests`' three Recent search tests and `TodayUITests.testSearchHidesTheDayChromeAndClearingBringsItBack`, with the Today-only `type` and `clearQuery` helpers they leave unused. The Works search tests stay   - Add: Today presents no search field; and a banner filter hides `today-week-range` and the releases sections and clearing it restores them, replacing the day-chrome coverage the removed test carried   - The no-search-field test also runs in the iPad suite selected by `make test-ui-ipad`   - Stream: 2   - Requirements: [5.1](requirements.md#5.1), [5.3](requirements.md#5.3) -- [ ] 10. Remove the search field from TodayView and keep the filter <!-- id:inmfi3t -->+- [x] 10. Remove the search field from TodayView and keep the filter <!-- id:inmfi3t -->   - `Views/TodayView.swift`: remove `searchQuery`, `searchFilter`, `searchFocusRequest` and `.listSearch`; default `TodayDisplayPlan.init`'s `searchFilter` to `RecentSearchFilter(query: "")`; `.searchMiss` stays in the plan and renders `ContentUnavailableView.search`   - `Layout/AppScreens.swift:85`: stop passing `searchFocusRequest(for: .today)`   - Do not touch `ViewModels/SearchFilters.swift`, the plan's filter path, `AppNavigation` or their unit tests (Req 5.4, T-2347)@@ -117,7 +117,7 @@ references:  ## Measurement -- [ ] 11. Write tests for the launch phase record <!-- id:inmfi3u -->+- [x] 11. Write tests for the launch phase record <!-- id:inmfi3u -->   - The phase record is a small value type the signposts and the log line are both built from, so it is testable without OSLog   - Phases ExportPassWait, StoreOpen, CaptureDrain, TodayReads; UI-test seeding belongs to none; outcomes `published`, `fellBack`, `nothing`, `unavailable`   - bootstrap cancels and awaits an in-flight background-export pass before StoreOpen begins, asserted on the record (`AppLibraryModelBackgroundExportTests` has the setup)@@ -125,7 +125,7 @@ references:   - Stream: 1   - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2) -- [ ] 12. Emit the LaunchToToday signposts and the launch notice line <!-- id:inmfi3v -->+- [x] 12. Emit the LaunchToToday signposts and the launch notice line <!-- id:inmfi3v -->   - `AppLibraryModel.bootstrap()`: one `LaunchToToday` interval with the four child intervals, on an OSSignposter using `M2PerformanceSignposts`' subsystem and category; ends when `state` leaves `.loading`   - One `.notice` line with the outcome, the four durations and the total in milliseconds. Numbers and the outcome only; no reader content, so it is readable in `Personal` builds too   - Not configuration-gated@@ -135,7 +135,7 @@ references:  ## Verification -- [ ] 13. Run the full host and simulator suites and fix what they find <!-- id:inmfi3w -->+- [x] 13. Run the full host and simulator suites and fix what they find <!-- id:inmfi3w -->   - `make test-core`, `make test-quick`, `make test-ui`, `make test-ui-ipad`. All simulator or host; none touches a device   - Design Assumption: a fixture's works load finishes within the default element wait once Works is selected. Where a suite proves it wrong, wait on the content identifier with the 60 s timeout already used for `recent-list`   - The Today suites that assert `today-section-releases` and `today-section-catching-up` straight after `recent-list` must pass unchanged; that is the Req 2.2 check@@ -144,7 +144,7 @@ references:   - Stream: 1   - Requirements: [2.2](requirements.md#2.2), [3.2](requirements.md#3.2), [5.1](requirements.md#5.1) -- [ ] 14. Record the after figures in the verification run <!-- id:inmfi3x -->+- [x] 14. Record the after figures in the verification run <!-- id:inmfi3x -->   - One `make test-performance-m4` run at the final commit, same host as task 1 and in one session with a re-run of the task 1 commit if the host state has changed   - Record in `specs/launch-to-today/verification-run.md`: the four `launchReads` figures, the `todayPublication` band, the run's exit status and known-issue count. Results go in that file, never in tasks.md   - State the launch saving as `launch-reads-full` before against `launch-reads-today` after@@ -152,7 +152,7 @@ references:   - Stream: 1   - Requirements: [1.4](requirements.md#1.4) -- [ ] 15. Amend CLAUDE.md and mark the superseded update-schedule decisions <!-- id:inmfi3y -->+- [x] 15. Amend CLAUDE.md and mark the superseded update-schedule decisions <!-- id:inmfi3y -->   - CLAUDE.md: the Convergence trigger list reads `Launch (after the first works load has published or failed)`; the `test-performance-m4` paragraph names the `launchReads` arm and the amended `todayPublication` arm   - `specs/update-schedule/decision_log.md`: mark Q28 superseded by launch-to-today Decision 2, and the search clauses of Q4 and Q10 by Decision 1; note Req 3.3 in `requirements.md` the same way   - Add a `docs/agent-notes/` note only if the launch sequence would otherwise be re-investigated: the two publications, `worksLoad`, `repositoryEpoch` and why the reconcile follows the load
specs/launch-to-today/verification-run.md Added +609 / -0
diff --git a/specs/launch-to-today/verification-run.md b/specs/launch-to-today/verification-run.mdnew file mode 100644index 00000000..c6f49177--- /dev/null+++ b/specs/launch-to-today/verification-run.md@@ -0,0 +1,609 @@+# Verification Run: Launch to Today++The measurement evidence for this spec, recorded here rather than in `tasks.md`,+which `rune` owns.++## 1. Before figures (task 1)++**Date**: 2026-09-20, 02:06–02:27 AEST+**Commit**: `d01660c3` (`feature/launch-to-today`), worktree+`.claude/worktrees/launch-to-today`, **plus the uncommitted `launchReads` arm**+in `M4ToleratedScalePerformanceTests.swift`. That arm is the only code+difference from `d01660c3`: no `AsterismCore` source and no app source had+changed, so these are the figures for the launch as it stands before the+feature. The arm is committed together with this file.+**Host**: the project machine — `Mac13,1` (Apple M1 Max, 10 cores), macOS 27.0+(26A428).+**Host only.** `make test-performance-m4` is a `swift test` run of the+`AsterismCore` package. No device target was run, nothing was installed or+launched, and `CONFIRM_DEVICE_RUN` was not set.++### 1.1 The host was not quiet++| When | Load averages (1 / 5 / 15 min) |+|---|---|+| Before anything was built (01:56) | 7.21 / 7.05 / 7.15 |+| Immediately before the run (02:06) | 223.87 / 125.13 / 59.15 |+| After the run (02:27) | 140.61 / 105.01 / 81.25 |++The 02:06 reading follows a 500 s release build of the test bundle and a+filtered run of the new arm, both made to check the arm compiled and ran before+spending 21 minutes on the target. Beside that, `mediaanalysisd` (~90% of a+core), Time Machine's `backupd` (~55%), `dasd` and `photolibraryd` were busy+throughout, none of them anything this run could stop. Read every figure below+as a loaded-host figure. The medians held up better than the tails did: see the+spreads.++**One run is not a baseline.** `percentile(of:)` returns the second-slowest of+twenty samples, so one scheduling hiccup sets a p95 (`CLAUDE.md`, Performance+measurement). Req 1.4 asks for before and after on the same host in the same+session; the after figures are owed by the final task, and if that run happens+in a different session this section should be re-measured beside it rather+than compared across sessions.++### 1.2 The run++```+make test-performance-m4 PERFORMANCE_LOG=/tmp/l2t-m4-perf.log+```++`Test run with 46 tests in 7 suites passed after 1238.856 seconds with 9 known+issues.` **`EXIT=0`.** The release build was already warm (0.50 s); cold it+took 500.48 s on this host a few minutes earlier.++**Nine known issues, not ten, and that is explained.** The nine are Req 5.4's+three capture-projection arms, Req 5.5's three diagnosis re-derivations, the+full-tier no-op reconcile, `dedupe-credits-noop` (0.0536 s against 50 ms) and+the `backup-export-thumbnails` peak (**412.5 MB**, over the 400 MB and under+the 600 MB ceiling, so Q80's plain known issue recorded as it should). The one+that did not record is `dedupe-links-noop`, which measured **0.008782 s** and+so *met* its 10 ms budget; its block is `isIntermittent`+(`M4SeriesScalePerformanceTests.swift:227`), so meeting the budget is not a+failure. `creator-converge-noop`, the intermittent one a loaded host usually+adds, measured 0.006580 s and stayed inside its budget too. No regression+ceiling was reached on any arm.++### 1.3 The figures++```+ASTERISM-PERF launch-reads-full median=2.572540s p95=4.153633s min=2.419457s max=7.419337s spread=3.07x n=20+ASTERISM-PERF launch-reads-today median=0.772299s p95=0.848675s min=0.738232s max=1.106705s spread=1.50x n=20+ASTERISM-PERF todayPublication median=0.752713s p95=0.776108s min=0.741829s max=0.784231s spread=1.06x n=20+```++| Arm | Times | Median | p95 | min–max | Budget |+|---|---|---|---|---|---|+| `launch-reads-full` | `todayPresentation` + `works` + `siteNames` | **2.572540 s** | 4.153633 s | 2.419–7.419 s | none, reported |+| `launch-reads-today` | `todayPresentation` + `siteNames` | **0.772299 s** | 0.848675 s | 0.738–1.107 s | none, reported |+| `todayPublication` | unchanged arm, Req 10.5 of `update-schedule` | **0.752713 s** | 0.776108 s | 0.742–0.784 s | 2 s, met |++Read together: on this run the works snapshot is **1.80 s of the 2.57 s**+the reader waits on in repository reads, 70% of it, which is the saving the+design is after. `works-snapshot-duplicate-free` in the same run measured+2.217 s (spread 2.78×) on its own store, so the two readings of `works()` agree+about its size and about how much a loaded host moves it.++`launch-reads-full`'s tail is the host: its spread is 3.07× against 1.50× and+1.06× for the two arms that do not call `works()`, and `works()` is the+allocation-heavy read of the three. The filtered run made ten minutes earlier,+under the heaviest load of the session, measured the same arm at **3.160 s**+median (p95 4.480 s, max 6.828 s) and `launch-reads-today` at **0.788 s** — the+Today-only figure moved 2%, the full figure 23%. Take 2.57 s as the before+figure and 0.77 s as the figure the after run has to be compared with, and+treat the full figure's second decimal as noise.++### 1.4 What the arm does not cover++The store open, the pending-capture drain and the app-side derivations+(`TodaySchedule.build`, the title fold) are outside it; those belong to the+`LaunchToToday` signpost, which a later task adds. The before figure for+`launch-reads-today` does not yet include building the schedule inside+`todayPresentation` (Decision 2) — that cost lands in the after figure, and+`todayPublication`'s 2 s budget is the bound on it.++## 2. Post-Core figures (task 4)++**Date**: 2026-09-20, 03:37–04:04 AEST — the same night as section 1, about+ninety minutes later, on the same machine. Not the same process session, and+the load was different (2.1), so read the comparisons below with that in mind.+**Commit**: `229f37c1` (`feature/launch-to-today`), clean tree. The Core change+under measurement is `29bf129e`, which builds the schedule and the work titles+inside `todayPresentation`.+**Host**: the same `Mac13,1` (Apple M1 Max, 10 cores), macOS 27.0.+**Host only.** `make test-performance-m4`, once. No device target, nothing+installed or launched, `CONFIRM_DEVICE_RUN` not set.++### 2.1 The host was loaded, less than in section 1++| When | Load averages (1 / 5 / 15 min) |+|---|---|+| Immediately before the run (03:37) | 12.75 / 36.48 / 65.26 |+| After the run (04:04) | 11.11 / 10.30 / 18.01 |++At the start another job's simulator UI tests were running on this machine+(the simulator's `Asterism.app` at ~99% of a core, `pairedsyncd` at ~33%),+beside `mediaanalysisd` (~58%) and `dasd` (~57%). At the end the simulator+process was gone and `mediaanalysisd` (~131%), `dasd` (~61%) and Time Machine's+`backupd` (~49%) were the busy ones. A load of 10–12 on ten cores is a busy+host, not a quiet one, so **this run sets no band**. It was far calmer than+section 1's 140–220, and the spreads show it: every arm below is at 1.05–1.11×,+where section 1's `launch-reads-full` was at 3.07×.++### 2.2 The run++```+make test-performance-m4 PERFORMANCE_LOG=/tmp/l2t-m4-perf-task4.log+```++`Test run with 46 tests in 7 suites failed after 1174.066 seconds with 9 issues+(including 8 known issues).` **`EXIT=2`.** The release build before it was cold+at 436.40 s; wall time for the target was 26 min 54 s.++**The one failure is `backup-export-thumbnails`, and it is the documented+one.** `M4DuplicateScalePerformanceTests.swift:389`: `Known issue was not+recorded`. The exporter peaked at **350.1 MB** (51.1 MB archive, 15.4 s),+*under* the 400 MB that Q80 wraps as a plain, non-intermittent known issue, so+the block had nothing to record and the test failed for meeting its budget.+`CLAUDE.md` describes exactly this, first seen on 2026-09-13 at 330.2 MB on a+memory-pressured host. The arm is not touched by this spec, and no regression+ceiling was reached on any arm. The target was **not** re-run: a second run+would have cost another 20 minutes on the same busy host to change an exit+status, not a figure this task needs.++**Eight known issues**: Req 5.4's three capture-projection arms, Req 5.5's three+diagnosis re-derivations, the full-tier no-op reconcile, and+`dedupe-credits-noop` (0.0574 s against 50 ms). The two intermittent ones both+met their budgets and so recorded nothing: `dedupe-links-noop` at 0.008674 s+against 10 ms, `creator-converge-noop` at 0.007260 s against 10 ms. With the+export peak that is the ten of `CLAUDE.md` less two that met and one that met+and is not allowed to.++### 2.3 The figures++```+ASTERISM-PERF todayPublication median=0.903413s p95=0.924825s min=0.882529s max=0.926468s spread=1.05x n=20+ASTERISM-PERF launch-reads-full median=2.550620s p95=2.650248s min=2.419140s max=2.674735s spread=1.11x n=20+ASTERISM-PERF launch-reads-today median=0.912349s p95=0.938449s min=0.896347s max=0.945043s spread=1.05x n=20+```++| Arm | Before (§1) median / p95 / spread | After median / p95 / spread | Change in median |+|---|---|---|---|+| `todayPublication` | 0.752713 s / 0.776108 s / 1.06× | **0.903413 s** / 0.924825 s / 1.05× | +0.151 s (+20%) |+| `launch-reads-full` | 2.572540 s / 4.153633 s / 3.07× | **2.550620 s** / 2.650248 s / 1.11× | −0.022 s (−1%) |+| `launch-reads-today` | 0.772299 s / 0.848675 s / 1.50× | **0.912349 s** / 0.938449 s / 1.05× | +0.140 s (+18%) |++**Verdict on Risk 1: `todayPublication` is within its 2 s budget**, at 0.90 s+median and 0.92 s p95 with 1.08 s of headroom, and the arm's own assertion+passed. The design's fallback (notedDays from the row loop's EntrySnapshots)+was **not applied** and no code changed. The host was not quiet, so 0.90 s is a+reading and not a band; but a loaded host only inflates a figure, the spread is+1.05×, and the margin is more than the whole measurement, so the verdict does+not depend on a quieter run.++**What the +0.15 s is.** Both arms that call `todayPresentation` rose by the+same amount (+0.151 s and +0.140 s) at tight spreads, on a host calmer than the+one the before figures came from, so it is cost and not load: the schedule+build, the bucketed-row snapshots and the title fold that Decision 2 moved+inside the read. That is the price section 1.4 said would land here. The+before arm timed a schedule build too — it called `TodaySchedule.build` itself+inside the closure — but over a `works()` snapshot read *outside* it, so the+work snapshots that build consumed were free. Now they are produced inside+the timed read.++**`launch-reads-full` did not move, and two things cancel inside it.** It+carries the same +0.15 s from `todayPresentation`, and `works()` got cheaper+for a reason that has nothing to do with the launch change: `29bf129e` made the+group `snapshot(_:canonicalWorkIDs:…)` delegate to the new `entryRows` overload+with `entries: []` for the representative and the carrier, so `works()` no+longer builds per-row entry snapshots it threw away.+`works-snapshot-duplicate-free` in this run measured **1.596 s** (p95 1.658 s,+spread 1.12×) against 2.217 s (spread 2.78×) in section 1's. Some of that 0.62 s+is the calmer host and some is the saved work; one run on each side of a load+difference this size cannot split them, and this file does not try.++**The launch saving (Req 1.4), provisionally**: `launch-reads-full` before,+2.573 s, against `launch-reads-today` after, 0.912 s — **1.66 s, 65%** of the+repository reads the reader waits on. After the change the background load's+read cost is `launch-reads-full` after, 2.551 s. Req 1.4 asks for both sides in+one session on one host; the final task owes that run, and these two sides were+measured ninety minutes apart under different load, so treat 1.66 s as the+expected size and not the recorded one.++## 3. Suite runs (task 13)++**Date**: 2026-09-20, 11:57–15:10 AEST.+**Commit**: `803a14bf` (`feature/launch-to-today`), clean tree, plus the one+test change this task made (`WideLayoutUITests`, §3.3), which is committed with+this file.+**Host**: the same `Mac13,1` (Apple M1 Max, 10 cores), macOS 27.0. **Not quiet**+— another session was running its own simulator suites in a second worktree for+the whole window (load averages 47 / 100 / 109 at the end). No timing claim is+made here; these are pass/fail runs.+**Simulator and host only.** No device target, no `Personal` scheme, nothing+installed or launched, `CONFIRM_DEVICE_RUN` not set.++### 3.1 The devices, and why they are not the defaults++The other session held the Makefile's default `SIMULATOR` (`iPhone 18 Pro`) for+the whole window, and a second job on the same device installs the same bundle+id. So the iPhone targets were run on **`iPhone 18 Pro Max`** (iOS 27.0)+instead. No iPad was in use, so `make test-ui-ipad` kept its default+`IPAD_SIMULATOR`, **`iPad Pro 11-inch (M5)`** — deliberately, because the wide+suites assert geometry and a second override would have been a second variable.++That override has a cost, and it produced one of the four `make test-ui`+failures (§3.5). Read the iPhone UI run as "the default device plus one known+width artefact".++### 3.2 The runs++| Command | Device | Result | Exit |+|---|---|---|---|+| `make test-core` | host | **3,011 tests in 274 suites, 0 failures, zero known issues** | **0** |+| `make test-quick SIMULATOR='iPhone 18 Pro Max'` | iPhone 18 Pro Max, and `build-mac` | **1,681 tests, 0 failures**, `Test Succeeded` | **0** |+| `make test-ui SIMULATOR='iPhone 18 Pro Max'` | iPhone 18 Pro Max | **182 executed, 2 skipped, 4 failures**, 6,080.7 s | 2 |+| `make test-ui-ipad` | iPad Pro 11-inch (M5) | **30 executed, 1 failure**, 634.9 s | 2 |+| `make test-ui-ipad` (after the §3.3 fix) | iPad Pro 11-inch (M5) | **30 executed, 0 failures**, 641.8 s | **0** |++`make test-core`'s zero known issues is the state `CLAUDE.md` expects with no+schema window open.++**Req 2.2's check passed unchanged.** `TodayUITests` is **21/21**, including+every case that asserts `today-section-releases` and `today-section-catching-up`+straight after `recent-list` — `testTheCurrentDayLeadsWithItsReleases`,+`testAPastDayDrawsNoCatchUpSection`, `testAPastDayLeadsWithItsNotes`,+`testAnEmptyLibraryKeepsTheStripAndTheReleasesSection` and the banner-filter+case. Not one Today section arrives after the others.++**The design's Assumption held.** No suite needed the works load to be waited on+with the 60 s timeout `recent-list` uses: every case that selects Works found+`works-list` inside `waitFor`'s ordinary 30 s, on both trees, and+`WorksLoadGateUITests.testAFailedWorksLoadIsShownOnWorksAndStatsAndClearedByRetry`+is green. **No test was re-timed**, which is the design's fallback and was not+needed.++### 3.3 `WideLayoutUITests.testTheWorkNameInTheDetailColumnOpensTheWorkOnTheWorksPane` — root cause found, test fixed++The failure (`XCTAssertTrue failed - The name switches the window to the Works+pane`) is the one `specs/catch-up-mode/verification-run.md` recorded as+reproducing at `215c843` and left **unexplained**. It is explained now, and it+is not about the works-load gate.++A diagnostic run dumped the tree at the instant after the tap+(`make test-only … PIPE_PRETTY=`, iPad Pro 11-inch (M5)):++```+DIAG-WIDE loading=false failed=false listCV=false listAny=false+          workDetail=true noteEditor=false sidebarWorksSelected=false+```++and the tree showed `sidebar-today` **Selected**, the navigation bar titled+`Today`, `wide-list-column` holding the week strip, and `wide-detail-column`+holding the work. So: `works-loading` and `works-load-failed` are both absent —+the snapshot had loaded and this feature's gate is not in the picture — the tap+worked, and the work opened **on Today's pane**, which is where+`update-schedule` Q77 deliberately put it:++```swift+func openWork(_ workID: UUID, fromEntry entryID: UUID) {+    if selectedTab == .today { showWork(workID, on: .today) }+    …+}+```++pinned by `AppNavigationTests.openWorkFromTodayStaysOnToday`. The case was+written for `entry-to-work-link` Req 2's out-of-tab clause, which predates+Today's own stack; `215c843` is the merge that changed the behaviour and did not+carry this one wide-layout case with it. **The test asserted superseded+behaviour, and the app is right.**++Fixed, in the test only: renamed to+`testTheWorkNameInTheDetailColumnOpensTheWorkOnTodaysPane` and rewritten to+assert Q77's rule — the work fills `wide-detail-column` (unchanged, this is what+tells the route from Req 1.7's push across the pane), the entry it was opened+from is gone, `sidebar-today` is still selected, no `works-list` is behind it,+and the list column is still the day. Green on its own (22.9 s) and in the+re-run of the whole iPad target above.++### 3.4 The three `chooseWorksOption` failures — root cause found, handed on++| Case | Failure |+|---|---|+| `WorksListOptionsUITests.testTheReleaseDaysFilterNarrowsTheListByPresenceAndNamesItself` | `The menu offers Any` |+| `WorksListOptionsUITests.testTheStatusFiltersNarrowTheListAndNameTheirDimension` | `The menu offers Finished` |+| `WorksCreatorOptionsUITests.testTheCreatorFilterNarrowsTheListAndExplainsAnEmptyOne` | `The menu offers Any` |++The third was not on this task's list but fails identically and belongs with the+other two. All three reproduce on the default `iPhone 18 Pro` as well (two+earlier full runs of this branch, and a `WorksListOptionsUITests`-only run), so+the simulator override is not involved.++A diagnostic print inside `UIJourneySupport.chooseWorksOption`, at the point+where the 8-swipe loop gives up, says exactly what is wrong:++```+DIAG-MENU id=works-filter-work-status-finished idExists=false labelCount=2+          subscriptExists=true subscriptHittable=false+DIAG-MENU   [0] id= hittable=true frame=(171.3, 110.0, 250.0, 42.0)+DIAG-MENU   [1] id= hittable=true frame=(171.3, 341.0, 250.0, 42.0)+```++Read it in order:++- `idExists=false`, and both matching rows publish an **empty** identifier. The+  accessibility identifier on the `Text` inside the inline `Picker` does not+  reach the menu item at all — the behaviour `docs/agent-notes/testing.md`+  already records as "does not reliably reach", now reliably absent.+- So `worksOptionRow` falls back to the visible label, as it is designed to.+- `labelCount=2`: two rows are labelled `Finished` — the Work status one and the+  Reading status one, which `work-and-reading-status` Req 6.2 is entirely about+  telling apart. Nine rows are labelled `Any`, one per filter dimension.+- `app.buttons["Finished"]` is therefore ambiguous: `exists` is true but+  `isHittable` is **false**, because XCUITest will not hit-test a query with+  more than one match. The loop's `row.exists, row.isHittable` can never hold,+  it swipes eight times and fails — while the row sits on screen, hittable, at+  y 110 the whole time.++**Every failing row has a duplicated label and every passing row has a unique+one**, across all three suites: `alpha.test`, `webtoon`, `On hiatus`,+`Abandoned`, `Has release days`, `No release days`, `No creators` and the four+sort rows all pass; `Any` (×9) and `Finished` (×2) are the only ambiguous+labels, and they are the only failures. `specs/catch-up-mode/verification-run.md`+records these suites green on 2026-09-16, and the Xcode 27 upgrade+(`397e0247`, `5a750f38`) sits between that run and the first failure, which is+consistent with the identifier having reached the menu item before it.++**Not fixed here, deliberately.** There is no correct one-line fix: taking+`firstMatch` of the label would silently tap the *Work status* `Finished` when+the test asked for the *Reading status* one, and the Type dimension's `Any` when+it asked for Release days — a green test asserting the wrong dimension is worse+than a red one. The real fixes are each bigger than this task: either give the+menu rows identifiers XCUI can see (an app-side accessibility change, and it is+worth asking whether nine rows VoiceOver reads as "Any" should be qualified the+way the pills are), or thread the picker's section through `chooseWorksOption`+and its ~20 call sites so an ambiguous label can be scoped. Either is its own+bugfix spec. Nothing about them is caused by `launch-to-today`, and no test was+skipped or deleted to get green.++### 3.5 `AccessibilityJourneyUITests.testTheReleaseDayTogglesStayOperableAtLargestDynamicType` — the simulator override++`XCTAssertGreaterThan failed: ("1") is not greater than ("1") - Req 10.4: seven+44 pt targets cannot share one line at this size, so they wrap`. The case+collects the seven release-day toggles' `minY` at `accessibilityXXXL` and+requires more than one row. On the wider `iPhone 18 Pro Max` window they fit on+one line, so the assertion — which is about the **default device's** width —+does not hold. The same case passed twice on this branch on `iPhone 18 Pro`+earlier the same day. It is an artefact of §3.1's override, not a defect, and+nothing was changed for it. A confirming single-case run on `iPhone 18 Pro` is+owed whenever that device is free.++### 3.6 Forced-recompile warning check++Per the Swift rules file: every changed Swift file was `touch`ed, together with+two files carrying **known pre-existing warnings** as controls, and both halves+were rebuilt with the pretty-printer off and the raw log grepped for+`warning:`.++```+swift build --package-path Packages/AsterismCore --build-tests+make test-only TEST=AsterismUITests/WideLayoutUITests/… \+     SIMULATOR='iPad Pro 11-inch (M5)' PIPE_PRETTY=+```++Both controls appeared, so the logs are trustworthy:++- `AsterismTests/OptionalSequenceTeachingMessagesTests.swift:270` and `:271` —+  `main actor-isolated static property 'workID' can not be referenced from a+  nonisolated context`.+- `AsterismTests/AppLibraryModelTests.swift:1114` — `reference to captured var+  'after' in concurrently-executing code`, which `git log -L` traces to+  `215c8437`, before this branch.+- Package side: four `result of call to 'commitReShareUpdate…' is unused` in+  `AsterismCoreTests/RepositoryReShareTests.swift`, a file this branch does not+  touch.++**Those three are the whole set.** No warning is reported at any line of any+file this branch changed, in `AsterismCore`, the app target, the unit bundle or+the UI bundle. The `appintentsmetadataprocessor` "Metadata extraction skipped"+lines are tool noise, not compiler warnings.++## 4. After figures (task 14)++**Date**: 2026-09-20, 15:46–16:27 AEST. **Both sides were measured back to back+in one session on one machine**, which is what Req 1.4 asks for and what+sections 1 and 2 could not give it: section 1's before figures were taken+thirteen hours earlier at load averages of 140–220, section 2's after figures on+a much calmer host, and comparing across those two is the thing Req 1.4 exists+to prevent. Both runs below are **host only** — `swift test` of the+`AsterismCore` package. No device target was run, no `Personal` product was+built, installed or launched, and `CONFIRM_DEVICE_RUN` was not set.++**Host**: the same `Mac13,1` (Apple M1 Max, 10 cores), macOS 27.0 (26A428), as+sections 1–3.++### 4.1 Waiting for the host, and what it was doing++Another session held the machine with a `make test-ui` run on `iPhone 18 Pro`+for the first forty minutes. Nothing was measured while it was in flight; a+poller watched `ps` and `sysctl vm.loadavg` every two minutes from 15:04 until+it exited at **15:44**, at which point the load averages were **6.56 / 7.37 /+13.64** and no `xcodebuild` was running. That is the quietest this host has been+for any run recorded in this file.++| When | Load averages (1 / 5 / 15 min) |+|---|---|+| Host clear, before anything was started (15:44) | 6.56 / 7.37 / 13.64 |+| Start of the before run, release build beginning (15:46) | 116.22 / 51.48 / 30.34 |+| End of the before run (15:56) | 55.65 / 55.61 / 40.84 |+| Start of the after run, once the build's load had decayed (15:58) | 10.21 / 35.63 / 35.13 |+| End of the after run (16:27) | 239.59 / 113.36 / 90.59 |++Read the two three-digit readings for what they are, not as load the+measurements paid:++- **15:46 is the before run's own cold release build** starting, not other work.+  A `swift test -c release` fans out across all ten cores; the one-minute+  average is still climbing when the build begins. The build finished before any+  arm ran, and the load was allowed to decay to 10.21 before the after run was+  started.+- **16:27 is another session's `AsterismTests` run**, which started at about+  16:26 in the `today-announcement-rows` worktree — 1 min 18 s old when it was+  first observed at 16:27:23, against an after run that ended at 16:27:01.+  `launchReads` had finished by roughly **16:25:47** (77.1 s long, with 74.1 s+  of further tests after it), so **both arms this task is about were measured+  before that contention arrived**, and their spreads say so: 1.22× and 1.04×+  where the three arms that ran after them are at 4.73×, 3.11× and 13.01×.++Throughout both runs `mediaanalysisd`, `dasd` and Time Machine's `backupd` were+busy, as in every other run in this file. **A busy host is not a quiet host and+neither run sets a band**; what these two runs give is a like-for-like+comparison, because the before and after sides sat twelve minutes apart on the+same machine rather than thirteen hours.++### 4.2 The before run (task 1 commit)++**Commit**: `52ab0a2a` — "launchReads performance arm and the before figures",+the task 1 commit. It carries the arm and **none** of the Core change, which is+exactly the before state. The branch was not reset: the commit was checked out+into a throwaway detached worktree under the job's tmp directory+(`git worktree add --detach … 52ab0a2a`), measured there, and the worktree was+removed afterwards.++```+ASTERISM_RUN_PHYSICAL_PERFORMANCE=1 swift test --package-path Packages/AsterismCore \+  --no-parallel -c release -Xswiftc -DASTERISM_PERFORMANCE_TESTING \+  --filter 'M4ToleratedScalePerformanceTests/launchReads' \+  --filter 'M4ToleratedScalePerformanceTests/todayPublication'+```++This is `make test-performance-m4`'s own invocation with the filter narrowed to+the two arms the task needs. The whole 46-test target was not re-run on this+side: it is 21 minutes for 44 arms this task does not compare, and running it+would have pushed the after run into the other session's window.++`Test run with 2 tests in 1 suite passed after 118.467 seconds.` **`EXIT=0`,+zero known issues** — neither of these two arms carries one. 585 s wall+including the cold release build.++```+ASTERISM-PERF todayPublication median=0.968091s p95=1.629985s min=0.806262s max=4.682728s spread=5.81x n=20+ASTERISM-PERF launch-reads-full median=2.497368s p95=2.935145s min=2.433105s max=3.090939s spread=1.27x n=20+ASTERISM-PERF launch-reads-today median=0.763301s p95=0.777787s min=0.749837s max=0.800845s spread=1.07x n=20+```++**`todayPublication` ran first and paid for it.** Its spread is 5.81× with a+4.68 s max, against 1.27× and 1.07× for the two arms that ran after it: the+release build's load was still draining through it. Its 0.968 s median is not a+usable before figure, and this file does not use it as one — §1's **0.752713 s**+on this same commit is the before value for that arm, and §2 already recorded+what the Core change cost it. `launchReads` ran second, after the host had+settled, and both its arms are tight.++The two `launchReads` figures agree closely with §1's, measured thirteen hours+earlier at load 140–220: `launch-reads-full` 2.497 s against 2.573 s (−3%) and+`launch-reads-today` 0.763 s against 0.772 s (−1%). §1's tails were the host+(p95 4.15 s, spread 3.07×) and its medians held up, which is what it said at the+time.++### 4.3 The after run (final commit)++**Commit**: `68f13d85` (`feature/launch-to-today`), clean tree — the final+commit of the branch, with tasks 1–13 in.++```+make test-performance-m4 PERFORMANCE_LOG=/tmp/l2t-m4-perf-task14.log+```++`Test run with 46 tests in 7 suites passed after 1272.582 seconds with 9 known+issues.` **`EXIT=0`.** 1,691 s wall including the release build; 1,272.6 s of+test time, inside the 1,175–1,239 s this target has been measured at since+`update-schedule`.++```+ASTERISM-PERF todayPublication median=0.896484s p95=0.912889s min=0.847799s max=0.919794s spread=1.08x n=20+ASTERISM-PERF launch-reads-full median=2.434543s p95=2.554645s min=2.321882s max=2.839103s spread=1.22x n=20+ASTERISM-PERF launch-reads-today median=0.852188s p95=0.872044s min=0.836831s max=0.873504s spread=1.04x n=20+```++**Nine known issues, and they are the expected nine.** Req 5.4's three+capture-projection arms (0.145 s, 0.145 s, 0.182 s against 100 ms), Req 5.5's+three diagnosis re-derivations (0.353 s, 0.274 s, 0.280 s against 250 ms), the+full-tier no-op reconcile (0.026264 s against 10 ms), `dedupe-credits-noop`+(0.055024 s against 50 ms) and the `backup-export-thumbnails` peak. The two+`isIntermittent` ones met their budgets and so recorded nothing, as they did in+§2: `dedupe-links-noop` at 0.008676 s and `creator-converge-noop` at+0.006807 s. That is `CLAUDE.md`'s ten less those two. **No regression ceiling+was reached on any arm**, and nothing failed.++**The export peak recorded this time, narrowly.** `backup-export-thumbnails`+peaked at **408.1 MB** (51.1 MB archive, 15.47 s) — 2% over the 400 MB Q80+wraps as a plain, non-intermittent known issue, so the block recorded and the+target stayed green. §2's run on this branch peaked at 350.1 MB and failed with+`Known issue was not recorded`, which is the documented way that arm turns a+quieter host red. 408.1 MB is the closest a passing run has come to that edge;+it is worth watching, and it is not this spec's to move.++### 4.4 The four `launchReads` figures and the `todayPublication` band++Both sides measured on `Mac13,1`, twelve minutes apart, 2026-09-20.++| Arm | Before (`52ab0a2a`) median / p95 / spread | After (`68f13d85`) median / p95 / spread | Change in median |+|---|---|---|---|+| `launch-reads-full` | **2.497368 s** / 2.935145 s / 1.27× | **2.434543 s** / 2.554645 s / 1.22× | −0.063 s (−2.5%) |+| `launch-reads-today` | **0.763301 s** / 0.777787 s / 1.07× | **0.852188 s** / 0.872044 s / 1.04× | +0.089 s (+11.6%) |+| `todayPublication` | 0.968091 s / 1.629985 s / 5.81× — contended, see §4.2; §1's **0.752713 s** is the usable before value | **0.896484 s** / 0.912889 s / 1.08× | budget 2 s, **met**, 1.10 s of headroom |++| Run | Tests | Wall (test time) | Exit | Known issues |+|---|---|---|---|---|+| Before, `52ab0a2a`, filtered | 2 in 1 suite | 118.5 s (585 s with build) | **0** | **0** |+| After, `68f13d85`, full target | 46 in 7 suites | 1,272.6 s (1,691 s with build) | **0** | **9** |++**`todayPublication` stays inside its 2 s budget** at 0.896 s median and 0.913 s+p95, spread 1.08×, with the schedule and the title fold now built inside the+read (Decision 2). That is the same figure §2 measured at 0.903 s on a different+day, so Risk 1 is closed on two independent runs and the design's fallback was+never needed.++### 4.5 The launch saving (Req 1.4)++**`launch-reads-full` before, 2.497368 s, against `launch-reads-today` after,+0.852188 s: the launch saving is 1.645 s, or 65.9% of the repository reads the+reader waits on before Today can be drawn.** At the p95 it is 2.935145 s against+0.872044 s — 2.063 s, 70.3%. Both sides on one host, one session, twelve minutes+apart.++`launch-reads-full` **after**, 2.434543 s, is the read cost the background works+load now carries out of the reader's way; it did not move (−2.5%), so the change+relocated that work rather than adding or removing any.++**What this proves.** Over the M4 fixture, the repository reads that stand+between the store being open and Today being drawable fell from about 2.50 s to+about 0.85 s. That is a real, measured 2.9× on the largest component the+`launch-to-today` design set out to remove from the launch path, and the two+sides are directly comparable because they were taken on one machine minutes+apart.++**What it does not prove.** This is **repository read time, not+time-to-first-Today**. The arm does not cover the store open, the+pending-capture drain, the background-export wait or any app-side work+(`TodaySchedule` consumption, view construction, first draw). Those are the+`LaunchToToday` signpost's to report (Req 1.1 and 1.2), on a device, on a real+library — and on a real library, where far fewer than 466 of 1,000 works+qualify for Today, the arm's proportions will not be these. Nor is 1.645 s a+band: the host was busy in the way it is always busy, one run does not make a+baseline, and `percentile(of:)` returns the second-slowest of twenty samples+(`CLAUDE.md`, Performance measurement). Read it as the size of the saving, not+as a budget; Req 1.3 deliberately asserts nothing, and a budget is set later+from the signpost.++### 4.6 One tooling note from this run++`swift build --package-path Packages/AsterismCore --build-tests -c release`+**fails** at `ConstellationKitTests` with `unable to resolve Swift module+dependency to a compatible module: 'ConstellationKit'`. It is not a defect in+the tree: `swift build --build-tests` does not pass `-enable-testing`, and in+release that leaves `@testable import ConstellationKit` with nothing to import.+`swift test -c release` does pass it, which is why the Makefile's targets build+through `swift test` and why §3.6's forced-recompile check — which builds in+debug, where testability is on by default — is unaffected. Build the release+test bundle through `swift test`, never through `swift build --build-tests`.
specs/update-schedule/decision_log.md Modified +3 / -3
diff --git a/specs/update-schedule/decision_log.md b/specs/update-schedule/decision_log.mdindex bb54b17c..f1dc3715 100644--- a/specs/update-schedule/decision_log.md+++ b/specs/update-schedule/decision_log.md@@ -7,13 +7,13 @@ | Q1 | 2026-09-15 | Full spec, not a smolspec | Owner's call; a new Work column is a schema and archive bump, and replacing the start page is user-owned behaviour the code cannot settle | | Q2 | 2026-09-15 | Spec directory is `update-schedule` | Matches the v2 plan's wording ("update weekdays") and the `docs/update-schedule/` design canvas | | Q3 | 2026-09-15 | Day navigation is the week strip (the canvas's `Main` artboard), not title chevrons or a single scroll | Owner's pick; the strip shows the week's shape and lets a future weekday be reached in one tap, which the other two directions cannot |-| Q4 | 2026-09-15 | Today inherits everything Recent carries: banners, elsewhere sections and search; Recent is removed outright | Owner's pick; keeping a second history screen would split the same rows over two tabs |+| Q4 | 2026-09-15 | Today inherits everything Recent carries: banners, elsewhere sections and ~~search~~; Recent is removed outright — **the search clause is superseded by `launch-to-today` Decision 1** (2026-09-19: Today presents no search field on any platform; `RecentSearchFilter` and its tests stay in the codebase, unreachable until T-2347 gives note search a home on Works) | Owner's pick; keeping a second history screen would split the same rows over two tabs. The banners, the elsewhere sections and the removal of Recent stand | | Q5 | 2026-09-15 | A work is scheduled only while work status is `ongoing` and reading status is `reading`, in addition to having release days | Owner's pick; a work the reader has finished or abandoned still publishes, but the reader does not want it on their day | | Q6 | 2026-09-15 | The strip pages any week in either direction, with no bound | Owner's pick; past weeks are the capture history, future weeks are the schedule only, and neither costs anything to reach | | Q7 | 2026-09-15 | Outside the editor, release days show only on the work detail meta line | Owner's pick; the Works row already carries a type tag, two status glyphs, a series caption and a count pill, and the schedule is what Today is for | | Q8 | 2026-09-15 | A release row opens the work detail, with no open-last-noted shortcut on the row | Owner's pick; the reading action already lives on the detail page and a second tap target per row would crowd it | | Q9 | 2026-09-15 | Empty sections keep their header and show one dim line; no first-run hint on the Today screen | Owner's pick; a hint is chrome on a screen that is otherwise the reader's own notes. The editor's Status card carries a passive line instead when the work is not scheduled (Q19) |-| Q10 | 2026-09-15 | Search and the banner filters span all days, hiding the strip and the releases sections while active; release rows are never search results | Recent's search covers the whole history and searches entries only; a search scoped to one day would silently lose results |+| Q10 | 2026-09-15 | ~~Search and~~ the banner filters span all days, hiding the strip and the releases sections while active; ~~release rows are never search results~~ — **the search clauses are superseded by `launch-to-today` Decision 1** (2026-09-19: there is no search field on Today to span anything; the banner-filter half stands unchanged and is restated as that spec's Req 5.3) | Recent's search covers the whole history and searches entries only; a search scoped to one day would silently lose results. The all-days reach is also one of the constraints that held Today to reading the whole entry table, which is why removing the field was worth recording | | Q11 | 2026-09-15 | Weekday order follows the device calendar's first weekday; no in-app setting | The Stats period naming already takes the calendar as a parameter for the same reason | | Q12 | 2026-09-15 | Today's publication inherits Recent's 2 s host budget over the M4 fixture, which gains release days on a third of its works | The same screen's replacement over the same rows; a fixture with no release days would pass the arm without exercising the feature | | Q13 | 2026-09-15 | The bump opens markers `14` and `15` only; the owner confirms every device on `14` before the freeze commit | One frozen snapshot and a `[V(n-1), V(n)]` plan is the standing rule; keeping `13` openable would need a second snapshot and a two-stage chain, which `retire-migration-chain` removed. `work-creators` Q15, `place-extraction` Q48 and `work-thumbnails` verified first and substituted; V9→V10 retired one commit late and the note records it as the trap |@@ -31,7 +31,7 @@ | Q25 | 2026-09-15 | The week controls live in a week row above the strip, chevrons at both ends with the week's date range between; the row hides with the strip under search and the banner filters | Seven cells already fill a 320 pt column; the `Main` artboard drew no controls and the design decides their look, not their absence | | Q26 | 2026-09-15 | A strip cell's hit target may be 36 pt wide at non-accessibility sizes, an accepted deviation from the 44 pt minimum width; every accessibility size wraps 4 + 3 at full width | Seven 44 pt targets cannot share a 320 pt column; the height stays 44 pt and the accessibility sizes are where the guarantee matters most | | Q27 | 2026-09-15 | Release days are a `[String]` column of lowercase English day names, `releaseDaysRaw`, defaulted to `[]`, with a tolerant accessor; no bitmask, no join table | `CLAUDE.md`: a small value set is a `[String]` array, the shape `genreTags` already mirrors; a bitmask is unreadable in the CloudKit dashboard and the archive, and a table is the shape for facts two devices edit concurrently, which one work's own days are not |-| Q28 | 2026-09-15 | The Today screen's content is a pure derivation in `AsterismCore` over the two DTOs the app already publishes together, the entry presentation and the works snapshot; no new repository read | `refreshAll` publishes both in one block with a generation guard, and `WorkSnapshot.entries` already carries every entry's `lastSharedAt` and chapter fields; a Core builder over DTOs is what the host performance arm can time over the M4 fixture |+| Q28 | 2026-09-15 | ~~The Today screen's content is a pure derivation in `AsterismCore` over the two DTOs the app already publishes together, the entry presentation and the works snapshot~~; no new repository read — **superseded by `launch-to-today` Decision 2** (2026-09-19: `todayPresentation` builds `TodaySchedule` and the work-title map itself, from the work groups and entry rows it already fetches under its own lock, and the app reads both off the presentation; `TodaySchedule.build` has no app-layer caller left). The "no new repository read" half stands — the derivation moved *inside* the read Today already made, and the day-tap path still touches no store | `refreshAll` publishes both in one block with a generation guard, and `WorkSnapshot.entries` already carries every entry's `lastSharedAt` and chapter fields; a Core builder over DTOs is what the host performance arm can time over the M4 fixture. What the DTO pairing cost was a dependency on `works()`, the most expensive read at launch (1.6–2.1 s over the M4 fixture), which is what Decision 2 removed | | Q29 | 2026-09-15 | The Core Recent types and the repository read rename to Today (`TodayPresentation`, `TodayPresentationGroup`, `TodayPresentationRow`, `todayPresentation(calendar:)`), with the performance labels and the signpost | Owner's pick; the screen, the tab and the DTO carry one name | | Q30 | 2026-09-15 | The meta-line item is a `calendar` symbol with `Mon · Thu` in secondary text, no accent | Owner's pick; the schedule is neither a work state nor a reading state, so neither hue applies | | Q31 | 2026-09-15 | No count on a releases header | Owner's pick; `ConstellationSectionHeader` is one static text for the UI suites' sake, and a count folded into the string bought little |
specs/update-schedule/requirements.md Modified +1 / -1
diff --git a/specs/update-schedule/requirements.md b/specs/update-schedule/requirements.mdindex 360b11a8..12a418e5 100644--- a/specs/update-schedule/requirements.md+++ b/specs/update-schedule/requirements.md@@ -78,7 +78,7 @@ A work carries no record of which days of the week its author publishes, and the  1. <a name="3.1"></a>The first tab SHALL be titled `Today` with a calendar glyph, in the position the Recent tab holds today, in both the compact tab bar and the wide-layout sidebar (`specs/ipad-and-mac-layouts/`); no tab or sidebar row titled `Recent` SHALL remain.   2. <a name="3.2"></a>Today SHALL carry every banner Recent carries — actionable, duplicate, sync, diagnosis and refresh failure — with the same gates, wording, placement above the list and tap behaviour, and SHALL carry Recent's duplicate "elsewhere" sections with the same content and gates.  -3. <a name="3.3"></a>Today SHALL offer Recent's note search through the same placement on each platform; WHILE Recent's rule would treat the query as active, the screen SHALL show the same results Recent shows for that query across all days, grouped and headed as Recent groups them, with the week row, the week strip and every releases section hidden; release rows SHALL never be search results.  +3. <a name="3.3"></a>~~Today SHALL offer Recent's note search through the same placement on each platform; WHILE Recent's rule would treat the query as active, the screen SHALL show the same results Recent shows for that query across all days, grouped and headed as Recent groups them, with the week row, the week strip and every releases section hidden; release rows SHALL never be search results.~~ **Superseded** (2026-09-19) by [`specs/launch-to-today/`](../launch-to-today/requirements.md) Decision 1 and its Req 5.1: Today presents no search field on iPhone, iPad or Mac, so there is no query for this criterion to govern. The matching behaviour itself survives with its unit tests, unreachable from the interface until T-2347 gives note search a home on the Works tab (that spec's Req 5.4). The hiding rule this criterion shares with [3.4](#3.4) is unaffected and is restated as that spec's Req 5.3, and the search clauses of [3.5](#3.5), [5.8](#5.8) and [10.1](#10.1) fall with this one; everything those three say about the banner filters stands.   4. <a name="3.4"></a>WHILE the actionable-only or duplicate-only filter a banner toggles is active, the screen SHALL show the filtered rows across all days exactly as Recent does, with the week row, the week strip and every releases section hidden.   5. <a name="3.5"></a>WHEN the last of an active search and an active banner filter is cleared, the screen SHALL show the selected day again, with [3.7](#3.7) having applied while it was hidden.   6. <a name="3.6"></a>Opening an entry row, a work row, an elsewhere row or a banner from Today SHALL reach the same destination it reaches from Recent, and returning SHALL show the selected day again.  
specs/launch-to-today/implementation.md Added +258 / -0
diff --git a/specs/launch-to-today/implementation.md b/specs/launch-to-today/implementation.mdnew file mode 100644index 00000000..1951dd5a--- /dev/null+++ b/specs/launch-to-today/implementation.md@@ -0,0 +1,253 @@+# Implementation: Launch to Today++Written at the end of the build (2026-09-20, 19 commits on+`feature/launch-to-today` from `d01660c3`) as the `explain-like` validation+pass. Three readings of the same change, then an honest account of what is+finished and what is not.++## Beginner Level++### What Changed++Opening Asterism used to mean waiting for the whole library to be read before+anything appeared. The largest part of that wait was building the **works+snapshot** — a list of every work in the library, with its entries attached.+Today, the screen you land on, did not actually need that list. It only needed+it for one thing: working out which stories are due for a new chapter today.++So the app now does the calculation in a different place. The "what's due+today" list is worked out while the app is already reading Today's own data,+from information it has in its hands anyway. That means Today can be drawn+immediately, and the big list can be fetched afterwards, in the background,+while you are already reading.++Two other things follow from that. The Works and Stats screens *do* need the+big list, so they now show a small spinner until it arrives, and an error with+a **Retry** button if the fetch fails. And Today lost its search field — it had+become a dashboard rather than a place to search, and note search is moving to+Works instead.++### Why It Matters++The reads you wait on before Today is drawable dropped from about **2.5 seconds+to about 0.85 seconds** on the 5,000-entry test library — roughly two-thirds+less. The work did not get cheaper; it moved out of the way, to where nobody is+waiting for it.++There is also a new line in the system log at every launch saying how long the+launch took and where the time went, so the next person to ask "why is opening+slow?" has numbers instead of a guess.++### Key Concepts++- **Snapshot** — a frozen, read-only copy of data handed to the screens.+  Screens never touch the database directly; they get snapshots. Think of it as+  a photocopy rather than the original file.+- **Publication** — one moment when the app hands a fresh set of snapshots to+  the screens. Everything in one publication describes the same instant, so you+  never see half-old, half-new data.+- **The schedule** — the "Releasing" and "Catching up" lists, plus the dots on+  the week strip. This is the thing that moved.+- **Reconcile** — a background repair pass that tidies up duplicates after data+  syncs between devices. It now runs *after* the big list has loaded rather than+  before, because they compete for the same database lock and only one of them+  has a person waiting on it.++---++## Intermediate Level++### Changes Overview++The change splits what was one launch publication into two, and moves one+derivation across a module boundary.++**AsterismCore** (`Packages/AsterismCore/Sources/AsterismCore/`)++- `TodayDayPlan.swift` — the bucket test that decides whether a work is+  `scheduled`, `catchingUp` or neither is extracted into+  `TodaySchedule.admits(readingStatus:workStatus:releaseDays:)`. `build` now+  calls it, so there is one spelling of the predicate instead of an inline copy.+- `LibraryRepository.swift` — `snapshot(_ work:types:series:credits:)` is split+  into a fields-only core that takes the entry snapshots as a parameter. The+  existing signature passes `work.entryValues` into it, so nothing changed for+  its callers.+- `LibraryRepository+Groups.swift` — a new overload builds a work-group+  snapshot from entry *rows* the caller already holds, rather than reading them+  through the relationship. The pre-existing group snapshot now delegates to it.+- `LibraryRepository+TodayPresentation.swift` — computes the work groups once+  and shares them with the title fold; prefilters groups through `admits` so+  only works the schedule lists are snapshotted; buckets the entry rows once by+  work id; and returns `schedule` and `workTitles` on `TodayPresentation`.++**App** (`Asterism/Asterism/`)++- `AppLibraryModel.swift` — a new `publishToday()` publishes the Today half+  alone. `bootstrap()` calls it and reaches `.ready` from it, falling back to+  the full `refreshAll()` only when it publishes nothing. A `worksLoad` state+  (`loading` / `loaded` / `failed`) says whether the works snapshot exists.+  `scheduleLaunchTail()` runs the first works load, retries once, then runs the+  launch reconcile. `repositoryEpoch` invalidates cycles belonging to a released+  library. The overlap, calendar and epoch guards are consolidated into one+  `enterCycle()` / `canPublish(_:)` pair used by both publishers.+- `WorksLoadGate.swift` (new) — wraps Works and Stats, showing progress or an+  error with Retry, and passing content through untouched once loaded.+- `LaunchMeasurement.swift` (new) — a `LaunchPhaseRecord` value type that both+  the signposts and the log line are built from, so what they report is testable+  without OSLog.+- `TodayView.swift` — the search field, its state and its ⌘F focus token are+  removed; the filter stays in the plan, defaulted inactive.++### Implementation Approach++**One publication, two publishers.** The invariant the file already had — no+`await` between the publish gate and the last assignment, so a reader observes+one cycle's values — is preserved in both publishers. `enterCycle()` captures+calendar, calendar key, generation and epoch synchronously before the first+read; `canPublish(_:)` re-checks all three before publishing.++**Answer "not loaded yet" once.** The audit found five readers of the works+snapshot that would otherwise have to distinguish "empty library" from "not+read yet". Rather than teaching all five, the question is answered at the screen+boundary: `WorksView` and `StatsView` are constructed *only* in the `.loaded`+arm, so they cannot present an absent snapshot as a fact about the library.++**Equivalence by construction, checked by test.** The schedule built inside the+presentation must equal the one built from the works snapshot.+`TodayScheduleEquivalenceTests` asserts that over seven fixtures — the M4+composed library, a same-UUID split group whose rows disagree on reading+status, a dismissed cross-site pair, a split entry group pointing at two works,+a finished catching-up work with release days, a scheduled work with no+entries, and an empty library.++### Trade-offs++- **Moving the derivation vs. caching it.** Caching the schedule across+  publications was rejected: it would need invalidation on every write, and the+  pairing with the rows is exactly what makes Today coherent.+- **One gate view vs. teaching five readers.** The gate is one place to get+  right and one place to change; the alternative spreads a tri-state through+  five call sites.+- **An ordinary `refreshAll()` as the first works load.** Reusing the existing+  publisher means one code path rather than two, at the cost of the tail+  repeating the Today read the reader has just waited for. That repeat is off+  the critical path but it is real — see Potential Issues.+- **Reported, not budgeted.** The new `launchReads` performance arm asserts+  nothing. No time-to-first-Today number exists yet, so a bound drawn now would+  be a guess; the arm exists to record a band a later budget can be set from.++---++## Expert Level++### Technical Deep Dive++**Why the schedule can move without changing its answer.** `TodaySchedule.build`+consumes `WorkSnapshot`s and reads only `readingStatus`, `workStatus`,+`releaseDays` and each work's entry days. A snapshot's statuses and release days+are its *carrier's* — the row whose authored content the group presents — so+asking `admits` of the carrier before snapshotting is an exact prefilter, not an+approximation. Only admitted groups are then snapshotted, with `series: .empty`+and `credits: .empty`, because `ScheduledWork` reads neither.++**Why nothing on the new path faults `work.entries`.** The fields-only snapshot+core touches only stored columns on the row. The group overload passes+`entries: []` for the representative and carrier and supplies the group's own+entries from rows the caller holds, bucketed once by `row.work?.id` — a to-one+the surrounding entry-snapshot loop has already faulted for the common case.+This matters because a to-many fault per work over a 1,000-work fixture is the+cost the whole feature exists to avoid+(`docs/agent-notes/swiftdata-relationships.md`).++**A side effect worth naming.** Because the pre-existing group snapshot now+delegates to the new overload, `works()` stopped building per-row entry+snapshots for the representative and carrier that it then discarded — including+a `citationsData` JSON decode per entry. For an unsplit group, every attached+entry in the library was being snapshotted twice and one copy thrown away. This+was not in the design; it fell out of the refactor and is recorded in+`verification-run.md` §2.3.++**The three publish guards, and what they do and do not promise.** The+generation guard means a cycle that entered at *n* can never overwrite one that+published at *n+1*. It does **not** order two cycles that entered at the same+generation: the repository is an actor, their reads serialise in an order the+model cannot see, and the first to reach the publish wins even holding the+staler read. The residue is a write-then-refresh path whose refresh loses and+leaves a just-committed change unshown until the next one — self-correcting. A+re-read loop would close it and is deliberately not taken, because a CloudKit+hydration republishes dozens of times and retrying until the counter holds still+is exactly the shape that does not terminate under the load it would matter+most in.++**Why the reconcile moved behind the works load.** `CrossProcessLibraryLock`+polls a non-blocking lock with no writer fairness. A reconcile that won it first+could time the works read out from under the Works tab, and the reader is+waiting on the read, not the reconcile. Two tail attempts are the bound (Q21);+if both are abandoned at a gate the reconcile runs anyway, which is a knowingly+accepted gap against Req 3.10's "published or failed" wording.++### Architecture Impact++`TodayPresentation` grows two fields and becomes the single source of Today's+schedule; `TodaySchedule.build` has no app-layer caller left. The app model+gains a lifecycle counter (`repositoryEpoch`) alongside the existing+`pendingCaptureGeneration`, both bumped in the same teardown for the same+purpose — a third such counter should be resisted.++`snapshotGeneration` changed meaning: it now bumps twice per launch, and a+non-zero generation no longer implies the works snapshot was read. Anything+keyed on it should be re-read in that light —+`ArrivingLibraryPresentation.hasContent(snapshotGeneration:)` is documented as+"a refresh cycle has completed", which is no longer what the counter means.++### Potential Issues++Four concurrency gaps were identified in review, all narrow, none blocking, none+fixed in this branch because each changes behaviour specified by an approved+design listing:++1. **Teardown window.** `repositoryEpoch` is bumped before the first suspension,+   but `repository` is not cleared until after `await shutdown()`. A cycle+   entering *during* teardown captures the new epoch, reads a dying store, and+   may publish or mark `.failed` — the latter being the case Req 3.8 says must+   not be a failure. Self-corrects on the next publication.+2. **The tail's first read is unguarded.** `scheduleLaunchTail()` awaits+   `refreshAll()` before any cancellation or epoch check, so a cancelled tail+   still issues one full library read, possibly against the replacing library.+3. **The `.fellBack` launch reads twice.** When `publishToday()` publishes+   nothing, `bootstrap()` runs `refreshAll()` and the tail then runs it again+   unconditionally — a second full works read moments later. Only the tail's+   *second* attempt is conditional.+4. **Retry has no retry.** `retryWorksLoad()` makes one attempt; if that cycle+   is abandoned at the calendar or generation gate it publishes nothing and+   leaves `worksLoad == .loading` — a spinner with the Retry button no longer+   on screen — until an unrelated refresh publishes.++Also carried forward: `works()` still faults `work.entries` per work, which the+new overload makes trivially fixable but which this branch did not touch.++## Completeness Assessment++**Fully implemented.** All 25 numbered requirements (1.1–1.4, 2.1–2.5, 3.1–3.10,+4.1–4.2, 5.1–5.4) have code behind them, and all four design decisions match+what the code does. The independent spec review found no unrecorded+architectural divergence.++**Implemented but thinly tested.**++- Req 3.2's `.loading` arm has no assertion of any kind. The UI test's own+  header explains why (over a seeded fixture the state is gone before the tab is+  reachable), and the `.failed` UI test exercises the same chrome path, so only+  the label and its identifier are unasserted.+- Req 2.4 is tested structurally (map equality at both publications) rather than+  behaviourally; no test navigates from a Today row to a work while the load is+  still running.+- Req 3.5's Mac restored-selection path has a proxy assertion, with the real+  check left to the owner's `prerequisites.md` run.+- `LaunchMeasurement.name(of:)` spells the four phase names a second time as+  `StaticString`, and nothing pins the two spellings against each other; a typo+  would mislabel an Instruments track silently.++**Not done here, by design.** The two device launch readings and the Mac Today+check are the owner's, under the device-run rule. No launch *budget* is set —+Q4 defers that until a reading exists from a phone.

Things to double-check

The three documents that quote the performance figures.

CLAUDE.md, the changelog and specs/OVERVIEW.md all now quote 2.497 s, 0.852 s and 1.645 s / 65.9%. Those came from one before/after pair on a busy host. If anyone re-measures on a quiet machine, all three want updating together, and the verification run is the file that owns the numbers.

Whether the Works gate's spinner feels long on a real device.

The works load now runs behind the gate and behind a repeated Today read (about 0.85 s of it). On the M4 fixture that is fine; on a phone with a real library it is the thing to watch during the owner's device readings. If it feels long, finding C3 is where the time is.

The retry dead end.

Worth exercising by hand: launch with ASTERISM_UI_TEST_WORKS_LOAD=fail-until-retry, tap Retry, and change the day or trigger an arrival at the same moment. If the spinner stays and the Retry button is gone, that is C4 reproducing.

make test-core is red on this machine for an unrelated reason.

The screen is locked, so the three pending-capture spool suites fail with file-protection errors (NSCocoaErrorDomain 257 under PendingCaptures/quarantine/). The last clean Core run was at commit 68f13d85 with 3,011 tests and zero known issues, and only documentation has changed since. A confirming run once unlocked is owed.