asterism branch T-2367/app-intents commits 21 files 59 touched lines +6119 / -138

Pre-push review: T-2367/app-intents

App Intents for Siri and Shortcuts: two Today questions, add a page as to read, open Today or a work, and works as Shortcuts values. Spec specs/app-intents/.

At a glance

  • Five App Intents plus a WorkEntity run in the app process. They reach the library through IntentLibraryBroker, which uses the resident repository or a one-step cold openForExtension session.
  • Answers are pure Core functions over the Today read, so Siri and the Today screen cannot disagree.
  • The add intent checks for duplicates by the capture key and again under the write's lock, and creates a to-read work the way the New Work form does.
  • The open intents route through a revision-stamped IntentRoute and never navigate over an open editor.
  • Development is now displayed as Devsterism, and verify-identity enforces that the two display names differ.
  • Owed by the owner: the Mac cold-path timing and the phone runbook, both Development only.

Verdict

Ready to push

The four review agents raised 21 findings. The 14 that needed fixing are fixed in e14963f9, 95418976, 9148ddff and e60c0564, including three majors: two broker and export races, and stale spec text. The 7 skipped items are low-impact efficiency, test-fixture and naming points. make test-core (3,118 passing) and make test-quick (1,872 passing, macOS build included) pass at e60c0564, and so does make verify-identity. Caveat: origin/main has moved past the branch base (bbdcd8b6 → d0596e79), so rebase before pushing. The implementation-explanation commit dd2a86b3 moved HEAD after the test run, and it touches only implementation.md.

Review findings

21 raised · 14 fixed · 7 skipped

Jump to findings →

Tests

Pass rate: n/a

New tests: 89

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

What changed

Before this branch the reading library could only be reached by opening the app. Siri and the Shortcuts app can now use it directly, through five actions:

  • Chapters releasing today: lists the works with a chapter due today, in Today's order.
  • Notes from today: reads out today's notes. Above five it gives the count and the first five.
  • Add as to read: saves a web page as a new to-read work after confirming its title. If the page is already in the library, it says so and adds nothing.
  • Open Today and Open work: bring the app forward on Today or on a named work.

Works also become a Shortcuts value, with a "Find Works" action that searches by title.

Why it matters

The reader can ask what to read, or save a serial for later, without opening the app. Siri's answers come from the same code as the Today screen, so the two cannot disagree.

Key concepts

  • App Intent: Apple's way for an app to offer actions to Siri and Shortcuts. The system can start the app in the background to run one, with no window.
  • Cold vs. resident: when the app is already running with its library open, an action uses that library. When the app was started only for the action, the action opens the library briefly, as the share extension does, and then closes it.
  • Broker: a doorkeeper that lets one library action through at a time.
  • Edit guard: when the reader is editing something, an open action brings the app forward but does not navigate away, so the draft survives.

Changes overview

  • Core:
    • LibraryRepository+Intents.swift adds workSummaries, pageMatch and createWorkUnlessPresent.
    • IntentAnswers.swift holds pure answer functions over TodayPresentation.
    • createWork is split into validatedNewWork and insertWork.
    • captureLookup is split into captureCandidates and captureMatches.
  • App target:
    • Five intents, WorkEntity and its query, and AsterismShortcuts.
    • IntentLibraryBroker.
    • The plain flows AddPageToReadFlow and OpenTargetFlow, which the intents wrap.
  • Plumbing:
    • AsterismApp.init registers the model and navigation with AppDependencyManager.
    • bootstrap() drains the broker before teardown.
    • The export pass holds the broker's turn around its open and its shutdown.
    • AppNavigation gains intentRoute, revision, isEditing and .intentEditSession.
  • Identity: Development is displayed as Devsterism, and verify-identity checks that the two display names differ.

Implementation approach

  • The broker is a FIFO of continuations on the main actor, because the main actor is reentrant at every await.
  • A step runs on the resident repository when the library is ready, throws when it is unavailable, and otherwise runs on a cold openForExtension session.
  • Bootstrap drains the broker and never cancels a step.
  • The caller declares writes through writes: or wroteIf:. A resident write refreshes after the answer; a cold write leaves an ExportOwed/ marker.
  • createWorkUnlessPresent runs the duplicate check and the insert under one exclusive lock and one save.
  • Open intents stamp the route with revision. The window drops it if the reader moved, if an edit is open, or if the work is unknown.

Trade-offs

  • In-app rather than an extension (Decision 1): no new target and no second mirroring process, at the cost of a store open inside Siri's timeout.
  • One step per cold session (Decision 4): no session lifetime rules, at the cost of a validateStore per step, two for an add. The Mac timing (Q60) decides whether the keep-alive fallback is needed.
  • Mirroring off on cold sessions (Q38): a cold-created work syncs on the next grant or foreground.
  • The edit guard fails safe (Q37): any sheet blocks navigation.

Technical deep dive

  • Admission. withLibrary waits on libraryReady() while bootstrapInFlight, then takes the turn. It re-checks after admission and gives the turn back if a bootstrap started meanwhile. Otherwise the step would either run cold beside bootstrap's container or deadlock drain().
  • Export (Q51, Q65).
    • acquire() skips a pass while the broker is busy, then takes holdingTurn with no suspension in between.
    • A step that queues during the pass's open borrows backgroundSession.
    • release() shuts the session down inside the turn and re-reads it there.
    • Together these rule out two containers in one process and a borrowed session that is shutting down.
  • Refresh after a write (Q68): runs in pendingWriteRefresh, outside the turn.
  • pageMatch:
    • The entry arm uses capture's candidate set.
    • The work arm compares EntryIdentityNormalizer.key(forRawURL:) on both sides. A fragment or a trailing slash still makes a different page (Q35).
    • A work beats an entry; titleOrder picks among works, and the least UUID among unattached entries.
  • workSummaries summarises single-row buckets from the row, so memberships are not faulted (Q69).
  • Edit sessions end on active == false or through an isolated deinit, not on onDisappear (Q54).

Architecture impact

  • openForExtension now has two callers.
  • Any future scene-less library user must go through holdingTurn.
  • Any new navigation property must bump revision.
  • Any new local sheet or edit mode must opt into .intentEditSession.

Potential issues

  • Cold-step latency is unmeasured on a real library (Q60).
  • isProtectedDataAvailable lags a lock by about 10 s (Q36).
  • Reopening a closed Mac window is untested.
  • A collapsed work reads as not found (Q14).
  • verify-identity compares only the configurations named Development and Personal.

Important changes — detailed

IntentLibraryBroker: FIFO admission, three arms, drain instead of cancel

Asterism/Asterism/Intents/IntentLibraryBroker.swift

Why it matters. Correctness: this is what keeps the library from being open twice for mirroring (Req 6.4). Every intent and entity query goes through it.

What to look at. IntentLibraryBroker.withLibrary(wroteIf:_:), run, runCold, holdingTurn, drain

Takeaway. The main actor is not a mutex across awaits. A FIFO of CheckedContinuations with a turn flag, plus a drain waiter list, gives ordered exclusion without Tasks chained on Tasks.
Rationale. Decision 4 and Q50: one step per cold session removes any need for session lifetime rules. Waiting for a short step is cheaper than making cancellation safe.

AppLibraryModel: bootstrap drains, export holds the turn

Asterism/Asterism/ViewModels/AppLibraryModel.swift

Why it matters. Correctness: this closes the two-container race between a cold step and the background-export pass, and between a step and bootstrap's teardown.

What to look at. bootstrap() drain call; acquire() isBusy skip; acquireColdSession/openColdSession inside holdingTurn; release() inside holdingTurn

Takeaway. When two subsystems share an exclusive resource, give them one admission gate, not two cooperating flags.
Rationale. Q51 and Q65: a drain loop still leaves the shutdown's own await open, so the pass holds the turn around both its open and its shutdown.

createWorkUnlessPresent and pageMatch: check and write under one lock

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

Why it matters. User-visible behaviour: Siri must not create a duplicate work (Req 3.5), including when a match is committed between the prompt and the write.

What to look at. pageMatch(rawURL:), createWorkUnlessPresent(_:), workSummaries single-row fast path

Takeaway. Split a public write into validate, then an insert body that takes a context. A check-then-write variant can then share the body under one lock, with no copy of the refusals.
Rationale. Q19, Q31, Q35 and Q69: the work arm uses the identity-key normaliser because work URLs are stored as typed, and the entry arm reuses capture's candidates so the two cannot disagree.

LibraryRepository.createWork split into validatedNewWork + insertWork

Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift

Why it matters. API surface: this refactors a shipped write path. The New Work form's behaviour must stay identical.

What to look at. createWork, validatedNewWork, insertWork

Takeaway. A behaviour-preserving extraction keeps the existing comments and order of operations exactly. Here the diff is indentation plus two signatures.
Rationale. Design, Core section: the add intent must refuse exactly what the form refuses (Req 3.6).

AppNavigation: intentRoute, revision and the edit guard

Asterism/Asterism/Layout/AppNavigation.swift

Why it matters. User-visible behaviour: an open intent must not discard an unsaved draft (Req 4.5) or override a move the reader made after the intent ran.

What to look at. didSet revision bumps, withoutRevision, isEditing, takeIntentRoute(workTitlesByID:)

Takeaway. A monotonically increasing revision stamped on a deferred command is a cheap way to say 'only if nothing happened since'.
Rationale. Q42, Q53 and Q54: a tab comparison misses a push on the same tab, and restore or prune must not count as the reader moving.

IntentEditSession modifier

Asterism/Asterism/Layout/IntentEditSession.swift

Why it matters. Correctness: this is how local sheets and edit modes register with the guard. It is not covered by an automated test.

What to look at. IntentEditSessionModifier, IntentEditRegistration isolated deinit

Takeaway. Tie a registration's lifetime to @State storage with an isolated deinit, not to onDisappear, when a view can disappear while its state is still meaningful, as a tab switched away does.
Rationale. Q30 and Q54: no central editing flag exists, and ending on onDisappear would let an intent replace the stack under a hidden editor.

verify-identity: display names must differ

scripts/verify-identity.sh

Why it matters. Build safety: two apps with the same display name give Siri two answers to one phrase (Req 7.3).

What to look at. display-name check block

Takeaway. Check the property that matters (the names differ) rather than a specific value, so a rename stays a one-place edit.
Rationale. Q25, Q61 and Q62.

Key decisions

Intents run in the app process, not an App Intents extension.

Decision 1. There is no new target or entitlement, and the one-mirroring-process rule holds by construction. A cold intent pays the store open inside Siri's timeout.

Cold steps use openForExtension, one step per session, mirroring off.

Decision 4, superseding Decision 2 and Q24. Every open is paired with its close in one call. A cold write leaves an ExportOwed/ marker (Q38).

Bootstrap drains the broker; it never cancels a step.

Decision 4, Q50. A step is short and bounded by the 2 s lease. A queued step that comes up during a bootstrap gives its turn back.

The export pass holds the broker turn around its open and its shutdown.

Q51, Q65. This rules out a second container beside the pass's, and a step borrowing a session that is closing.

Writes are declared by the caller, with no default.

Q48, amended by Q67. wroteIf: lets .present skip the refresh and the marker. A default of false failed open.

A resident write's refresh runs after the answer.

Q68. The refresh took about 3 s at library scale and held Siri's answer and the turn.

The title prompt is a choice, then a question.

Decision 3. App Intents has no prefilled text prompt.

Answers are composed from todayPresentation + TodayDayPlan.

Q28, Q17. Equality with the screen is guaranteed, and Today is minted when the intent runs, not when the screen last published.

The edit guard counts any presented sheet, plus in-stack edit modes.

Q37, Q54, Q64. It fails safe, and sessions end on active == false or state release, not on onDisappear.

Open Work routes at once while the library is opening.

Q66. Req 4.6 asks the app to come forward on the state it shows. The window drops an unknown id.

The duplicate check's work arm uses EntryIdentityNormalizer keys.

Q35. Scheme case, host case, trackers and an added https:// are equal; a fragment or a trailing slash is not, as in capture.

The two M4 arms are bounded by their 2 s budget only.

Q43. A ceiling under the budget would redefine Req 6.6.

Review findings

SeverityAreaFindingResolution
majorIntentLibraryBroker / background exportA cold intent step could open a second container while the background-export pass was opening its own.The pass holds the broker turn around its open (Q65).
majorAppLibraryModel.release()release() could shut down an export session that a step had just borrowed after the drain.The shutdown runs under the broker turn and re-reads the session inside it (Q65).
majorSpec: decision log and runbookDecision 1 still said bootstrap cancels intent sessions, and the runbook told the owner to install Personal.Decision 1's status now names Decision 4. The runbook is Development-only and leaves the installed Personal app alone.
mediumworkSummaries (efficiency)Every Siri work query faulted each work's siteMemberships while building groups.Single-row buckets are summarised from the row (Q69).
mediumResident add (efficiency)A resident add held Siri's answer and the broker turn for a full refresh of about 3 s.The refresh runs after the answer, and not at all on .present (Q67, Q68).
mediumIntentLibraryErrorThe error had no readable message, so entity queries showed a generic error.It conforms to CustomLocalizedStringResourceConvertible (Q70).
mediumOpenWorkIntent (Req 4.6)Open Work waited for bootstrap instead of foregrounding while the library was opening.It routes at once and skips the existence check (Q66).
minorOpen intentsA route survived a failed continueInForeground.The route is cleared on failure.
minorwithLibrary(writes:)writes defaulted to false, which fails open for a future write step.The argument is required, and a wroteIf: overload was added.
minorWorkDetailView edit guardThe cover viewer was missing from the presentsSheet expression.Added.
minorAddPageToReadIntent logging (Req 6.7)Nothing was logged on cancel, and no line said whether the URL was supplied or asked for.Each line carries url supplied or url asked, and a cancel logs cancelled (Q70).
minorReuse and cleanupSeveral duplications: the spoken reading/catching-up status set, a redundant reorder dictionary in the chapters intent, an unchunked Work-by-id fetch in pageMatch, three shapes of refusal handling, duplicated branches in runCold, and an error message swallowed by intentConfiguration.All unified or fixed.
minorDocsStale design text (the publishToday refresh, the audit table, the ceiling, @Dependency), a stale schema-migration note, a duplicate phrase in the OVERVIEW, no phase 4 record in implementation.md, and ambiguous Q37 citations.All corrected.
nitAppLibraryModel log lineA space was dropped from the "Snapshot refresh failed:" log line.Restored.
minorFind Works (efficiency)Find Works with k comparators reads the Work table k times.Low impact; left as is.
minorsuggestedEntities / resident Today intentsThey re-read data the model already publishes.Freshness was kept deliberately.
nitShortcutParametersIt re-registers once per launch.Negligible.
minorOpenWorkIntentOpen Work resolves the work up to three times.Left as is.
minorTest fixturesTest helpers are copied between suites (waitUntil, rule and capture helpers).The review policy does not refactor tests. The ContainerGate was shared by the fix anyway.
minorWorkEntityStatuses are display strings rather than an AppEnum.Left as is.
minorverify-identityOnly the configurations named Development and Personal are compared.Left as is; recorded in implementation.md.

Tests

Source: local run at 2026-09-24T15:06:00+10:00 · snapshot e60c0564a5e3565f4e584e1ef7552a49e47ae6e2

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 bbdcd8b68a71e196a95f4bc3b71e18ac6612a041.

Dependents none found Changed Dependencies none found Asterism/Asterism Asterism/Asterism.xcodeproj Asterism/Asterism/Intents Asterism/Asterism/Layout Asterism/Asterism/Support Asterism/Asterism/ViewModels Asterism/Asterism/Views Asterism/AsterismTests Asterism/AsterismTests/Helpers …rismCore/Sources/AsterismCore …mCore/Tests/AsterismCoreTests scripts Asterism/Asterism/AsterismApp.swift…sm/Asterism/AsterismApp.swift Asterism/Asterism/ContentView.swift…sm/Asterism/ContentView.swift Asterism/Asterism.xcodeproj/project.pbxproj…ism.xcodeproj/project.pbxproj Asterism/Asterism/Intents/AddPageToReadFlow.swift…tents/AddPageToReadFlow.swift Asterism/Asterism/Intents/AddPageToReadIntent.swift…nts/AddPageToReadIntent.swift Asterism/Asterism/Intents/AsterismShortcuts.swift…tents/AsterismShortcuts.swift Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swift…ersReleasingTodayIntent.swift Asterism/Asterism/Intents/IntentLibraryBroker.swift…nts/IntentLibraryBroker.swift Asterism/Asterism/Intents/IntentLog.swift…erism/Intents/IntentLog.swift Asterism/Asterism/Intents/IntentOutcome.swift…m/Intents/IntentOutcome.swift Asterism/Asterism/Intents/NotesFromTodayIntent.swift…ts/NotesFromTodayIntent.swift Asterism/Asterism/Intents/OpenTargetFlow.swift…/Intents/OpenTargetFlow.swift Asterism/Asterism/Intents/OpenTodayIntent.swift…Intents/OpenTodayIntent.swift Asterism/Asterism/Intents/OpenWorkIntent.swift…/Intents/OpenWorkIntent.swift Asterism/Asterism/Intents/ShortcutParameters.swift…ents/ShortcutParameters.swift Asterism/Asterism/Intents/WorkEntity.swift…rism/Intents/WorkEntity.swift Asterism/Asterism/Layout/AppNavigation.swift…sm/Layout/AppNavigation.swift Asterism/Asterism/Layout/IntentEditSession.swift…ayout/IntentEditSession.swift Asterism/Asterism/Support/AppLifecycle.swift…sm/Support/AppLifecycle.swift Asterism/Asterism/Support/PlatformModifiers.swift…pport/PlatformModifiers.swift Asterism/Asterism/ViewModels/AppLibraryModel.swift…wModels/AppLibraryModel.swift Asterism/Asterism/ViewModels/EntryDetailModel.swift…Models/EntryDetailModel.swift Asterism/Asterism/Views/CreatorDetailView.swift…Views/CreatorDetailView.swift Asterism/Asterism/Views/EntryDetailView.swift…m/Views/EntryDetailView.swift Asterism/Asterism/Views/MaintenanceViews.swift…/Views/MaintenanceViews.swift Asterism/Asterism/Views/SeriesDetailView.swift…/Views/SeriesDetailView.swift Asterism/Asterism/Views/StatsView.swift…sterism/Views/StatsView.swift Asterism/Asterism/Views/WorkDetailView.swift…sm/Views/WorkDetailView.swift Asterism/AsterismTests/AddPageToReadFlowTests.swift…/AddPageToReadFlowTests.swift Asterism/AsterismTests/AppNavigationIntentRouteTests.swift…igationIntentRouteTests.swift Asterism/AsterismTests/EntryDetailModelTests.swift…s/EntryDetailModelTests.swift Asterism/AsterismTests/IntentLibraryBrokerTests.swift…ntentLibraryBrokerTests.swift Asterism/AsterismTests/OpenTargetFlowTests.swift…sts/OpenTargetFlowTests.swift Asterism/AsterismTests/WorkEntityQueryTests.swift…ts/WorkEntityQueryTests.swift Asterism/AsterismTests/Helpers/MirroredContainerGate.swift…s/MirroredContainerGate.swift Asterism/AsterismTests/Helpers/MockLibraryProvider.swift…ers/MockLibraryProvider.swift Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swift…erismCore/IntentAnswers.swift Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift…smCore/LibraryProviding.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift…aryRepository+Bootstrap.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift…braryRepository+Capture.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift…braryRepository+Intents.swift Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift…mCore/LibraryRepository.swift Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift…/AsterismCore/Snapshots.swift Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swift…ests/IntentAnswersTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift…eTests/IntentReadsTests.swift Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift…edScalePerformanceTests.swift scripts/verify-identity.shscripts/verify-identity.sh
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

59 files: 47 code · 12 docs. Click to expand.

Code (47)

Asterism/Asterism.xcodeproj/project.pbxproj Modified +2 / -0
diff --git a/Asterism/Asterism.xcodeproj/project.pbxproj b/Asterism/Asterism.xcodeproj/project.pbxprojindex cb8ebc2a..1930c7e7 100644--- a/Asterism/Asterism.xcodeproj/project.pbxproj+++ b/Asterism/Asterism.xcodeproj/project.pbxproj@@ -718,6 +718,7 @@ 				ENABLE_USER_SELECTED_FILES = readwrite; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = Asterism/Info.plist;+				INFOPLIST_KEY_CFBundleDisplayName = Devsterism; 				"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; 				"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; 				"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;@@ -767,6 +768,7 @@ 				ENABLE_USER_SELECTED_FILES = readwrite; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = Asterism/Info.plist;+				INFOPLIST_KEY_CFBundleDisplayName = Asterism; 				"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; 				"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; 				"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;
Asterism/Asterism/AsterismApp.swift Modified +23 / -3
diff --git a/Asterism/Asterism/AsterismApp.swift b/Asterism/Asterism/AsterismApp.swiftindex f88c899a..956a5eea 100644--- a/Asterism/Asterism/AsterismApp.swift+++ b/Asterism/Asterism/AsterismApp.swift@@ -8,6 +8,7 @@ #if os(macOS) import AppKit #endif+import AppIntents import AsterismCore import ConstellationKit import SwiftUI@@ -24,11 +25,15 @@ struct AsterismApp: App {     /// The library, owned by the app rather than by `ContentView` (Q14): the     /// macOS `Settings` scene needs the same model as the main window, and two     /// scenes cannot share a view's `@State`.-    @State private var model = ContentView.launchModel()+    ///+    /// Built in `init` rather than at the declaration (`app-intents`), so the+    /// same instance can be registered for the intents there.+    @State private var model: AppLibraryModel     /// Every piece of navigation state (Q21), for the same reason and one more:     /// Req 2.3 asks that the compact and wide trees be two views over one-    /// place, so the state has to outlive whichever of them is on screen.-    @State private var navigation = AppNavigation()+    /// place, so the state has to outlive whichever of them is on screen. Built+    /// in `init` for the model's reason: the open intents route through it.+    @State private var navigation: AppNavigation     /// The announcement seen state (`today-announcements` Q22), for both of the     /// reasons above and one more: a `UserDefaults` write triggers no     /// Observation, so the Mac's Settings window storing the version has to be@@ -59,6 +64,18 @@ struct AsterismApp: App {     #endif      init() {+        let model = ContentView.launchModel()+        let navigation = AppNavigation()+        _model = State(initialValue: model)+        _navigation = State(initialValue: navigation)+        // `app-intents`: the intents read the library and the navigation+        // through `@Dependency`, and this is Apple's documented place to+        // register them — `App.init` runs on a background intent launch that+        // connects no scene, where no view's `task` ever would. The instances+        // are the ones the scenes below are handed, so an intent and the window+        // see one library and one navigation.+        AppDependencyManager.shared.add(dependency: model)+        AppDependencyManager.shared.add(dependency: navigation)         #if canImport(UIKit)         Self.applySerifNavigationTitles()         #endif@@ -101,6 +118,9 @@ struct AsterismApp: App {             // removes the row over there.             .environment(\.siteNames, model.siteNames)             .environment(announcements)+            // `app-intents` Q30: a draft open in this window blocks an open+            // intent as surely as one in the main window.+            .environment(\.intentEditSessions, navigation)         }         .defaultSize(width: 640, height: 560)         #else
Asterism/Asterism/ContentView.swift Modified +33 / -4
diff --git a/Asterism/Asterism/ContentView.swift b/Asterism/Asterism/ContentView.swiftindex 9fb49898..66282ba8 100644--- a/Asterism/Asterism/ContentView.swift+++ b/Asterism/Asterism/ContentView.swift@@ -371,10 +371,27 @@ struct ContentView: View {         // Before the bootstrap rather than after it, so the reader's place is         // already set when the first snapshot arrives and the detail column         // never flashes a placeholder it is about to replace.-        .onAppear(perform: restoreSelection)+        .onAppear {+            restoreSelection()+            // `app-intents`: after the restore, so a route an open intent left+            // wins over the place the Mac was left on. Only takes anything when+            // the library is already ready — a window reopened on a resident+            // Mac; otherwise the `.ready` edge below takes it.+            takeIntentRoute()+        }         .task {             await model.bootstrap()         }+        // `app-intents` Req 4.6: a route set while the library was opening or+        // unavailable is taken once it is ready.+        .onChange(of: model.state) { _, state in+            if state == .ready { takeIntentRoute() }+        }+        // And one set while it already is: an open intent against a resident+        // app (Reqs 4.1, 4.2).+        .onChange(of: navigation.intentRoute) { _, route in+            if route != nil { takeIntentRoute() }+        }         // The mirror. One `onChange` each rather than a single observer of the         // navigation object: these are the three values Q23 stores, and a         // fourth arriving in `AppNavigation` should not silently join them.@@ -511,9 +528,17 @@ struct ContentView: View {     private func restoreSelection() {         guard RuntimePlatform.isMac, !hasRestoredSelection else { return }         hasRestoredSelection = true-        navigation.selectedTab = AppTab(rawValue: storedTab) ?? .today-        navigation.selectedTodayEntryID = UUID(uuidString: storedTodayEntryID)-        navigation.restoreWorksSelection(UUID(uuidString: storedWorkID))+        navigation.restoreSelection(+            tab: AppTab(rawValue: storedTab),+            todayEntryID: UUID(uuidString: storedTodayEntryID),+            workID: UUID(uuidString: storedWorkID))+    }++    /// Applies an open intent's waiting route, once the library is ready to+    /// say whether its work exists (`app-intents` Q42).+    private func takeIntentRoute() {+        guard model.state == .ready else { return }+        navigation.takeIntentRoute(workTitlesByID: model.workTitlesByID)     }      /// Holds the restored ids to the library, once it has one to be held to@@ -597,6 +622,10 @@ struct ContentView: View {             // window is a second scene and gets its own write in `AsterismApp`,             // of the same instance.             .environment(announcements)+            // `app-intents` Q30: where an editor or a local sheet registers its+            // draft, written here for `siteNames`' reason — it reaches both+            // trees, everything they push and every sheet.+            .environment(\.intentEditSessions, navigation)     }      private var presentedContent: some View {
Asterism/Asterism/Intents/AddPageToReadFlow.swift Added +174 / -0
diff --git a/Asterism/Asterism/Intents/AddPageToReadFlow.swift b/Asterism/Asterism/Intents/AddPageToReadFlow.swiftnew file mode 100644index 00000000..c9ceb7ea--- /dev/null+++ b/Asterism/Asterism/Intents/AddPageToReadFlow.swift@@ -0,0 +1,174 @@+import AsterismCore+import Foundation++/// The add intent's decisions, as a plain type (`app-intents` Req 3).+///+/// The intent maps the prompts to `requestValue` and `requestChoice`; the+/// flow decides when to ask, what to write and what to say, so every path is+/// unit-tested without the App Intents runtime. A cancelled prompt throws out+/// of `run` before the write, so a cancel writes nothing (Req 3.7).+///+/// Every run writes one outcome line (Req 6.7), cancels included, and every+/// line says whether the page was supplied or asked for (`url supplied` or+/// `url asked`), which the runbook's Safari step reads.+@MainActor+struct AddPageToReadFlow {+    /// The answer to the fetched-title choice (Decision 3).+    enum TitleChoice: Equatable, Sendable {+        case useFetched+        case change+    }++    /// The three questions the flow can ask. Each throws when the reader+    /// cancels.+    struct Prompts {+        var askForURL: @MainActor () async throws -> URL+        var chooseTitle: @MainActor (_ fetchedTitle: String) async throws -> TitleChoice+        var askForTitle: @MainActor () async throws -> String+    }++    /// What the intent says, and the work it created, if it created one.+    struct Outcome: Equatable {+        let dialog: String+        let created: WorkSummary?+    }++    static let notAWebPageSentence = "Asterism can only add a web page, with an http or https address."+    static let unattachedChapterSentence =+        "That page is already in your library, captured as a chapter that isn't part of a work."++    let broker: IntentLibraryBroker+    /// The page's title, or nil where none came back within the bound. The+    /// intent passes `BoundedPageTitleFetcher`'s (3 s, 64 KB).+    let fetchTitle: @Sendable (URL) async -> String?+    let prompts: Prompts++    /// Runs the flow for a page and an optional supplied title.+    func run(url suppliedURL: URL?, title suppliedTitle: String?) async throws -> Outcome {+        let intent = "add page to read (url \(suppliedURL == nil ? "asked" : "supplied"))"+        do {+            return try await decide(url: suppliedURL, title: suppliedTitle, intent: intent)+        } catch {+            // Only a prompt throws out of the flow: every library refusal is+            // answered. So this is the reader cancelling, at whichever prompt.+            IntentLog.note("\(intent): cancelled")+            throw error+        }+    }++    private func decide(+        url suppliedURL: URL?, title suppliedTitle: String?, intent: String+    ) async throws -> Outcome {+        // Req 3.8: a page Siri supplies from the screen arrives as `url`; with+        // none, ask.+        let url: URL+        if let suppliedURL {+            url = suppliedURL+        } else {+            url = try await prompts.askForURL()+        }+        let rawURL = url.absoluteString++        // Req 3.6: refused before anything is read.+        guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else {+            IntentLog.note("\(intent): not a web page", content: rawURL)+            return Outcome(dialog: Self.notAWebPageSentence, created: nil)+        }++        // Req 3.5's first check, before the reader is asked anything.+        let match: PageMatch?+        do {+            match = try await broker.withLibrary(writes: false) { try await $0.pageMatch(rawURL: rawURL) }+        } catch {+            return refusal(error, intent: intent, url: rawURL)+        }+        if let match { return present(match, intent: intent, url: rawURL) }++        let title = try await confirmedTitle(supplied: suppliedTitle, url: url)++        // Req 3.4, with Req 3.5's check repeated under the write's lock. A+        // write only when it creates (Q48 as amended): the resident snapshots+        // refresh, or a cold session leaves the export owed. A `.present`+        // answer wrote nothing, so it is followed by neither.+        let draft = NewWorkDraft(displayTitle: title, hostname: rawURL, readingStatus: .toRead)+        let outcome: CreateWorkOutcome+        do {+            outcome = try await broker.withLibrary(wroteIf: Self.created) {+                try await $0.createWorkUnlessPresent(draft)+            }+        } catch {+            return refusal(error, intent: intent, url: rawURL)+        }+        switch outcome {+        case .present(let match):+            return present(match, intent: intent, url: rawURL)+        case .created(let work):+            let summary = WorkSummary(+                id: work.id, displayTitle: work.displayTitle,+                readingStatus: work.readingStatus, workStatus: work.workStatus)+            IntentLog.note("\(intent): created", content: "\(work.displayTitle) | \(rawURL)")+            return Outcome(+                dialog: "Added “\(work.displayTitle)” as \(ReadingStatusPresentation.name(work.readingStatus)).",+                created: summary)+        }+    }++    private static func created(_ outcome: CreateWorkOutcome) -> Bool {+        if case .created = outcome { return true }+        return false+    }++    // MARK: - The title (Reqs 3.1–3.3, Decision 3)++    private func confirmedTitle(supplied: String?, url: URL) async throws -> String {+        // Req 3.2, Q41: a supplied title is used as given, unless it is blank.+        if let supplied = Self.nonBlank(supplied) { return supplied }+        if let fetched = Self.nonBlank(await fetchTitle(url)),+           try await prompts.chooseTitle(fetched) == .useFetched+        {+            return fetched+        }+        // "Change title", or nothing fetched: ask, and ask again while blank+        // (Req 3.3). A cancel throws out of the loop.+        while true {+            if let answer = Self.nonBlank(try await prompts.askForTitle()) { return answer }+        }+    }++    private static func nonBlank(_ text: String?) -> String? {+        guard let trimmed = text?.trimmingCharacters(in: .whitespacesAndNewlines),+              !trimmed.isEmpty+        else { return nil }+        return trimmed+    }++    // MARK: - Answers++    private func present(_ match: PageMatch, intent: String, url: String) -> Outcome {+        switch match {+        case .work(let work):+            IntentLog.note("\(intent): already a work", content: "\(work.displayTitle) | \(url)")+            return Outcome(+                dialog: "“\(work.displayTitle)” is already in your library, as \(ReadingStatusPresentation.name(work.readingStatus)).",+                created: nil)+        case .unattachedEntry(let captureTitle):+            IntentLog.note("\(intent): already an unattached chapter", content: "\(captureTitle) | \(url)")+            return Outcome(dialog: Self.unattachedChapterSentence, created: nil)+        }+    }++    /// An unavailable library, or the library's own refusal worded as the New+    /// Work form would word it (Req 3.6, Q49). Answered either way: the add+    /// flow is the one intent that words a `.failed` step rather than+    /// rethrowing it (Q58).+    private func refusal(_ error: IntentLibraryError, intent: String, url: String) -> Outcome {+        switch IntentOutcome.refusal(error, intent: intent, content: url) {+        case .unavailable(let sentence):+            return Outcome(dialog: sentence, created: nil)+        case .rethrow(let underlying):+            return Outcome(+                dialog: "Asterism couldn't add that page. \(underlying.localizedDescription)",+                created: nil)+        }+    }+}
Asterism/Asterism/Intents/AddPageToReadIntent.swift Added +76 / -0
diff --git a/Asterism/Asterism/Intents/AddPageToReadIntent.swift b/Asterism/Asterism/Intents/AddPageToReadIntent.swiftnew file mode 100644index 00000000..3b131813--- /dev/null+++ b/Asterism/Asterism/Intents/AddPageToReadIntent.swift@@ -0,0 +1,76 @@+import AppIntents+import AsterismCore+import Foundation++/// "Add this as to read" (`app-intents` Req 3).+///+/// A thin shell over `AddPageToReadFlow`: the flow decides, and this maps its+/// three questions onto the App Intents prompts (Decision 3). Runs in the+/// background (Req 6.1) and only on an unlocked device (Req 6.3).+struct AddPageToReadIntent: AppIntent {+    static var title: LocalizedStringResource { "Add Page as To Read" }++    static var description: IntentDescription? {+        IntentDescription(+            "Adds a web page to your library as a new work to read, after you confirm its title.")+    }++    static var supportedModes: IntentModes { .background }++    static var authenticationPolicy: IntentAuthenticationPolicy {+        .requiresLocalDeviceAuthentication+    }++    /// The page. From a Shortcuts action, the share sheet through Shortcuts,+    /// or the page Siri supplies from the screen (Req 3.8, Q16); asked for when+    /// none arrives.+    @Parameter(title: "Web Page")+    var url: URL?++    /// A title supplied with the action skips the fetch and the prompts+    /// (Req 3.2). Blank counts as not supplied (Q41).+    @Parameter(title: "Title")+    var title: String?++    static var parameterSummary: some ParameterSummary {+        Summary("Add \(\.$url) as to read") {+            \.$title+        }+    }++    @Dependency private var model: AppLibraryModel++    @MainActor+    func perform() async throws -> some IntentResult & ReturnsValue<WorkEntity?> & ProvidesDialog {+        let flow = AddPageToReadFlow(+            broker: model.intentBroker,+            fetchTitle: { url in+                // A throw or the 3 s / 64 KB bound running out is no title.+                (try? await BoundedPageTitleFetcher().fetch(url: url.absoluteString))??.title+            },+            prompts: AddPageToReadFlow.Prompts(+                askForURL: { try await $url.requestValue("Which page?") },+                chooseTitle: { fetched in try await chooseTitle(fetched) },+                askForTitle: { try await $title.requestValue("What should it be called?") }))+        let outcome = try await flow.run(url: url, title: title)+        return .result(+            value: outcome.created.map(WorkEntity.init),+            dialog: IntentDialog(stringLiteral: outcome.dialog))+    }++    /// Decision 3's choice: use the fetched title, or change it.+    @MainActor+    private func chooseTitle(_ fetched: String) async throws -> AddPageToReadFlow.TitleChoice {+        let use = IntentChoiceOption(title: "Use “\(fetched)”")+        let change = IntentChoiceOption(title: "Change title")+        let chosen = try await requestChoice(+            between: [use, change, .cancel], dialog: "Add it as “\(fetched)”?")+        switch chosen {+        case use: return .useFetched+        case change: return .change+        // The system ends the run on Cancel itself; this is the backstop, so a+        // cancel can never fall through to the write (Req 3.7).+        default: throw CancellationError()+        }+    }+}
Asterism/Asterism/Intents/AsterismShortcuts.swift Added +56 / -0
diff --git a/Asterism/Asterism/Intents/AsterismShortcuts.swift b/Asterism/Asterism/Intents/AsterismShortcuts.swiftnew file mode 100644index 00000000..8083fa79--- /dev/null+++ b/Asterism/Asterism/Intents/AsterismShortcuts.swift@@ -0,0 +1,56 @@+import AppIntents++/// The App Shortcuts: every intent available from Siri, Spotlight and the+/// Shortcuts app with no setup (`app-intents` Req 7.1).+///+/// Every phrase names the app through `.applicationName`, which is the display+/// name — Devsterism for `Development` — so the two apps' phrases resolve to+/// different apps on one device (Req 7.3).+nonisolated struct AsterismShortcuts: AppShortcutsProvider {+    static var appShortcuts: [AppShortcut] {+        AppShortcut(+            intent: ChaptersReleasingTodayIntent(),+            phrases: [+                "What's releasing today in \(.applicationName)",+                "Chapters releasing today in \(.applicationName)",+            ],+            shortTitle: "Releasing Today",+            systemImageName: "calendar")+        AppShortcut(+            intent: NotesFromTodayIntent(),+            phrases: [+                "Notes from today in \(.applicationName)",+                "What did I note today in \(.applicationName)",+            ],+            shortTitle: "Notes from Today",+            systemImageName: "note.text")+        AppShortcut(+            intent: AddPageToReadIntent(),+            phrases: [+                "Add this as to read in \(.applicationName)",+                "Add this page to read in \(.applicationName)",+                "Save this to read later in \(.applicationName)",+            ],+            shortTitle: "Add as To Read",+            systemImageName: "bookmark")+        AppShortcut(+            intent: OpenTodayIntent(),+            phrases: [+                "Open Today in \(.applicationName)",+                "Show Today in \(.applicationName)",+            ],+            shortTitle: "Open Today",+            systemImageName: "sun.max")+        // The spoken name comes from `WorkEntityQuery.suggestedEntities()`, the+        // reading and catching-up works, which `ShortcutParameters` keeps+        // registered (Req 5.4, Q23).+        AppShortcut(+            intent: OpenWorkIntent(),+            phrases: [+                "Open \(\.$work) in \(.applicationName)",+                "Show \(\.$work) in \(.applicationName)",+            ],+            shortTitle: "Open Work",+            systemImageName: "book")+    }+}
Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swift Added +91 / -0
diff --git a/Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swift b/Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swiftnew file mode 100644index 00000000..c781e4b4--- /dev/null+++ b/Asterism/Asterism/Intents/ChaptersReleasingTodayIntent.swift@@ -0,0 +1,91 @@+import AppIntents+import AsterismCore+import Foundation+import SwiftUI++/// "Which chapters release today?" (`app-intents` Req 1).+///+/// Answers from the Today read and `IntentAnswers`, the derivation the Today+/// screen draws from, built for the civil day at the moment the intent runs+/// (Req 1.4, Q17). Runs in the background (Req 6.1) and only on an unlocked+/// device (Req 6.3).+struct ChaptersReleasingTodayIntent: AppIntent {+    static var title: LocalizedStringResource { "Chapters Releasing Today" }++    static var description: IntentDescription? {+        IntentDescription(+            "Lists the works in your library with a chapter expected today, as the Today screen shows them.")+    }++    static var supportedModes: IntentModes { .background }++    static var authenticationPolicy: IntentAuthenticationPolicy {+        .requiresLocalDeviceAuthentication+    }++    @Dependency private var model: AppLibraryModel++    @MainActor+    func perform() async throws+        -> some IntentResult & ReturnsValue<[WorkEntity]> & ProvidesDialog & ShowsSnippetView+    {+        let calendar = model.intentCalendar+        let currentDay = CivilDay(Date(), calendar: calendar)+        // One step, so a cold library is opened once for both reads: the+        // Today read, and the summaries the returned work values carry.+        guard let answer = try await IntentOutcome.read(+            model.intentBroker, intent: "chapters releasing today",+            { library -> (releases: [ReleaseAnswer], works: [WorkSummary]) in+                let presentation = try await library.todayPresentation(calendar: calendar)+                let releases = IntentAnswers.releasingToday(+                    presentation, currentDay: currentDay, calendar: calendar)+                return (releases, try await library.workSummaries(ids: releases.map(\.workID)))+            })+        else {+            let sentence = IntentOutcome.unavailableSentence+            return .result(+                value: [], dialog: IntentDialog(stringLiteral: sentence),+                view: IntentMessageSnippet(text: sentence))+        }++        let dialog = IntentAnswers.dialog(for: answer.releases)+        // In the releases' order, once each, already: that is what+        // `workSummaries(ids:)` answers.+        let values = answer.works.map(WorkEntity.init)+        IntentLog.note(+            "chapters releasing today: \(answer.releases.count) works",+            content: answer.releases.map(\.title).joined(separator: "; "))+        return .result(+            value: values,+            dialog: IntentDialog(+                full: "\(dialog.full)", supporting: "\(dialog.supporting)"),+            view: ReleasesSnippet(releases: answer.releases, summary: dialog.supporting))+    }+}++/// The shown list: every release, with a mark on the ones noted today.+private struct ReleasesSnippet: View {+    let releases: [ReleaseAnswer]+    let summary: String++    var body: some View {+        VStack(alignment: .leading, spacing: 6) {+            if releases.isEmpty {+                Text(summary)+            } else {+                ForEach(releases, id: \.workID) { release in+                    HStack(spacing: 6) {+                        Text(release.title)+                        if release.notedToday {+                            Image(systemName: "checkmark.circle.fill")+                                .foregroundStyle(.secondary)+                                .accessibilityLabel("Noted today")+                        }+                    }+                }+            }+        }+        .padding()+        .frame(maxWidth: .infinity, alignment: .leading)+    }+}
Asterism/Asterism/Intents/IntentLibraryBroker.swift Added +321 / -0
diff --git a/Asterism/Asterism/Intents/IntentLibraryBroker.swift b/Asterism/Asterism/Intents/IntentLibraryBroker.swiftnew file mode 100644index 00000000..2be9f0a8--- /dev/null+++ b/Asterism/Asterism/Intents/IntentLibraryBroker.swift@@ -0,0 +1,321 @@+import AppIntents+import AsterismCore+import Foundation++/// Why an intent could not get an answer out of the library.+///+/// `CustomLocalizedStringResourceConvertible`, which is what App Intents reads+/// for the message of an error thrown from `perform` or an entity query: an+/// unavailable library is said in the design's sentence, and a refusal in the+/// refusal's own words.+nonisolated enum IntentLibraryError: Error, CustomLocalizedStringResourceConvertible {+    /// No library yet, a marker this build cannot open, a store that failed+    /// validation, the lock held past the interactive timeout, or a model that+    /// has already said so (Req 6.2, and the requirements' definition of+    /// "library unavailable").+    case unavailable+    /// The library answered, and the answer was a refusal — an invalid URL, a+    /// title `createWork` will not take. Carried whole, so an intent can say+    /// the reason the New Work form would have said (Req 3.6).+    case failed(any Error)++    var localizedStringResource: LocalizedStringResource {+        switch self {+        case .unavailable: "\(IntentOutcome.unavailableSentence)"+        case .failed(let underlying): "\(underlying.localizedDescription)"+        }+    }+}++/// The one way an intent reaches the library (`app-intents` Decision 4).+///+/// A step is one repository call. It runs on the **resident** repository when+/// the app has a library open, and otherwise on a **cold** session opened with+/// `openForExtension` — the share extension's opener: existing-only, a shared+/// lease with the interactive timeout, mirroring off — that lives for exactly+/// that step. Nothing holds a session across a prompt or between two queries,+/// so no caller needs a lifetime rule.+///+/// **One step at a time, in arrival order.** The main actor is not a mutex — it+/// is reentrant at every `await` — so admission is a FIFO of waiting callers,+/// each resumed by the step before it. `bootstrap()` waits for that queue to+/// empty before it releases the previous library and opens the mirrored one+/// (Req 6.4); it never cancels a step, so no write is torn and none is retried.+/// A background-export pass takes the same turn while it opens and while it+/// shuts down its cold session (`holdingTurn`), so no step can open a second+/// container beside it.+///+/// Owned by `AppLibraryModel`, which is what gives it one instance per process:+/// the same object `AsterismApp` registers for the intents is the one+/// `bootstrap()` drains.+@MainActor+final class IntentLibraryBroker {+    /// `unowned`: the model owns this object and outlives it by construction.+    private unowned let model: AppLibraryModel++    /// Whether a step holds the admission turn — running, or handed the turn+    /// and about to.+    private var holdsTurn = false+    /// Callers waiting for the turn, oldest first.+    private var admissionQueue: [CheckedContinuation<Void, Never>] = []+    /// `drain()` callers, resumed when the queue empties.+    private var drainWaiters: [CheckedContinuation<Void, Never>] = []++    /// The snapshot refresh the last resident write started, kept so a test can+    /// await it. It runs outside the turn: the answer does not wait for it.+    private(set) var pendingWriteRefresh: Task<Void, Never>?++    init(model: AppLibraryModel) {+        self.model = model+    }++    /// Whether a step is in flight or waiting for its turn. A background+    /// export pass does not start while this holds (Decision 4, "Export+    /// yields").+    var isBusy: Bool { holdsTurn }++    /// Whether the app is opening its library right now — a scene's bootstrap+    /// is in flight. A step started now would wait for it (Req 6.2's+    /// "opening"); an open intent asks this first so it can route instead of+    /// waiting (Req 4.6).+    var isLibraryOpening: Bool { model.bootstrapInFlight }++    /// Runs one repository step and returns its answer.+    ///+    /// `writes` is the caller's statement that the step can change the library.+    /// The broker cannot see inside the closure, and what follows a write+    /// differs by arm: on the resident library the snapshots are refreshed, as+    /// the New Work form's `onMutation` refreshes them, and no reconcile is+    /// scheduled (Req 3.9); on a cold session an `ExportOwed/` marker is left,+    /// so the change reaches CloudKit on the next grant or foreground (Req 6.5).+    /// Required, with no default, so a write can never be declared a read by+    /// omission.+    ///+    /// Waits while the app is opening its library rather than failing+    /// (Req 6.2's "opening").+    func withLibrary<T: Sendable>(+        writes: Bool,+        _ step: @escaping @Sendable (any LibraryProviding) async throws -> T+    ) async throws(IntentLibraryError) -> T {+        try await withLibrary(wroteIf: { _ in writes }, step)+    }++    /// The same, for a step whose answer says whether it wrote — the add+    /// intent's `createWorkUnlessPresent`, which writes nothing when it answers+    /// `.present`. What follows a write follows only when `wrote` says so.+    func withLibrary<T: Sendable>(+        wroteIf wrote: (T) -> Bool,+        _ step: @escaping @Sendable (any LibraryProviding) async throws -> T+    ) async throws(IntentLibraryError) -> T {+        while true {+            // Before admission, so a step that arrives while `bootstrap()` is+            // opening never joins the queue that bootstrap is draining.+            if model.bootstrapInFlight { await model.libraryReady() }+            await admit()+            // A step that was already queued when a bootstrap started reaches+            // its turn with the library half-open. It gives the turn back and+            // waits like a late arrival: running cold here would put a second+            // container beside the one bootstrap is about to open, and waiting+            // while holding the turn would deadlock the drain.+            if model.bootstrapInFlight, model.state == .loading {+                release()+                continue+            }+            defer { release() }+            return try await run(wrote: wrote, step)+        }+    }++    /// Runs `body` holding the admission turn, after the steps already queued.+    ///+    /// The background-export pass's call, around its cold open and around its+    /// shutdown: a step admitted meanwhile would find no session to borrow and+    /// open a second container beside the pass's. Steps that queue behind it+    /// run once it returns — on the session it set, or cold after a failed or+    /// cancelled open. The turn is released however `body` ends, so a pass that+    /// `bootstrap()` cancels frees it before bootstrap drains.+    func holdingTurn<T>(_ body: () async -> T) async -> T {+        await admit()+        defer { release() }+        return await body()+    }++    /// Resolves when no step is in flight or waiting. `bootstrap()`'s call.+    func drain() async {+        guard holdsTurn else { return }+        await withCheckedContinuation { drainWaiters.append($0) }+    }++    // MARK: - Admission++    private func admit() async {+        guard holdsTurn else {+            holdsTurn = true+            return+        }+        await withCheckedContinuation { admissionQueue.append($0) }+    }++    /// Hands the turn to the oldest waiter, or frees it and wakes the drains.+    private func release() {+        guard admissionQueue.isEmpty else {+            admissionQueue.removeFirst().resume()+            return+        }+        holdsTurn = false+        let waiters = drainWaiters+        drainWaiters = []+        for waiter in waiters { waiter.resume() }+    }++    // MARK: - The three arms++    private func run<T: Sendable>(+        wrote: (T) -> Bool,+        _ step: @escaping @Sendable (any LibraryProviding) async throws -> T+    ) async throws(IntentLibraryError) -> T {+        switch model.state {+        case .ready:+            guard let library = model.intentResidentLibrary else { throw .unavailable }+            let value = try await outcome(of: step, on: library).get()+            if wrote(value) { refreshAfterWrite() }+            return value+        case .unavailable:+            // The foreground has already diagnosed it; a cold open would only+            // repeat the diagnosis.+            throw .unavailable+        case .loading:+            // Not bootstrapping (that waited above), so no scene has asked for+            // the library: a background launch, or a window that has not started+            // its bootstrap yet.+            return try await runCold(wrote: wrote, step)+        }+    }++    /// A resident write's refresh, started after the answer and outside the+    /// turn: the reader is not kept waiting for a full snapshot rebuild, and the+    /// next step is not queued behind it.+    private func refreshAfterWrite() {+        let model = model+        pendingWriteRefresh = Task { @MainActor in+            await model.intentStepDidWrite()+        }+    }++    private func runCold<T: Sendable>(+        wrote: (T) -> Bool,+        _ step: @escaping @Sendable (any LibraryProviding) async throws -> T+    ) async throws(IntentLibraryError) -> T {+        let scene = Self.sceneState+        let configuration: LibraryConfiguration+        switch model.intentConfiguration {+        case .success(let resolved):+            configuration = resolved+        case .failure(let error):+            IntentLog.note("cold step unavailable: \(error.message) | scene=\(scene)")+            throw .unavailable+        }+        let marker = ExportOwedMarker(directory: configuration.exportOwedURL)++        // A background-export pass already holds a session in this process. A+        // second container beside it is what the one-container rule forbids, so+        // the step borrows it; the pass shuts the session down only while it+        // holds the turn, which is after this step.+        if let session = model.backgroundSession?.repository {+            return try await coldStep(+                step, on: session, wrote: wrote, marker: marker,+                label: "cold step on the export session:", scene: scene)+        }++        let clock = ContinuousClock()+        let started = clock.now+        let repository: LibraryRepository+        do {+            repository = try await LibraryRepository.openForExtension(+                configuration, capabilities: model.capabilities+            ).repository+        } catch {+            // No marker, a marker this build cannot open, a store that fails+            // validation, a lease timeout: all of them are "not available", and+            // none of them is repaired from here.+            IntentLog.note(+                "cold open unavailable after \(IntentLog.milliseconds(clock.now - started)) ms: "+                    + "\(IntentLog.describe(error)) | scene=\(scene)")+            throw .unavailable+        }+        return try await coldStep(+            step, on: repository, wrote: wrote, marker: marker,+            label: "cold step: open \(IntentLog.milliseconds(clock.now - started)) ms,",+            scene: scene, afterStep: { await repository.shutdown() })+    }++    /// One step on a cold session: the step, the marker a write owes, whatever+    /// the session needs after it, and the one log line.+    private func coldStep<T: Sendable>(+        _ step: @escaping @Sendable (any LibraryProviding) async throws -> T,+        on library: LibraryRepository,+        wrote: (T) -> Bool,+        marker: ExportOwedMarker,+        label: String,+        scene: String,+        afterStep: () async -> Void = {}+    ) async throws(IntentLibraryError) -> T {+        let clock = ContinuousClock()+        let started = clock.now+        let result = await outcome(of: step, on: library)+        let stepped = clock.now - started+        if case .success(let value) = result, wrote(value) { markExportOwed(marker) }+        await afterStep()+        IntentLog.note(+            "\(label) step \(IntentLog.milliseconds(stepped)) ms, "+                + "\(Self.describe(result)) | scene=\(scene)")+        return try result.get()+    }++    // MARK: - Helpers++    /// The step's answer, with the two refusals that mean "the library is not+    /// there right now" folded into `.unavailable`: a lock held past the+    /// interactive timeout, and a library that is closed or closing.+    private func outcome<T: Sendable>(+        of step: @escaping @Sendable (any LibraryProviding) async throws -> T,+        on library: any LibraryProviding+    ) async -> Result<T, IntentLibraryError> {+        do {+            return .success(try await step(library))+        } catch let error as LibraryRepositoryError {+            switch error {+            case .libraryBusy, .libraryUnavailable: return .failure(.unavailable)+            default: return .failure(.failed(error))+            }+        } catch {+            return .failure(.failed(error))+        }+    }++    /// The share extension's rule: a marker that cannot be written costs the+    /// prompt export, never the write, and the next foreground mirror run+    /// exports the change anyway (Req 6.5).+    private func markExportOwed(_ marker: ExportOwedMarker) {+        do {+            try marker.mark()+        } catch {+            IntentLog.failure("could not mark the export owed: \(IntentLog.describe(error))")+        }+    }++    private static func describe<T>(_ result: Result<T, IntentLibraryError>) -> String {+        switch result {+        case .success: "succeeded"+        case .failure(.unavailable): "unavailable"+        case .failure(.failed(let error)): "failed: \(IntentLog.describe(error))"+        }+    }++    /// Whether a scene was connected when a cold step ran — the design's+    /// assumption that a background intent launch runs `App.init` without one,+    /// recorded on every cold step rather than argued (design, Risks).+    private static var sceneState: String {+        AppLifecycle.hasConnectedScene ? "connected" : "none"+    }+}
Asterism/Asterism/Intents/IntentLog.swift Added +47 / -0
diff --git a/Asterism/Asterism/Intents/IntentLog.swift b/Asterism/Asterism/Intents/IntentLog.swiftnew file mode 100644index 00000000..8bfcc672--- /dev/null+++ b/Asterism/Asterism/Intents/IntentLog.swift@@ -0,0 +1,47 @@+import Foundation+import OSLog++/// The App Intents diagnostic log (`app-intents` Req 6.7).+///+/// An intent runs where nobody is looking — Siri, a shortcut, a phone with no+/// scene connected — so these lines are the only record of what it did and+/// why. Follow a run in Console.app with+/// `subsystem:me.nore.ig.Asterism category:AppIntents`.+///+/// The body is `PipelineLog`'s, for the reason the two model pipelines share+/// it: one privacy split. The *reason* — the outcome, the step, the open and+/// step milliseconds, whether a scene was connected — is always readable. The+/// *content* — titles, URLs, note text — is readable in a `Development` build+/// only.+///+/// `nonisolated` for `RuleSuggestionLog`'s reason: a static under this target's+/// default isolation would otherwise be main-actor bound, and an intent's+/// entity query is not guaranteed to run there.+nonisolated enum IntentLog {+    static let pipeline = PipelineLog(category: "AppIntents")++    static var logger: Logger { pipeline.logger }++    /// Logged at notice level by default, like the `BackgroundExport` lines: a+    /// `.debug` line is hidden in Console and never persisted, and an intent+    /// that ran before Console was streaming would leave no evidence.+    static func note(+        _ reason: @autoclosure () -> String,+        content: @autoclosure () -> String? = nil,+        level: OSLogType = .default+    ) {+        pipeline.note(reason(), content: content(), level: level)+    }++    static func failure(+        _ reason: @autoclosure () -> String, content: @autoclosure () -> String? = nil+    ) {+        pipeline.failure(reason(), content: content())+    }++    static func describe(_ error: any Error) -> String { PipelineLog.describe(error) }++    static func milliseconds(_ duration: Duration) -> Int64 {+        PipelineLog.milliseconds(duration)+    }+}
Asterism/Asterism/Intents/IntentOutcome.swift Added +71 / -0
diff --git a/Asterism/Asterism/Intents/IntentOutcome.swift b/Asterism/Asterism/Intents/IntentOutcome.swiftnew file mode 100644index 00000000..ae6e14f9--- /dev/null+++ b/Asterism/Asterism/Intents/IntentOutcome.swift@@ -0,0 +1,71 @@+import AppIntents+import AsterismCore+import Foundation+import SwiftUI++/// What an intent says when the broker would not give it an answer.+///+/// An unavailable library is an answer, not a failure: the reader is told so+/// in the sentence the design fixes (Error Handling), and nothing is written.+/// Any other refusal is thrown on with its own reason, which+/// `LibraryRepositoryError` already words (Req 3.6, Q49).+nonisolated enum IntentOutcome {+    static let unavailableSentence = "Your Asterism library isn't available right now."++    enum Refusal {+        case unavailable(String)+        case rethrow(any Error)+    }++    /// Sorts a broker refusal without logging it, for a flow that goes on to+    /// write its own outcome line.+    static func classify(_ error: IntentLibraryError) -> Refusal {+        switch error {+        case .unavailable: .unavailable(unavailableSentence)+        case .failed(let underlying): .rethrow(underlying)+        }+    }++    /// Sorts a broker refusal, logging it as the run's one outcome line.+    static func refusal(+        _ error: IntentLibraryError, intent: String, content: String? = nil+    ) -> Refusal {+        let refusal = classify(error)+        switch refusal {+        case .unavailable:+            IntentLog.note("\(intent): library unavailable", content: content)+        case .rethrow(let underlying):+            IntentLog.failure("\(intent): failed: \(IntentLog.describe(underlying))", content: content)+        }+        return refusal+    }++    /// A read intent's one broker step, or nil where the library is+    /// unavailable — which is then already logged as the run's outcome line.+    /// Any other refusal is logged and rethrown.+    @MainActor+    static func read<T: Sendable>(+        _ broker: IntentLibraryBroker, intent: String,+        _ step: @escaping @Sendable (any LibraryProviding) async throws -> T+    ) async throws -> T? {+        do {+            return try await broker.withLibrary(writes: false, step)+        } catch {+            switch refusal(error, intent: intent) {+            case .unavailable: return nil+            case .rethrow(let underlying): throw underlying+            }+        }+    }+}++/// A one-sentence snippet, for the answers that are a sentence.+struct IntentMessageSnippet: View {+    let text: String++    var body: some View {+        Text(text)+            .padding()+            .frame(maxWidth: .infinity, alignment: .leading)+    }+}
Asterism/Asterism/Intents/NotesFromTodayIntent.swift Added +79 / -0
diff --git a/Asterism/Asterism/Intents/NotesFromTodayIntent.swift b/Asterism/Asterism/Intents/NotesFromTodayIntent.swiftnew file mode 100644index 00000000..e04c7cd7--- /dev/null+++ b/Asterism/Asterism/Intents/NotesFromTodayIntent.swift@@ -0,0 +1,79 @@+import AppIntents+import AsterismCore+import Foundation+import SwiftUI++/// "What did I note today?" (`app-intents` Req 2).+///+/// The Today screen's noted section for the civil day at the moment the intent+/// runs, without the blank notes (Q3, Q7). Above five notes the spoken dialog+/// gives the count and the first five, and the shown list has them all+/// (Req 2.4).+struct NotesFromTodayIntent: AppIntent {+    static var title: LocalizedStringResource { "Notes from Today" }++    static var description: IntentDescription? {+        IntentDescription("Reads the notes you made on chapters today.")+    }++    static var supportedModes: IntentModes { .background }++    static var authenticationPolicy: IntentAuthenticationPolicy {+        .requiresLocalDeviceAuthentication+    }++    @Dependency private var model: AppLibraryModel++    @MainActor+    func perform() async throws -> some IntentResult & ProvidesDialog & ShowsSnippetView {+        let calendar = model.intentCalendar+        let currentDay = CivilDay(Date(), calendar: calendar)+        guard let notes = try await IntentOutcome.read(+            model.intentBroker, intent: "notes from today",+            { library in+                IntentAnswers.notesToday(+                    try await library.todayPresentation(calendar: calendar),+                    currentDay: currentDay, calendar: calendar)+            })+        else {+            let sentence = IntentOutcome.unavailableSentence+            return .result(+                dialog: IntentDialog(stringLiteral: sentence),+                view: IntentMessageSnippet(text: sentence))+        }++        let dialog = IntentAnswers.dialog(for: notes)+        IntentLog.note(+            "notes from today: \(notes.count) notes",+            content: notes.map { "\($0.title): \($0.note)" }.joined(separator: "; "))+        return .result(+            dialog: IntentDialog(full: "\(dialog.full)", supporting: "\(dialog.supporting)"),+            view: NotesSnippet(notes: notes, summary: dialog.supporting))+    }+}++/// The shown list: every note, however many (Req 2.4).+private struct NotesSnippet: View {+    let notes: [NoteAnswer]+    let summary: String++    var body: some View {+        VStack(alignment: .leading, spacing: 10) {+            if notes.isEmpty {+                Text(summary)+            } else {+                ForEach(notes, id: \.entryID) { note in+                    VStack(alignment: .leading, spacing: 2) {+                        Text(note.title).font(.headline)+                        if let chapterLine = note.chapterLine {+                            Text(chapterLine).font(.subheadline).foregroundStyle(.secondary)+                        }+                        Text(note.note)+                    }+                }+            }+        }+        .padding()+        .frame(maxWidth: .infinity, alignment: .leading)+    }+}
Asterism/Asterism/Intents/OpenTargetFlow.swift Added +110 / -0
diff --git a/Asterism/Asterism/Intents/OpenTargetFlow.swift b/Asterism/Asterism/Intents/OpenTargetFlow.swiftnew file mode 100644index 00000000..84c11ed9--- /dev/null+++ b/Asterism/Asterism/Intents/OpenTargetFlow.swift@@ -0,0 +1,110 @@+import AsterismCore+import Foundation++/// The open intents' decisions, as a plain type (`app-intents` Req 4).+///+/// Checks the target, respects an edit in progress, leaves a route for the+/// window and brings the app forward where the system allows it. The window+/// applies the route when its library is ready (`AppNavigation.takeIntentRoute`),+/// and drops it if the reader has moved since (Q42).+@MainActor+struct OpenTargetFlow {+    struct Outcome: Equatable {+        let dialog: String+        /// Whether the app was brought to the foreground.+        let foregrounded: Bool+    }++    static let notFoundSentence = "I couldn't find that work."+    static let editingSentence = "You're editing something in Asterism."++    let broker: IntentLibraryBroker+    let navigation: AppNavigation+    /// `systemContext.currentMode.canContinueInForeground`.+    let canContinueInForeground: Bool+    /// `continueInForeground(alwaysConfirm: false)`.+    let continueInForeground: @MainActor () async throws -> Void++    func run(_ target: IntentRoute.Target) async throws -> Outcome {+        let name: String+        var check = ""+        switch target {+        case .today:+            name = "Today"+        case .work(let id):+            guard let checked = try await checkedName(of: id) else {+                IntentLog.note("open work: not found")+                return Outcome(dialog: Self.notFoundSentence, foregrounded: false)+            }+            name = checked.name+            check = ", check \(checked.check)"+        }++        // Req 4.5: an edit in progress keeps its screen and its draft.+        if navigation.isEditing {+            let foregrounded = try await foreground(target, route: nil)+            IntentLog.note("open \(Self.describe(target)): edit in progress, foregrounded=\(foregrounded)")+            return Outcome(dialog: Self.editingSentence, foregrounded: foregrounded)+        }++        let route = IntentRoute(target: target, revision: navigation.revision)+        navigation.intentRoute = route+        let foregrounded = try await foreground(target, route: route)+        IntentLog.note(+            "open \(Self.describe(target)): routed\(check), foregrounded=\(foregrounded)", content: name)+        return Outcome(dialog: "Opening \(name).", foregrounded: foregrounded)+    }++    /// The work's name as the answer says it, and how it was checked — or nil+    /// where the library no longer holds it.+    ///+    /// Req 4.4 (Q32): a work that is gone is answered from the background, so+    /// the check comes before any foregrounding. Req 4.6, Q22: where the+    /// library is opening or unavailable the check is skipped and the work is+    /// "that work" — the app shows its own opening or unavailable state, and the+    /// window drops the route if the work turns out to be unknown. Opening is+    /// asked first, because a step started then would wait for the whole open+    /// before the app could come forward.+    private func checkedName(of id: UUID) async throws -> (name: String, check: String)? {+        if broker.isLibraryOpening { return ("that work", "skipped, library opening") }+        do {+            let found = try await broker.withLibrary(writes: false) {+                try await $0.workSummaries(ids: [id])+            }+            return found.first.map { ("“\($0.displayTitle)”", "found") }+        } catch {+            switch IntentOutcome.classify(error) {+            case .unavailable:+                return ("that work", "skipped, library unavailable")+            case .rethrow(let underlying):+                IntentLog.failure("open work: failed: \(IntentLog.describe(underlying))")+                throw underlying+            }+        }+    }++    /// Brings the app forward where the system allows it; where it does not,+    /// the answer stands and the route waits for the reader's next activation.+    ///+    /// A foregrounding that throws takes back the route this run left, if it is+    /// still the one waiting, so a failed open cannot move the window later.+    private func foreground(_ target: IntentRoute.Target, route: IntentRoute?) async throws -> Bool {+        guard canContinueInForeground else { return false }+        do {+            try await continueInForeground()+        } catch {+            if let route, navigation.intentRoute == route { navigation.intentRoute = nil }+            IntentLog.failure(+                "open \(Self.describe(target)): foregrounding failed: \(IntentLog.describe(error))")+            throw error+        }+        return true+    }++    private static func describe(_ target: IntentRoute.Target) -> String {+        switch target {+        case .today: "today"+        case .work: "work"+        }+    }+}
Asterism/Asterism/Intents/OpenTodayIntent.swift Added +33 / -0
diff --git a/Asterism/Asterism/Intents/OpenTodayIntent.swift b/Asterism/Asterism/Intents/OpenTodayIntent.swiftnew file mode 100644index 00000000..44aaa254--- /dev/null+++ b/Asterism/Asterism/Intents/OpenTodayIntent.swift@@ -0,0 +1,33 @@+import AppIntents+import Foundation++/// "Open Today" (`app-intents` Req 4.1).+///+/// Background plus dynamic foreground (Q32), so the flow decides whether the+/// app comes forward: not over an edit the reader has open without saying so.+struct OpenTodayIntent: AppIntent {+    static var title: LocalizedStringResource { "Open Today" }++    static var description: IntentDescription? {+        IntentDescription("Opens Asterism on the Today screen.")+    }++    static var supportedModes: IntentModes { [.background, .foreground(.dynamic)] }++    static var authenticationPolicy: IntentAuthenticationPolicy {+        .requiresLocalDeviceAuthentication+    }++    @Dependency private var model: AppLibraryModel+    @Dependency private var navigation: AppNavigation++    @MainActor+    func perform() async throws -> some IntentResult & ProvidesDialog {+        let outcome = try await OpenTargetFlow(+            broker: model.intentBroker, navigation: navigation,+            canContinueInForeground: systemContext.currentMode.canContinueInForeground,+            continueInForeground: { try await continueInForeground(alwaysConfirm: false) }+        ).run(.today)+        return .result(dialog: IntentDialog(stringLiteral: outcome.dialog))+    }+}
Asterism/Asterism/Intents/OpenWorkIntent.swift Added +43 / -0
diff --git a/Asterism/Asterism/Intents/OpenWorkIntent.swift b/Asterism/Asterism/Intents/OpenWorkIntent.swiftnew file mode 100644index 00000000..69776739--- /dev/null+++ b/Asterism/Asterism/Intents/OpenWorkIntent.swift@@ -0,0 +1,43 @@+import AppIntents+import Foundation++/// "Open <work>" (`app-intents` Reqs 4.2–4.4).+///+/// The work is resolved through `WorkEntityQuery` — by a spoken name for the+/// reading and catching-up works, and through Find Works for the rest (Req 5.4,+/// Q23) — and checked again here, because a saved value can outlive its work+/// (Req 4.4). Background plus dynamic foreground (Q32): a work that is gone+/// must be answered without bringing the app forward.+struct OpenWorkIntent: AppIntent {+    static var title: LocalizedStringResource { "Open Work" }++    static var description: IntentDescription? {+        IntentDescription("Opens a work in Asterism.")+    }++    static var supportedModes: IntentModes { [.background, .foreground(.dynamic)] }++    static var authenticationPolicy: IntentAuthenticationPolicy {+        .requiresLocalDeviceAuthentication+    }++    @Parameter(title: "Work")+    var work: WorkEntity++    static var parameterSummary: some ParameterSummary {+        Summary("Open \(\.$work)")+    }++    @Dependency private var model: AppLibraryModel+    @Dependency private var navigation: AppNavigation++    @MainActor+    func perform() async throws -> some IntentResult & ProvidesDialog {+        let outcome = try await OpenTargetFlow(+            broker: model.intentBroker, navigation: navigation,+            canContinueInForeground: systemContext.currentMode.canContinueInForeground,+            continueInForeground: { try await continueInForeground(alwaysConfirm: false) }+        ).run(.work(work.id))+        return .result(dialog: IntentDialog(stringLiteral: outcome.dialog))+    }+}
Asterism/Asterism/Intents/ShortcutParameters.swift Added +44 / -0
diff --git a/Asterism/Asterism/Intents/ShortcutParameters.swift b/Asterism/Asterism/Intents/ShortcutParameters.swiftnew file mode 100644index 00000000..6b47333d--- /dev/null+++ b/Asterism/Asterism/Intents/ShortcutParameters.swift@@ -0,0 +1,44 @@+import AppIntents+import AsterismCore+import Foundation++/// Keeps the "open work" phrase's spoken names in step with the library+/// (`app-intents` Req 5.4, Q23).+///+/// The phrase takes a name for every reading and catching-up work, which the+/// system learns from `WorkEntityQuery.suggestedEntities()` when the app asks+/// it to — `updateAppShortcutParameters()`. That call re-reads the library+/// through the broker, so it is made only when the id-to-title set actually+/// changed, not on every publication.+@MainActor+final class ShortcutParameters {+    /// The process's one instance, updating the real App Shortcuts.+    static let shared = ShortcutParameters(update: {+        AsterismShortcuts.updateAppShortcutParameters()+    })++    /// The reading statuses whose works the phrase takes a spoken name for —+    /// the set registered here and the set `WorkEntityQuery` suggests.+    nonisolated static let spokenNameStatuses: Set<ReadingStatus> = [.reading, .catchingUp]++    private let update: @MainActor () -> Void+    /// The last set registered; nil before the first refresh, so the first+    /// always registers.+    private var registered: [UUID: String]?++    init(update: @escaping @MainActor () -> Void) {+        self.update = update+    }++    /// Registers the reading and catching-up works among `works`, if they+    /// differ from the last set registered.+    func refresh(works: [WorkSnapshot]) {+        var titles: [UUID: String] = [:]+        for work in works where Self.spokenNameStatuses.contains(work.readingStatus) {+            titles[work.id] = work.displayTitle+        }+        guard titles != registered else { return }+        registered = titles+        update()+    }+}
Asterism/Asterism/Intents/WorkEntity.swift Added +187 / -0
diff --git a/Asterism/Asterism/Intents/WorkEntity.swift b/Asterism/Asterism/Intents/WorkEntity.swiftnew file mode 100644index 00000000..732474ee--- /dev/null+++ b/Asterism/Asterism/Intents/WorkEntity.swift@@ -0,0 +1,187 @@+import AppIntents+import AsterismCore+import Foundation++/// A work as a Shortcuts value (`app-intents` Req 5.1).+///+/// Carries the id and what Siri and Shortcuts show: the display title and the+/// two statuses as the app names them. It is a snapshot of the moment it was+/// found; an action that takes one resolves it again through+/// `WorkEntityQuery.entities(for:)`, so a renamed work shows its current title+/// and a removed one is not found (Req 5.3).+struct WorkEntity: AppEntity {+    static var typeDisplayRepresentation: TypeDisplayRepresentation {+        TypeDisplayRepresentation(name: "Work", numericFormat: "\(placeholder: .int) works")+    }++    static var defaultQuery: WorkEntityQuery { WorkEntityQuery() }++    let id: UUID++    /// A `@Property` rather than a plain field, because the Find Works action+    /// compares against it (Req 5.2, Q40).+    @Property(title: "Title")+    var title: String++    @Property(title: "Reading Status")+    var readingStatus: String++    @Property(title: "Work Status")+    var workStatus: String++    init(_ summary: WorkSummary) {+        id = summary.id+        title = summary.displayTitle+        readingStatus = ReadingStatusPresentation.name(summary.readingStatus)+        workStatus = WorkStatusPresentation.name(summary.workStatus)+    }++    var displayRepresentation: DisplayRepresentation {+        DisplayRepresentation(+            title: "\(title)", subtitle: "\(readingStatus) · \(workStatus)")+    }+}++/// Thrown by a query while the device is locked, so nothing from the library+/// is spoken or shown before an unlock (Req 6.3, Q34).+nonisolated struct IntentLockedError: Error, CustomLocalizedStringResourceConvertible {+    var localizedStringResource: LocalizedStringResource {+        "Unlock your device to use your Asterism library."+    }+}++/// What the work queries do, as a plain type the unit bundle can drive+/// without the App Intents runtime.+///+/// Every read goes through the broker, so a query waits while the library+/// opens and reports an unavailable one as unavailable rather than as "no+/// works" (Req 4.6, 6.2). On iOS it refuses first while protected data is+/// unavailable (Q34).+@MainActor+struct WorkEntityLookup {+    let broker: IntentLibraryBroker+    var isProtectedDataAvailable: @MainActor () -> Bool = { AppLifecycle.isProtectedDataAvailable }++    func works(ids: [UUID]) async throws -> [WorkEntity] {+        try await read { try await $0.workSummaries(ids: ids) }+    }++    /// Every work whose title contains `text` (Req 5.2).+    func works(titleContaining text: String) async throws -> [WorkEntity] {+        try await read { try await $0.workSummaries(titleContaining: text) }+    }++    /// The works whose title contains every text (`.and`) or any of them+    /// (`.or`), in title order — the Find Works action's comparators. One+    /// broker step, so a cold library is opened once for all of them.+    func works(+        titleContaining texts: [String], all: Bool, limit: Int?+    ) async throws -> [WorkEntity] {+        let texts = texts.isEmpty ? [""] : texts+        var found = try await read { library in+            var sets: [[WorkSummary]] = []+            for text in texts {+                sets.append(try await library.workSummaries(titleContaining: text))+            }+            return Self.combine(sets, all: all)+        }+        if let limit, found.count > limit { found = Array(found.prefix(limit)) }+        return found+    }++    /// The reading and catching-up works (Req 5.4).+    func suggestedWorks() async throws -> [WorkEntity] {+        let statuses = ShortcutParameters.spokenNameStatuses+        return try await read { try await $0.workSummaries(readingStatuses: statuses) }+    }++    private func read(+        _ step: @escaping @Sendable (any LibraryProviding) async throws -> [WorkSummary]+    ) async throws -> [WorkEntity] {+        guard isProtectedDataAvailable() else { throw IntentLockedError() }+        return try await broker.withLibrary(writes: false, step).map(WorkEntity.init)+    }++    /// Several title-ordered answers as one, still in title order.+    private nonisolated static func combine(_ sets: [[WorkSummary]], all: Bool) -> [WorkSummary] {+        guard let first = sets.first else { return [] }+        if all {+            let rest = sets.dropFirst().map { Set($0.map(\.id)) }+            return first.filter { summary in rest.allSatisfy { $0.contains(summary.id) } }+        }+        var byID: [UUID: WorkSummary] = [:]+        for summary in sets.joined() { byID[summary.id] = summary }+        return byID.values.sorted(by: WorkSummary.titleOrder)+    }+}++/// Resolves and finds works for Siri and Shortcuts (Reqs 5.2–5.4).+///+/// `EntityStringQuery` gives Siri a spoken or typed name to resolve;+/// `EntityPropertyQuery` gives Shortcuts its Find Works action (Q40). Both+/// answer from the same read.+struct WorkEntityQuery: EntityStringQuery, EntityPropertyQuery {+    typealias ComparatorMappingType = String++    @Dependency private var model: AppLibraryModel++    /// The unit bundle's seam: a lookup over a broker and a protected-data+    /// answer of its own. Nil in production, which reads the registered model.+    private let injectedLookup: (@MainActor @Sendable () -> WorkEntityLookup)?++    init() {+        injectedLookup = nil+    }++    init(lookup: @escaping @MainActor @Sendable () -> WorkEntityLookup) {+        injectedLookup = lookup+    }++    // Stored, in the builder's own form: the App Intents metadata processor+    // reads these declarations at build time and accepts nothing else.+    static let properties = QueryProperties {+        Property(\WorkEntity.$title) {+            ContainsComparator { $0 }+        }+    }++    static let sortingOptions = SortingOptions {+        SortableBy(\WorkEntity.$title)+    }++    static var findIntentDescription: IntentDescription? {+        IntentDescription("Finds works in your Asterism library by title.")+    }++    func entities(for identifiers: [UUID]) async throws -> [WorkEntity] {+        try await lookup().works(ids: identifiers)+    }++    func entities(matching string: String) async throws -> [WorkEntity] {+        try await lookup().works(titleContaining: string)+    }++    func entities(+        matching comparators: [String], mode: ComparatorMode,+        sortedBy: [EntityQuerySort<WorkEntity>], limit: Int?+    ) async throws -> [WorkEntity] {+        // Title is the one sortable property, and the reads already answer in+        // title order; a descending sort reverses it before the limit.+        let descending = sortedBy.first?.order == .descending+        let found = try await lookup().works(+            titleContaining: comparators, all: mode == .and, limit: descending ? nil : limit)+        guard descending else { return found }+        let reversed = Array(found.reversed())+        return limit.map { Array(reversed.prefix($0)) } ?? reversed+    }++    func suggestedEntities() async throws -> [WorkEntity] {+        try await lookup().suggestedWorks()+    }++    @MainActor+    private func lookup() -> WorkEntityLookup {+        if let injectedLookup { return injectedLookup() }+        return WorkEntityLookup(broker: model.intentBroker)+    }+}
Asterism/Asterism/Layout/AppNavigation.swift Modified +167 / -23
diff --git a/Asterism/Asterism/Layout/AppNavigation.swift b/Asterism/Asterism/Layout/AppNavigation.swiftindex 202f72a3..e36f2a94 100644--- a/Asterism/Asterism/Layout/AppNavigation.swift+++ b/Asterism/Asterism/Layout/AppNavigation.swift@@ -101,14 +101,20 @@ nonisolated enum TodaySelection: Equatable, Sendable { final class AppNavigation {     // MARK: - Tab and selection -    var selectedTab: AppTab = .today+    var selectedTab: AppTab = .today {+        didSet { if selectedTab != oldValue { noteReaderNavigation() } }+    } -    var selectedTodayEntryID: UUID?+    var selectedTodayEntryID: UUID? {+        didSet { if selectedTodayEntryID != oldValue { noteReaderNavigation() } }+    }      /// Which day Today is showing (Q32). Not view state: it has to survive a     /// push and a tab switch, and `.current` is Req 3.7's "the day that had been     /// current" with no clock bookkeeping at all.-    var todaySelection: TodaySelection = .current+    var todaySelection: TodaySelection = .current {+        didSet { if todaySelection != oldValue { noteReaderNavigation() } }+    }      /// Today's own typed route stack (Q38).     ///@@ -117,12 +123,16 @@ final class AppNavigation {     /// but a stack of its own, so Back from a pushed work returns to the     /// selected day. **Never restored** (Q42): a pushed work on Today is a place     /// the reader passes through, not one they are left on.-    var todayPath: [WorksRoute] = []+    var todayPath: [WorksRoute] = [] {+        didSet { if todayPath != oldValue { noteReaderNavigation() } }+    }      /// The entry the Works *list* opened — the unattached-notes group's route.     /// Its destination is declared at the stack root, which is where it is     /// tapped.-    var selectedWorksEntryID: UUID?+    var selectedWorksEntryID: UUID? {+        didSet { if selectedWorksEntryID != oldValue { noteReaderNavigation() } }+    }      /// The Works tab's stack, as a typed path (Decision 7 of     /// `specs/series-and-related-works`).@@ -143,7 +153,9 @@ final class AppNavigation {     /// whole pane (Q42, Q57 of `ipad-and-mac-layouts`). Because the path lives     /// here rather than in either tree, Req 2.3's layout crossing preserves a     /// series screen exactly as it preserves a work.-    var worksPath: [WorksRoute] = []+    var worksPath: [WorksRoute] = [] {+        didSet { if worksPath != oldValue { noteReaderNavigation() } }+    }      /// Which work the Works tab is *about* — the last `.work` on the path.     ///@@ -707,7 +719,8 @@ final class AppNavigation {         guard newCurrentDay > previousCurrentDay else { return }         guard case .day(let selected) = todaySelection else { return }         guard previousCurrentDay <= selected, selected <= newCurrentDay else { return }-        todaySelection = .current+        // The clock moved the selection, not the reader (`app-intents` Q42).+        withoutRevision { todaySelection = .current }     }      // MARK: - Today: the routes@@ -734,12 +747,16 @@ final class AppNavigation {     /// visible works — a series or creator screen pushed over it is the reader's     /// own depth, not a row in this list (`pruneRestoredSelection`'s rule).     func pruneTodaySelection(visibleEntryIDs: Set<UUID>, visibleWorkIDs: Set<UUID>) {-        if let entryID = selectedTodayEntryID, !visibleEntryIDs.contains(entryID) {-            selectedTodayEntryID = nil+        // The library moved under the selection, not the reader (`app-intents`+        // Q42).+        withoutRevision {+            if let entryID = selectedTodayEntryID, !visibleEntryIDs.contains(entryID) {+                selectedTodayEntryID = nil+            }+            guard case .work(let workID) = todayPath.first, !visibleWorkIDs.contains(workID)+            else { return }+            todayPath = []         }-        guard case .work(let workID) = todayPath.first, !visibleWorkIDs.contains(workID)-        else { return }-        todayPath = []     }      // MARK: - Relaunch restore (Req 7.2, 4.9)@@ -767,7 +784,20 @@ final class AppNavigation {     /// restore names the work and the stack starts there. This is the one writer     /// of `worksPath` outside the routes above.     func restoreWorksSelection(_ workID: UUID?) {-        worksPath = workID.map { [.work($0)] } ?? []+        withoutRevision { worksPath = workID.map { [.work($0)] } ?? [] }+    }++    /// Puts the Mac back on the tab, Today entry and work it was left on+    /// (Req 7.2) — `ContentView`'s three stored values, written here so that a+    /// restore is not counted as the reader moving (`app-intents` Q42). An+    /// intent route set before the window appeared has to survive the restore+    /// and then be applied over it.+    func restoreSelection(tab: AppTab?, todayEntryID: UUID?, workID: UUID?) {+        withoutRevision {+            selectedTab = tab ?? .today+            selectedTodayEntryID = todayEntryID+            restoreWorksSelection(workID)+        }     }      /// Applies that rule to the two ids the Mac restores.@@ -785,17 +815,131 @@ final class AppNavigation {         entryResolves: (UUID) -> Bool,         workResolves: (UUID) -> Bool     ) {-        selectedTodayEntryID = Self.restoredID(-            selectedTodayEntryID,-            resolves: selectedTodayEntryID.map(entryResolves) ?? false,-            hasEverImported: hasEverImported)-        guard let restoredWorkID = selectedWorkID else { return }-        let kept = Self.restoredID(-            restoredWorkID,-            resolves: workResolves(restoredWorkID),-            hasEverImported: hasEverImported)-        if kept == nil { restoreWorksSelection(nil) }+        withoutRevision {+            selectedTodayEntryID = Self.restoredID(+                selectedTodayEntryID,+                resolves: selectedTodayEntryID.map(entryResolves) ?? false,+                hasEverImported: hasEverImported)+            guard let restoredWorkID = selectedWorkID else { return }+            let kept = Self.restoredID(+                restoredWorkID,+                resolves: workResolves(restoredWorkID),+                hasEverImported: hasEverImported)+            if kept == nil { restoreWorksSelection(nil) }+        }+    }++    // MARK: - Intent routes (`app-intents` Reqs 4.1–4.6)++    /// Where an open intent asked the window to go, waiting for the library to+    /// be ready (Q29). Held in memory only: a route belongs to the one request+    /// that set it.+    var intentRoute: IntentRoute?++    /// Moves on every reader navigation — a tab change, a push or a pop on+    /// either stack, a selection — so a deferred route can tell whether the+    /// reader went somewhere of their own after it was set (Q42). A tab+    /// comparison would miss a push on the same tab.+    ///+    /// Counted from the stored properties' `didSet`s rather than from the route+    /// methods, because the stacks' own back gestures and the lists' selections+    /// write those properties through bindings and never call a method here.+    /// What the app writes on its own — the Mac's restore, the prunes that+    /// follow a snapshot, a day change — goes through `withoutRevision`.+    private(set) var revision = 0++    /// Whether the writes in progress are the app's own rather than the+    /// reader's.+    @ObservationIgnored private var suppressesRevision = false++    private func noteReaderNavigation() {+        guard !suppressesRevision else { return }+        revision &+= 1     }++    private func withoutRevision(_ body: () -> Void) {+        let outer = suppressesRevision+        suppressesRevision = true+        defer { suppressesRevision = outer }+        body()+    }++    /// Screens holding a draft, and sheets presented outside this object, that+    /// have registered through `.intentEditSession(active:)` (Q30).+    private var editSessions: Set<UUID> = []++    /// Opens or closes one registered edit session. Idempotent both ways.+    func setEditSession(_ token: UUID, active: Bool) {+        if active {+            editSessions.insert(token)+        } else {+            editSessions.remove(token)+        }+    }++    /// Req 4.5's guard: whether an open intent must leave the window where it+    /// is (Q37).+    ///+    /// **Fails safe.** Every sheet this object presents counts, whether or not+    /// it holds a draft, and so does every screen or local sheet that has+    /// registered a session. A harmless sheet blocks too, and the reader is told+    /// an edit is in progress; a draft view added later without a registration+    /// is still covered whenever it is presented from here. Pushed screens are+    /// navigation, not drafts, and do not count.+    var isEditing: Bool {+        !editSessions.isEmpty+            || showingNewWork+            || showingMoveTo != nil+            || showingSettings+            || showingTeachingForEntryID != nil+            || showingTeachingForHostname != nil+            || resolvingDuplicateSet != nil+            || mergingWorkID != nil+            || presentedAnnouncement != nil+    }++    /// Applies the waiting intent route, or drops it (Q42). The caller runs+    /// this only once the library is ready — when `state` becomes `.ready`,+    /// after the Mac's restore, and when a route arrives at a ready window.+    ///+    /// Taken once either way. Dropped when the reader navigated after it was+    /// set, when an edit is in progress, and — for a work — when the library+    /// does not hold that work: an intent that found the library unavailable+    /// set its route without checking (Req 4.6), and an empty detail is not a+    /// destination. The titles map arrives as a parameter for+    /// `route(toResolve:in:)`'s reason: this object holds no reference to the+    /// library it navigates.+    func takeIntentRoute(workTitlesByID: [UUID: String]) {+        guard let route = intentRoute else { return }+        intentRoute = nil+        guard route.revision == revision, !isEditing else { return }+        switch route.target {+        case .today:+            selectedTab = .today+            todaySelection = .current+            todayPath = []+            // The entry a noted row opened is Today's pane too, and the reader+            // asked for the Today screen itself.+            selectedTodayEntryID = nil+        case .work(let workID):+            guard workTitlesByID[workID] != nil else { return }+            showWork(workID)+        }+    }+}++// MARK: - The intent route++/// Where an open intent sends the window, and the navigation revision it was+/// set at (`app-intents` Q29, Q42).+nonisolated struct IntentRoute: Equatable, Sendable {+    enum Target: Equatable, Sendable {+        case today+        case work(UUID)+    }++    let target: Target+    let revision: Int }  // MARK: - The Works stack
Asterism/Asterism/Layout/IntentEditSession.swift Added +62 / -0
diff --git a/Asterism/Asterism/Layout/IntentEditSession.swift b/Asterism/Asterism/Layout/IntentEditSession.swiftnew file mode 100644index 00000000..4de25e43--- /dev/null+++ b/Asterism/Asterism/Layout/IntentEditSession.swift@@ -0,0 +1,62 @@+import SwiftUI++extension EnvironmentValues {+    /// The navigation object edit sessions register with (`app-intents` Q30).+    ///+    /// On the `\.siteNames` precedent: written once at the top of each scene, so+    /// every screen, everything pushed from it and every sheet it presents can+    /// register without a signature change. Nil — a preview, a test host — means+    /// nothing registers, which is the right answer where no intent can arrive.+    @Entry var intentEditSessions: AppNavigation?+}++extension View {+    /// Tells the open intents that this view holds a draft, or presents a+    /// sheet, while `active` is true (Req 4.5, Q37).+    ///+    /// An open intent that finds any session registered leaves the window where+    /// it is and says an edit is in progress, so the draft — the only copy of+    /// itself — is never navigated away from. The session ends when `active`+    /// goes false or the view is gone for good.+    func intentEditSession(active: Bool) -> some View {+        modifier(IntentEditSessionModifier(active: active))+    }+}++private struct IntentEditSessionModifier: ViewModifier {+    let active: Bool++    @Environment(\.intentEditSessions) private var navigation+    /// This view's registration, for the life of the view's state.+    @State private var registration = IntentEditRegistration()++    func body(content: Content) -> some View {+        content.onChange(of: active, initial: true) { _, isActive in+            registration.set(active: isActive, in: navigation)+        }+    }+}++/// One view's edit session, closed when the view's state is released.+///+/// **Not closed on `onDisappear`.** A tab the reader switches away from+/// disappears with its pushed editor still standing — `SwiftUI.Tab` keeps the+/// unselected tab's content alive — and ending the session there would let an+/// open-work intent replace the Works stack under a draft that is still open.+/// The state going away is the moment the draft does.+@MainActor+private final class IntentEditRegistration {+    private let token = UUID()+    private weak var navigation: AppNavigation?++    func set(active: Bool, in navigation: AppNavigation?) {+        if let navigation { self.navigation = navigation }+        self.navigation?.setEditSession(token, active: active)+    }++    /// `isolated`, for `MemoryPressureSource`'s reason: the navigation object+    /// is main-actor state, and a `nonisolated` deinit could not touch it.+    isolated deinit {+        navigation?.setEditSession(token, active: false)+    }+}
Asterism/Asterism/Support/AppLifecycle.swift Modified +29 / -0
diff --git a/Asterism/Asterism/Support/AppLifecycle.swift b/Asterism/Asterism/Support/AppLifecycle.swiftindex 84aa2c92..896c58cc 100644--- a/Asterism/Asterism/Support/AppLifecycle.swift+++ b/Asterism/Asterism/Support/AppLifecycle.swift@@ -629,4 +629,33 @@ enum AppLifecycle {         return UIApplication.shared.applicationState == .active         #endif     }++    /// Whether a window is connected right now (`app-intents`, design Risks).+    ///+    /// Logged on every cold intent step, because the design assumes a+    /// background intent launch runs `App.init` with no scene and that+    /// assumption is verified from the log, not argued. On the Mac a window+    /// counts only while it is visible: a closed `Window` scene leaves its+    /// `NSWindow` object behind.+    static var hasConnectedScene: Bool {+        #if os(macOS)+        return NSApplication.shared.windows.contains(where: \.isVisible)+        #else+        return !UIApplication.shared.connectedScenes.isEmpty+        #endif+    }++    /// Whether the device's protected data can be read — false on a locked+    /// phone (`app-intents` Req 6.3, Q34).+    ///+    /// The entity queries ask this before answering, because the intents'+    /// `authenticationPolicy` does not cover the queries Siri calls to resolve+    /// a work. The Mac has no such state, so it is always true there.+    static var isProtectedDataAvailable: Bool {+        #if os(macOS)+        return true+        #else+        return UIApplication.shared.isProtectedDataAvailable+        #endif+    } }
Asterism/Asterism/Support/PlatformModifiers.swift Modified +3 / -0
diff --git a/Asterism/Asterism/Support/PlatformModifiers.swift b/Asterism/Asterism/Support/PlatformModifiers.swiftindex c3b1fe15..cbf2db3c 100644--- a/Asterism/Asterism/Support/PlatformModifiers.swift+++ b/Asterism/Asterism/Support/PlatformModifiers.swift@@ -723,6 +723,9 @@ private struct DocumentExporter: ViewModifier {      func body(content: Content) -> some View {         content+            // `app-intents` Q37: the share sheet is a presented modal, and the+            // guard counts every one.+            .intentEditSession(active: isPresented)             .sheet(isPresented: $isPresented, onDismiss: startGraceWait) {                 if let file {                     // The presentation number is captured **by value** here, at
Asterism/Asterism/ViewModels/AppLibraryModel.swift Modified +102 / -6
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex c1ddb7ae..e39151fd 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -39,7 +39,11 @@ public final class AppLibraryModel {         case unavailable(message: String)     } -    public private(set) var state: State = .loading+    public private(set) var state: State = .loading {+        // `app-intents` Req 6.2: an intent that arrived while the library was+        // opening waits for it, and this is the moment it stops waiting.+        didSet { if state != .loading { resumeLibraryReadyWaiters() } }+    }     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: [])@@ -555,6 +559,12 @@ public final class AppLibraryModel {         }         launch.end(.exportPassWait)         assert(backgroundSession == nil, "a pre-empted pass releases its own session")+        // `app-intents` Decision 4: an intent step in flight finishes before the+        // library it is using is released, and before the mirrored container is+        // built beside a cold session it may hold. Awaited, never cancelled — a+        // step is one repository call bounded by the lease wait. No new step is+        // admitted meanwhile: the broker reads `bootstrapInFlight`, set above.+        await intentBroker.drain()         await teardownRepository()         if let startupFailureMessage {             state = .unavailable(message: startupFailureMessage)@@ -1341,6 +1351,12 @@ public final class AppLibraryModel {             // on the cycle that publishes the arrival — without the identity             // having changed, which it never does.             thumbnailLoader.update(generation: snapshotGeneration)+            // `app-intents` Req 5.4: the open-work phrase's spoken names follow+            // the works snapshot. Here and not in `publishToday()`, whose+            // schedule lists only the reading works with release days: that+            // would register part of the set and then, at the launch tail's+            // refresh a moment later, all of it.+            ShortcutParameters.shared.refresh(works: works.works)             return snapshotGeneration         } catch {             Self.logger.error("Snapshot refresh failed: \(String(describing: error), privacy: .public)")@@ -1929,6 +1945,10 @@ public final class AppLibraryModel {     /// process is alive to do it.     static let openingLibraryReason = "the library is opening" +    /// The sentence a pass is told while an intent step holds the library+    /// (`app-intents` Decision 4).+    static let intentHoldsLibraryReason = "an intent holds the library"+     /// How both openers construct the app's mirrored container.     ///     /// `.production` everywhere but a test. `.private` construction always fails@@ -1975,7 +1995,7 @@ public final class AppLibraryModel {     var hasOpenForegroundRepository: Bool { repository != nil }      /// The one configuration failure reported with a sentence of its own.-    private struct UnresolvableConfiguration: Error {+    struct UnresolvableConfiguration: Error {         let message: String     } @@ -2079,6 +2099,10 @@ public final class AppLibraryModel {         // First, because it has to dominate: that open's own monitor exports the         // same changes, and the process is alive to do it.         if bootstrapInFlight { return .skipped(.unavailable(Self.openingLibraryReason)) }+        // `app-intents` Decision 4: the reader is waiting on the intent, and the+        // pass re-runs at its next grant. On a cold launch this is also what+        // keeps the pass's mirrored container from opening beside the step's.+        if intentBroker.isBusy { return .skipped(.unavailable(Self.intentHoldsLibraryReason)) }         // The foreground has already diagnosed it; a pass adds nothing (Req 1.9).         if case .unavailable(let message) = state { return .skipped(.unavailable(message)) }         if state == .ready, let repository {@@ -2115,6 +2139,21 @@ public final class AppLibraryModel {             statusURL: configuration.syncStatusURL)         monitor.start() +        // `app-intents` Decision 4: the open holds the broker's turn until the+        // session is published, so a step that arrives meanwhile queues and then+        // borrows it, rather than finding no session and opening a second+        // container beside this one. `acquire()` checked `isBusy` with no+        // suspension since, so this takes the turn at once.+        return await intentBroker.holdingTurn {+            await openColdSession(configuration, monitor: monitor)+        }+    }++    /// The open-and-publish half of `acquireColdSession()`, run holding the+    /// broker's turn.+    private func openColdSession(+        _ configuration: LibraryConfiguration, monitor: SyncMonitor+    ) async -> BackgroundExportAcquisition {         let opened: LibraryRepository         do {             opened = try await LibraryRepository.openForApp(@@ -2154,10 +2193,21 @@ public final class AppLibraryModel {     /// reported (Req 1.5).     public func release() async {         backgroundPassHoldsLibrary = false-        guard let session = backgroundSession else { return }-        backgroundSession = nil-        session.monitor.stop()-        await session.repository.shutdown()+        guard backgroundSession != nil else { return }+        // A cold intent step may be running on this session (`app-intents`+        // Decision 4); it finishes before the container goes. Holding the+        // broker's turn rather than draining it: a drain resumes as a later job,+        // and a step admitted in that gap could borrow the session just before+        // it is cleared. Holding the turn through the shutdown also keeps a+        // later step from opening a cold container beside the closing one.+        // Re-read inside the turn, because a second `release()` can have taken+        // the session.+        await intentBroker.holdingTurn {+            guard let session = backgroundSession else { return }+            backgroundSession = nil+            session.monitor.stop()+            await session.repository.shutdown()+        }     }      /// Whether the cancellation a pass is seeing came from the reader opening@@ -2212,6 +2262,52 @@ public final class AppLibraryModel {         }     } +    // MARK: - App Intents (`app-intents` Decision 4)++    /// The broker every intent reaches the library through. One per model, so+    /// the instance `AsterismApp` registers for the intents is the one+    /// `bootstrap()` drains.+    @ObservationIgnored private(set) lazy var intentBroker = IntentLibraryBroker(model: self)++    /// Callers of `libraryReady()` waiting for `state` to leave `.loading`.+    @ObservationIgnored private var libraryReadyWaiters: [CheckedContinuation<Void, Never>] = []++    /// Resumes once `state` is `.ready` or `.unavailable` — at once if it+    /// already is (Req 6.2's "opening").+    func libraryReady() async {+        guard state == .loading else { return }+        await withCheckedContinuation { libraryReadyWaiters.append($0) }+    }++    private func resumeLibraryReadyWaiters() {+        let waiters = libraryReadyWaiters+        libraryReadyWaiters = []+        for waiter in waiters { waiter.resume() }+    }++    /// The resident repository, while the library is ready. `repository` itself+    /// stays private: the broker is its one reader outside this class.+    var intentResidentLibrary: (any LibraryProviding)? {+        state == .ready ? repository : nil+    }++    /// The configuration a cold intent step opens, resolved the way both of+    /// this model's openers resolve it — or the reason it will not resolve,+    /// which the broker logs and reports as unavailable.+    var intentConfiguration: Result<LibraryConfiguration, UnresolvableConfiguration> {+        configurationForPass()+    }++    /// What follows a resident write: the New Work form's `onMutation`, and+    /// nothing more — no reconcile is scheduled (Req 3.9).+    func intentStepDidWrite() async {+        await refreshDiagnosesAndSnapshots()+    }++    /// The calendar an intent builds its Today answer with — the same source+    /// the Today screen reads, read at the moment the intent runs (Req 1.4).+    var intentCalendar: Calendar { calendarSource() }+     // MARK: - Sync visibility (Req 8)      /// The live monitor, or nil when this configuration cannot mirror.
Asterism/Asterism/ViewModels/EntryDetailModel.swift Modified +9 / -0
diff --git a/Asterism/Asterism/ViewModels/EntryDetailModel.swift b/Asterism/Asterism/ViewModels/EntryDetailModel.swiftindex b31b8e67..503ad705 100644--- a/Asterism/Asterism/ViewModels/EntryDetailModel.swift+++ b/Asterism/Asterism/ViewModels/EntryDetailModel.swift@@ -103,6 +103,15 @@ public final class EntryDetailModel {     public var draftNote: String = ""     public var draftRating: Rating? +    /// Whether the draft differs from what this screen loaded (`app-intents`+    /// Req 4.5). The screen has no edit mode — its fields are always live — so+    /// this is what tells an open intent that navigating away would discard+    /// the reader's only copy of an edit. Nothing loaded means nothing to lose.+    public var hasUnsavedChanges: Bool {+        guard let entry else { return false }+        return draftNote != entry.note || draftRating != entry.rating+    }+     /// Which entry this model is *actually* about.     ///     /// Readable rather than private so the screen can name itself for the wide
Asterism/Asterism/Views/CreatorDetailView.swift Modified +3 / -0
diff --git a/Asterism/Asterism/Views/CreatorDetailView.swift b/Asterism/Asterism/Views/CreatorDetailView.swiftindex ce538ff6..a41c80ef 100644--- a/Asterism/Asterism/Views/CreatorDetailView.swift+++ b/Asterism/Asterism/Views/CreatorDetailView.swift@@ -156,6 +156,9 @@ struct CreatorDetailView: View {         // series screen has the same shape and the same gap; it is accepted         // rather than papered over on one screen.         .hidesBackButton(model.isEditing)+        // `app-intents` Req 4.5: edit mode holds the reader's place against an+        // open intent.+        .intentEditSession(active: model.isEditing)         .screenSky(showsSky)         .accessibilityIdentifier("creator-detail")         .toolbar { toolbarItems }
Asterism/Asterism/Views/EntryDetailView.swift Modified +6 / -0
diff --git a/Asterism/Asterism/Views/EntryDetailView.swift b/Asterism/Asterism/Views/EntryDetailView.swiftindex 95df87f5..42864222 100644--- a/Asterism/Asterism/Views/EntryDetailView.swift+++ b/Asterism/Asterism/Views/EntryDetailView.swift@@ -107,6 +107,12 @@ struct EntryDetailView: View {         // reaches the screen. In the wide tree the window owns it (Req 3.1).         .screenSky(showsSky)         .task { await model.load() }+        // `app-intents` Req 4.5: this screen has no edit mode — the note and+        // the rating are always editable — so an unsaved change is what holds+        // the reader's place against an open intent, with the two sheets it+        // raises.+        .intentEditSession(+            active: model.hasUnsavedChanges || showingComposedTeaching || showingReparse)     }      @ViewBuilder
Asterism/Asterism/Views/MaintenanceViews.swift Modified +2 / -0
diff --git a/Asterism/Asterism/Views/MaintenanceViews.swift b/Asterism/Asterism/Views/MaintenanceViews.swiftindex b27c7e4e..474b554a 100644--- a/Asterism/Asterism/Views/MaintenanceViews.swift+++ b/Asterism/Asterism/Views/MaintenanceViews.swift@@ -47,6 +47,8 @@ struct URLIdentityReviewView: View {         .sheet(item: $recalculationModel) { recalcModel in             RecalculateView(model: recalcModel)         }+        // `app-intents` Q37: a presented sheet holds the reader's place.+        .intentEditSession(active: recalculationModel != nil)     }      @ViewBuilder
Asterism/Asterism/Views/SeriesDetailView.swift Modified +3 / -0
diff --git a/Asterism/Asterism/Views/SeriesDetailView.swift b/Asterism/Asterism/Views/SeriesDetailView.swiftindex 298427b9..a07b92ef 100644--- a/Asterism/Asterism/Views/SeriesDetailView.swift+++ b/Asterism/Asterism/Views/SeriesDetailView.swift@@ -136,6 +136,9 @@ struct SeriesDetailView: View {         // is not one of them — it would leave the screen from a mode whose X         // means "leave the mode".         .hidesBackButton(model.isEditing)+        // `app-intents` Req 4.5: edit mode and the member picker hold the+        // reader's place against an open intent.+        .intentEditSession(active: model.isEditing || isPresentingPicker)         .screenSky(showsSky)         .accessibilityIdentifier("series-detail")         .toolbar { toolbarItems }
Asterism/Asterism/Views/StatsView.swift Modified +2 / -0
diff --git a/Asterism/Asterism/Views/StatsView.swift b/Asterism/Asterism/Views/StatsView.swiftindex 0b8bd191..87b66a23 100644--- a/Asterism/Asterism/Views/StatsView.swift+++ b/Asterism/Asterism/Views/StatsView.swift@@ -298,6 +298,8 @@ struct StatsView: View {         // `ViewThatFits` builds every candidate to measure it, and a         // presentation declared inside one of them is declared more than once.         .sheet(isPresented: $isPickingDate) { periodPicker(bounds) }+        // `app-intents` Q37: a presented sheet holds the reader's place.+        .intentEditSession(active: isPickingDate)     }      /// Q11's three-segment capsule, on the style guide's §7 recipe — literally
Asterism/Asterism/Views/WorkDetailView.swift Modified +15 / -0
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex c7aff4c4..6d47d727 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -163,6 +163,18 @@ struct WorkDetailView: View {         "Remove from \(hostname)"     } +    /// Whether a sheet of this screen's own is up (`app-intents` Q37). Most of+    /// them are raised only in edit mode, which counts already; they are listed+    /// anyway, so the guard does not rest on that staying true.+    private var presentsSheet: Bool {+        reviewModel != nil || activeMergeModel != nil || reviewingIdentityHostname != nil+            || showingURLReteach || isPresentingLinkPicker || pendingLinkTarget != nil+            || editingLink != nil || isNamingSeries || isPresentingCreatorPicker+            || editingCredit != nil || expandedEditCharacterID != nil+            || expandedEditPlaceID != nil || isPresentingCoverPicker || isShowingCoverViewer+            || model.isPresentingCoverCandidates || model.pendingCrop != nil+    }+     var body: some View {         Group {             switch model.state {@@ -188,6 +200,9 @@ struct WorkDetailView: View {         // chevron is not one of them — it would leave the screen from a mode         // whose X means "leave the mode".         .hidesBackButton(model.isEditing)+        // `app-intents` Req 4.5: edit mode, and every sheet this screen raises,+        // hold the reader's place against an open intent.+        .intentEditSession(active: model.isEditing || presentsSheet)         .screenSky(showsSky)         .task { await model.load() }         // A committed deletion takes the screen with it — there is nothing left
Asterism/AsterismTests/AddPageToReadFlowTests.swift Added +327 / -0
diff --git a/Asterism/AsterismTests/AddPageToReadFlowTests.swift b/Asterism/AsterismTests/AddPageToReadFlowTests.swiftnew file mode 100644index 00000000..e719c48c--- /dev/null+++ b/Asterism/AsterismTests/AddPageToReadFlowTests.swift@@ -0,0 +1,327 @@+import AsterismCore+import Foundation+import Testing+@testable import Asterism++/// Task 15 of `app-intents`: the add intent's decisions, without the App+/// Intents runtime (Reqs 3.1–3.9).+///+/// The flow is handed its prompts, its title fetcher and a broker over a mock+/// library, so every path is driven here and "writes nothing" is a count of+/// `createWorkUnlessPresent` calls — the flow's only write.+@Suite("AddPageToReadFlow")+@MainActor+struct AddPageToReadFlowTests {++    // MARK: - Fixtures++    private struct Cancelled: Error {}++    /// What the prompts and the fetcher were asked, in order, and what they+    /// answer.+    private final class Script {+        var events: [String] = []+        var url = URL(string: "https://example.com/story")!+        var fetchedTitle: String?+        var choice: AddPageToReadFlow.TitleChoice = .useFetched+        var titles: [String] = []+        var cancelAt: String?+        /// Held for the test's length: the broker keeps its model `unowned`.+        var model: AppLibraryModel?++        func prompts() -> AddPageToReadFlow.Prompts {+            AddPageToReadFlow.Prompts(+                askForURL: {+                    self.events.append("askForURL")+                    if self.cancelAt == "askForURL" { throw Cancelled() }+                    return self.url+                },+                chooseTitle: { fetched in+                    self.events.append("chooseTitle(\(fetched))")+                    if self.cancelAt == "chooseTitle" { throw Cancelled() }+                    return self.choice+                },+                askForTitle: {+                    self.events.append("askForTitle")+                    if self.cancelAt == "askForTitle" { throw Cancelled() }+                    return self.titles.isEmpty ? "" : self.titles.removeFirst()+                })+        }+    }++    /// Records the fetches from wherever the flow runs them.+    private final class FetchLog: @unchecked Sendable {+        private let lock = NSLock()+        private var stored: [URL] = []+        var urls: [URL] { lock.withLock { stored } }+        func append(_ url: URL) { lock.withLock { stored.append(url) } }+    }++    private static let summary = WorkSummary(+        id: UUID(), displayTitle: "Existing Serial", readingStatus: .reading, workStatus: .ongoing)++    private func flow(+        _ mock: MockLibraryProvider, _ script: Script, fetches: FetchLog = FetchLog()+    ) -> AddPageToReadFlow {+        let model = AppLibraryModel(readyRepository: mock)+        script.model = model+        let fetched = script.fetchedTitle+        return AddPageToReadFlow(+            broker: model.intentBroker,+            fetchTitle: { url in+                fetches.append(url)+                return fetched+            },+            prompts: script.prompts())+    }++    private func created(_ title: String) -> CreateWorkOutcome {+        .created(+            TestFixtures.makeWork(displayTitle: title, workStatus: .ongoing, readingStatus: .toRead))+    }++    // MARK: - The page (Reqs 3.6, 3.8)++    @Test("No URL asks for one, and the page it answers is the one added")+    func missingURLAsksForOne() async throws {+        let mock = MockLibraryProvider()+        mock.createWorkUnlessPresentResult = .success(created("Asked Serial"))+        let script = Script()+        script.url = URL(string: "https://example.com/asked")!++        let outcome = try await flow(mock, script).run(url: nil, title: "Asked Serial")++        #expect(script.events == ["askForURL"])+        #expect(mock.pageMatchURLs == ["https://example.com/asked"])+        #expect(mock.createWorkUnlessPresentDrafts.map(\.hostname) == ["https://example.com/asked"])+        #expect(outcome.created?.displayTitle == "Asked Serial")+    }++    @Test("A page that is not HTTP or HTTPS is refused with a reason, before anything is read or written")+    func nonHTTPSchemeRefuses() async throws {+        let mock = MockLibraryProvider()+        let script = Script()+        let fetches = FetchLog()++        let outcome = try await flow(mock, script, fetches: fetches)+            .run(url: URL(string: "ftp://example.com/story")!, title: nil)++        #expect(outcome.created == nil)+        #expect(outcome.dialog == AddPageToReadFlow.notAWebPageSentence)+        #expect(mock.pageMatchURLs.isEmpty)+        #expect(mock.createWorkUnlessPresentDrafts.isEmpty)+        #expect(fetches.urls.isEmpty)+        #expect(script.events.isEmpty)+    }++    // MARK: - Already in the library (Req 3.5)++    @Test("A page already held by a work names the work and its reading status, and asks nothing")+    func preCheckWorkMatchAnswers() async throws {+        let mock = MockLibraryProvider()+        mock.pageMatchResult = .success(.work(Self.summary))+        let script = Script()+        let fetches = FetchLog()++        let outcome = try await flow(mock, script, fetches: fetches)+            .run(url: script.url, title: nil)++        #expect(outcome.created == nil)+        #expect(outcome.dialog == "“Existing Serial” is already in your library, as Reading.")+        #expect(mock.createWorkUnlessPresentDrafts.isEmpty)+        #expect(fetches.urls.isEmpty)+        #expect(script.events.isEmpty)+    }++    @Test("A page captured only as a chapter with no work says so")+    func preCheckUnattachedEntryAnswers() async throws {+        let mock = MockLibraryProvider()+        mock.pageMatchResult = .success(.unattachedEntry(captureTitle: "Chapter 3"))+        let script = Script()++        let outcome = try await flow(mock, script).run(url: script.url, title: "Anything")++        #expect(outcome.created == nil)+        #expect(outcome.dialog == AddPageToReadFlow.unattachedChapterSentence)+        #expect(mock.createWorkUnlessPresentDrafts.isEmpty)+    }++    // MARK: - The title (Reqs 3.1–3.3, Decision 3)++    @Test("A supplied title is used as given, with no fetch and no prompt")+    func suppliedTitleSkipsFetchAndPrompts() async throws {+        let mock = MockLibraryProvider()+        mock.createWorkUnlessPresentResult = .success(created("Supplied"))+        let script = Script()+        let fetches = FetchLog()++        _ = try await flow(mock, script, fetches: fetches).run(url: script.url, title: "  Supplied  ")++        #expect(fetches.urls.isEmpty)+        #expect(script.events.isEmpty)+        let draft = try #require(mock.createWorkUnlessPresentDrafts.first)+        #expect(draft.displayTitle == "Supplied")+        #expect(draft.hostname == script.url.absoluteString)+        #expect(draft.readingStatus == .toRead)+    }++    @Test("A blank supplied title counts as not supplied (Q41)")+    func blankSuppliedTitleCountsAsUnset() async throws {+        let mock = MockLibraryProvider()+        mock.createWorkUnlessPresentResult = .success(created("Fetched Title"))+        let script = Script()+        script.fetchedTitle = "Fetched Title"+        let fetches = FetchLog()++        _ = try await flow(mock, script, fetches: fetches).run(url: script.url, title: "   ")++        #expect(fetches.urls == [script.url])+        #expect(script.events == ["chooseTitle(Fetched Title)"])+        #expect(mock.createWorkUnlessPresentDrafts.map(\.displayTitle) == ["Fetched Title"])+    }++    @Test("A fetched title is offered, and using it asks for nothing more")+    func fetchedTitleOffersTheChoice() async throws {+        let mock = MockLibraryProvider()+        mock.createWorkUnlessPresentResult = .success(created("Fetched Title"))+        let script = Script()+        script.fetchedTitle = "  Fetched Title "+        script.choice = .useFetched++        _ = try await flow(mock, script).run(url: script.url, title: nil)++        #expect(script.events == ["chooseTitle(Fetched Title)"])+        #expect(mock.createWorkUnlessPresentDrafts.map(\.displayTitle) == ["Fetched Title"])+    }++    @Test("Change title asks for one, and asks again while the answer is blank")+    func changeTitleAsksAndReasksWhileBlank() async throws {+        let mock = MockLibraryProvider()+        mock.createWorkUnlessPresentResult = .success(created("Spoken Title"))+        let script = Script()+        script.fetchedTitle = "Landing Page"+        script.choice = .change+        script.titles = ["", "   ", "Spoken Title"]++        _ = try await flow(mock, script).run(url: script.url, title: nil)++        #expect(script.events == [+            "chooseTitle(Landing Page)", "askForTitle", "askForTitle", "askForTitle",+        ])+        #expect(mock.createWorkUnlessPresentDrafts.map(\.displayTitle) == ["Spoken Title"])+    }++    @Test("With no fetched title, or a blank one, it asks for a title without offering a choice")+    func noFetchedTitleAsksDirectly() async throws {+        for fetched in [nil, "  "] as [String?] {+            let mock = MockLibraryProvider()+            mock.createWorkUnlessPresentResult = .success(created("Typed"))+            let script = Script()+            script.fetchedTitle = fetched+            script.titles = ["Typed"]++            _ = try await flow(mock, script).run(url: script.url, title: nil)++            #expect(script.events == ["askForTitle"], "fetched \(String(describing: fetched))")+            #expect(mock.createWorkUnlessPresentDrafts.map(\.displayTitle) == ["Typed"])+        }+    }++    // MARK: - Cancel (Req 3.7)++    @Test("Cancelling at any prompt writes nothing")+    func cancelAtAnyPromptWritesNothing() async throws {+        let cases: [(prompt: String, url: URL?, fetched: String?, choice: AddPageToReadFlow.TitleChoice)] = [+            ("askForURL", nil, "Title", .useFetched),+            ("chooseTitle", URL(string: "https://example.com/a")!, "Title", .useFetched),+            ("askForTitle", URL(string: "https://example.com/b")!, "Title", .change),+            ("askForTitle", URL(string: "https://example.com/c")!, nil, .useFetched),+        ]+        for (prompt, url, fetched, choice) in cases {+            let mock = MockLibraryProvider()+            mock.createWorkUnlessPresentResult = .success(created("Never"))+            let script = Script()+            script.fetchedTitle = fetched+            script.choice = choice+            script.cancelAt = prompt++            await #expect(throws: Cancelled.self, "cancel at \(prompt)") {+                _ = try await flow(mock, script).run(url: url, title: nil)+            }+            #expect(mock.createWorkUnlessPresentDrafts.isEmpty, "cancel at \(prompt)")+        }+    }++    // MARK: - The write (Reqs 3.4–3.6, 3.9)++    @Test("A match committed before the write answers as the first check would, and creates nothing")+    func presentAtCommitAnswersLikeThePreCheck() async throws {+        let mock = MockLibraryProvider()+        mock.createWorkUnlessPresentResult = .success(.present(.work(Self.summary)))+        let script = Script()++        let outcome = try await flow(mock, script).run(url: script.url, title: "Late Title")++        #expect(outcome.created == nil)+        #expect(outcome.dialog == "“Existing Serial” is already in your library, as Reading.")+    }++    @Test("A created work is returned, and the write is declared, so the snapshots refresh (Q48)")+    func createdReturnsTheWork() async throws {+        let mock = MockLibraryProvider()+        mock.createWorkUnlessPresentResult = .success(created("New Serial"))+        let script = Script()++        let outcome = try await flow(mock, script).run(url: script.url, title: "New Serial")++        let work = try #require(outcome.created)+        #expect(work.displayTitle == "New Serial")+        #expect(work.readingStatus == .toRead)+        #expect(outcome.dialog == "Added “New Serial” as To read.")+        // The refresh runs after the answer, outside the broker's turn.+        await script.model?.intentBroker.pendingWriteRefresh?.value+        #expect(mock.refreshDiagnosticsCallCount == 1, "a resident write refreshes, as the New Work form does")+    }++    @Test("A match committed before the write wrote nothing, so nothing is refreshed")+    func presentAtCommitRefreshesNothing() async throws {+        let mock = MockLibraryProvider()+        mock.createWorkUnlessPresentResult = .success(.present(.work(Self.summary)))+        let script = Script()++        _ = try await flow(mock, script).run(url: script.url, title: "Late Title")++        #expect(mock.createWorkUnlessPresentDrafts.count == 1, "the write was attempted")+        #expect(script.model?.intentBroker.pendingWriteRefresh == nil)+        #expect(mock.refreshDiagnosticsCallCount == 0)+    }++    @Test("A refusal from the library is answered with its reason, and nothing is created")+    func libraryRefusalAnswersWithTheReason() async throws {+        let mock = MockLibraryProvider()+        let refusal = LibraryRepositoryError.invalidInput(+            operation: "checking the site or URL", reason: "That address is on a.example, not b.example.")+        mock.createWorkUnlessPresentResult = .failure(refusal)+        let script = Script()++        let outcome = try await flow(mock, script).run(url: script.url, title: "Refused")++        #expect(outcome.created == nil)+        #expect(outcome.dialog.contains("That address is on a.example, not b.example."))+    }++    @Test("An unavailable library is answered as unavailable, and nothing is asked or written")+    func unavailableLibraryAnswers() async throws {+        let model = AppLibraryModel(startupFailureMessage: "No App Group")+        await model.bootstrap()+        let script = Script()+        let flow = AddPageToReadFlow(+            broker: model.intentBroker, fetchTitle: { _ in "Title" }, prompts: script.prompts())++        let outcome = try await flow.run(url: script.url, title: nil)++        #expect(outcome.created == nil)+        #expect(outcome.dialog == IntentOutcome.unavailableSentence)+        #expect(script.events.isEmpty)+    }+}
Asterism/AsterismTests/AppNavigationIntentRouteTests.swift Added +251 / -0
diff --git a/Asterism/AsterismTests/AppNavigationIntentRouteTests.swift b/Asterism/AsterismTests/AppNavigationIntentRouteTests.swiftnew file mode 100644index 00000000..10a06d9d--- /dev/null+++ b/Asterism/AsterismTests/AppNavigationIntentRouteTests.swift@@ -0,0 +1,251 @@+import AsterismCore+import Foundation+import Testing++@testable import Asterism++/// Task 10 of `app-intents`: the route an open intent leaves for the window,+/// and the edit guard that stops it (Reqs 4.1, 4.2, 4.5, 4.6; Q37, Q42).+///+/// Beside `AppNavigationTests` rather than inside it, for the reason+/// `AppLibraryModelBackgroundExportTests` stands beside its model's suite: that+/// file is already 1,600 lines, and everything under test is still+/// `AppNavigation`'s.+@Suite("AppNavigation intent routes and the edit guard")+@MainActor+struct AppNavigationIntentRouteTests {++    /// A day relative to today, in the current calendar.+    private static func day(_ offset: Int) -> CivilDay {+        CivilDay(.now, calendar: .current).adding(days: offset, calendar: .current)+    }++    // MARK: - The edit guard (Req 4.5, Q37)++    @Test("A fresh navigation is not editing")+    func freshNavigationIsNotEditing() {+        #expect(!AppNavigation().isEditing)+    }++    /// Every sheet `AppNavigation` drives, one at a time. The guard fails safe:+    /// a sheet that holds no draft blocks as surely as one that does.+    ///+    /// One test with a case per flag rather than `@Test(arguments:)`: a+    /// parameterised case in this bundle can compile and then never run+    /// (`docs/agent-notes/testing.md`), and this one did.+    @Test("Every sheet AppNavigation presents counts as editing")+    func everySheetFlagCountsAsEditing() {+        let presentations: [(String, (AppNavigation) -> Void)] = [+            ("showingNewWork", { $0.showingNewWork = true }),+            ("showingMoveTo", { $0.showingMoveTo = UUID() }),+            ("showingSettings", { $0.showingSettings = true }),+            ("showingTeachingForEntryID", { $0.showingTeachingForEntryID = UUID() }),+            ("showingTeachingForHostname", {+                $0.showingTeachingForHostname = PendingReteach(hostname: "example.com")+            }),+            ("resolvingDuplicateSet", {+                $0.resolvingDuplicateSet = PresentedDuplicateSet(+                    key: DuplicateSetKey(recordType: .work, memberIDs: [UUID(), UUID()]))+            }),+            ("mergingWorkID", { $0.mergingWorkID = PresentedWork(id: UUID()) }),+            ("presentedAnnouncement", { $0.presentedAnnouncement = .gettingStarted }),+        ]++        for (flag, present) in presentations {+            let navigation = AppNavigation()+            present(navigation)+            #expect(navigation.isEditing, "\(flag) is a presented sheet")+        }+    }++    @Test("A pushed screen is navigation, not editing")+    func navigationStateIsNotEditing() {+        let navigation = AppNavigation()+        navigation.showWork(UUID())+        navigation.showingDiagnostics = true+        navigation.selectedTodayEntryID = UUID()++        #expect(!navigation.isEditing)+    }++    @Test("A registered edit session counts as editing until it ends")+    func editSessionsCountAsEditing() {+        let navigation = AppNavigation()+        let first = UUID()+        let second = UUID()++        navigation.setEditSession(first, active: true)+        navigation.setEditSession(second, active: true)+        #expect(navigation.isEditing)++        navigation.setEditSession(first, active: false)+        #expect(navigation.isEditing, "one session is still open")++        navigation.setEditSession(second, active: false)+        #expect(!navigation.isEditing)++        navigation.setEditSession(second, active: false)+        #expect(!navigation.isEditing, "ending a session twice is harmless")+    }++    // MARK: - Taking the route (Reqs 4.1, 4.2, 4.6; Q42)++    @Test("A .today route shows the current day's Today screen with nothing pushed")+    func todayRouteShowsToday() {+        let navigation = AppNavigation()+        navigation.showWork(UUID())+        navigation.showWork(UUID(), on: .today)+        navigation.selectedTodayEntryID = UUID()+        navigation.todaySelection = .day(Self.day(-3))+        navigation.intentRoute = IntentRoute(target: .today, revision: navigation.revision)++        navigation.takeIntentRoute(workTitlesByID: [:])++        #expect(navigation.selectedTab == .today)+        #expect(navigation.todaySelection == .current)+        #expect(navigation.todayPath.isEmpty)+        #expect(navigation.selectedTodayEntryID == nil)+        #expect(navigation.intentRoute == nil, "a route is taken once")+    }++    @Test("A .work route opens the work as the Works stack's whole content")+    func workRouteShowsTheWork() {+        let navigation = AppNavigation()+        let workID = UUID()+        navigation.showSeriesList()+        navigation.selectedTab = .stats+        navigation.intentRoute = IntentRoute(target: .work(workID), revision: navigation.revision)++        navigation.takeIntentRoute(workTitlesByID: [workID: "The Work"])++        #expect(navigation.selectedTab == .works)+        #expect(navigation.worksPath == [.work(workID)])+        #expect(navigation.intentRoute == nil)+    }++    @Test("Every reader navigation moves the revision")+    func readerNavigationMovesTheRevision() {+        let navigation = AppNavigation()+        var last = navigation.revision++        func moved(_ what: String, _ change: () -> Void) {+            change()+            #expect(navigation.revision != last, "\(what) is a reader navigation")+            last = navigation.revision+        }++        moved("a tab change") { navigation.selectedTab = .works }+        moved("a push") { navigation.showWork(UUID()) }+        moved("a pop") { navigation.popWorksRoute() }+        moved("a Today selection") { navigation.selectedTodayEntryID = UUID() }+        moved("a Today push") { navigation.showWork(UUID(), on: .today) }+        moved("a day selection") {+            navigation.todaySelection = .day(Self.day(-3))+        }+        moved("a Works entry") { navigation.showWorksEntry(UUID()) }+        moved("a binding write to the path") { navigation.worksPath = [.seriesList] }+    }++    @Test("Writing the value a property already holds is not a navigation")+    func sameValueWritesDoNotMoveTheRevision() {+        let navigation = AppNavigation()+        let before = navigation.revision++        navigation.selectedTab = navigation.selectedTab+        navigation.worksPath = navigation.worksPath++        #expect(navigation.revision == before)+    }++    @Test("A route is dropped when the reader navigated after it was set")+    func movedRevisionDropsTheRoute() {+        let navigation = AppNavigation()+        let workID = UUID()+        navigation.intentRoute = IntentRoute(target: .work(workID), revision: navigation.revision)+        // The reader went somewhere of their own before the library was ready.+        navigation.showSeriesList()+        let placeTheReaderChose = navigation.worksPath++        navigation.takeIntentRoute(workTitlesByID: [workID: "The Work"])++        #expect(navigation.worksPath == placeTheReaderChose)+        #expect(navigation.intentRoute == nil, "a dropped route is not kept for later")+    }++    @Test("A route is dropped when an edit is in progress, and the draft's screen stays")+    func editingDropsTheRoute() {+        let navigation = AppNavigation()+        let open = UUID()+        navigation.showWork(open)+        navigation.intentRoute = IntentRoute(target: .today, revision: navigation.revision)+        navigation.setEditSession(UUID(), active: true)++        navigation.takeIntentRoute(workTitlesByID: [:])++        #expect(navigation.selectedTab == .works)+        #expect(navigation.worksPath == [.work(open)])+        #expect(navigation.intentRoute == nil)+    }++    @Test("A .work route whose work the library does not hold is dropped silently")+    func unknownWorkDropsTheRoute() {+        let navigation = AppNavigation()+        navigation.intentRoute = IntentRoute(target: .work(UUID()), revision: navigation.revision)++        navigation.takeIntentRoute(workTitlesByID: [UUID(): "Another Work"])++        #expect(navigation.selectedTab == .today)+        #expect(navigation.worksPath.isEmpty, "no empty detail is opened")+        #expect(navigation.intentRoute == nil)+    }++    @Test("Taking with no route does nothing")+    func noRouteIsANoOp() {+        let navigation = AppNavigation()+        navigation.showWork(UUID())+        let before = navigation.worksPath++        navigation.takeIntentRoute(workTitlesByID: [:])++        #expect(navigation.worksPath == before)+        #expect(navigation.selectedTab == .works)+    }++    // MARK: - The Mac's relaunch restore (Req 7.2 of `ipad-and-mac-layouts`)++    /// The restore writes the tab and the stack the Mac was left on, and it is+    /// not the reader moving: a route set before the window appeared must+    /// survive it and then win over it.+    @Test("The Mac restore neither drops the route nor overwrites it")+    func routeIsAppliedAfterTheRestore() {+        let navigation = AppNavigation()+        let routed = UUID()+        let restored = UUID()+        navigation.intentRoute = IntentRoute(target: .work(routed), revision: navigation.revision)++        navigation.restoreSelection(tab: .stats, todayEntryID: UUID(), workID: restored)+        #expect(navigation.selectedTab == .stats, "the restore itself still happens")+        #expect(navigation.worksPath == [.work(restored)])++        navigation.takeIntentRoute(workTitlesByID: [routed: "Routed", restored: "Restored"])++        #expect(navigation.selectedTab == .works)+        #expect(navigation.worksPath == [.work(routed)])+    }++    @Test("The prunes that follow a snapshot are not reader navigation either")+    func prunesDoNotMoveTheRevision() {+        let navigation = AppNavigation()+        navigation.restoreSelection(tab: .today, todayEntryID: UUID(), workID: UUID())+        navigation.showWork(UUID(), on: .today)+        let before = navigation.revision++        navigation.pruneRestoredSelection(+            hasEverImported: true, entryResolves: { _ in false }, workResolves: { _ in false })+        navigation.pruneTodaySelection(visibleEntryIDs: [], visibleWorkIDs: [])+        navigation.normalizeTodaySelection(+            previousCurrentDay: Self.day(0), newCurrentDay: Self.day(1))++        #expect(navigation.revision == before)+    }+}
Asterism/AsterismTests/EntryDetailModelTests.swift Modified +19 / -0
diff --git a/Asterism/AsterismTests/EntryDetailModelTests.swift b/Asterism/AsterismTests/EntryDetailModelTests.swiftindex 8c5de0ca..b9774c88 100644--- a/Asterism/AsterismTests/EntryDetailModelTests.swift+++ b/Asterism/AsterismTests/EntryDetailModelTests.swift@@ -103,6 +103,25 @@ struct EntryDetailModelTests {         #expect(mock.entryTeachingDetailCallCount == 1)     } +    /// `app-intents` Req 4.5: the entry screen has no edit mode, so an open+    /// intent asks this whether navigating away would lose an edit.+    @Test("hasUnsavedChanges follows the draft against the loaded snapshot")+    @MainActor func hasUnsavedChangesFollowsTheDraft() async {+        let (model, _, _) = makeSUT()+        #expect(!model.hasUnsavedChanges, "nothing loaded, nothing to lose")++        await model.load()+        #expect(!model.hasUnsavedChanges)++        model.draftNote = "a new thought"+        #expect(model.hasUnsavedChanges)+        model.draftNote = "original note"+        #expect(!model.hasUnsavedChanges, "typing back to the saved text is not a change")++        model.draftRating = .down+        #expect(model.hasUnsavedChanges)+    }+     @Test("Update commits note and rating changes")     @MainActor func updateCommits() async {         let (model, mock, tracker) = makeSUT()
Asterism/AsterismTests/Helpers/MirroredContainerGate.swift Added +36 / -0
diff --git a/Asterism/AsterismTests/Helpers/MirroredContainerGate.swift b/Asterism/AsterismTests/Helpers/MirroredContainerGate.swiftnew file mode 100644index 00000000..b34161e8--- /dev/null+++ b/Asterism/AsterismTests/Helpers/MirroredContainerGate.swift@@ -0,0 +1,36 @@+import AsterismCore+import Foundation++/// Counts the mirrored containers a bootstrap or a background-export pass+/// constructs, and can hold that construction open, so a test can act while+/// an open is in flight (`AppLibraryModelBackgroundExportTests`' shape).+///+/// The hold is bounded, so a gate nobody opens fails a test rather than+/// hanging the suite. Shared because the broker suite and the open-intent+/// suite both need a library that is still opening.+final class MirroredContainerGate: @unchecked Sendable {+    private let lock = NSLock()+    private let semaphore = DispatchSemaphore(value: 0)+    private var holds: Bool+    private var count = 0++    init(holds: Bool) { self.holds = holds }++    var constructionCount: Int { lock.withLock { count } }++    func release() {+        lock.withLock { holds = false }+        semaphore.signal()+    }++    var hooks: MirroringOpenHooks {+        MirroringOpenHooks(makeMirroredContainer: { storeURL, _ in+            if self.lock.withLock({ self.holds }) {+                _ = self.semaphore.wait(timeout: .now() + 5)+            }+            let container = try LibraryRepository.openContainer(at: storeURL)+            self.lock.withLock { self.count += 1 }+            return container+        })+    }+}
Asterism/AsterismTests/Helpers/MockLibraryProvider.swift Modified +34 / -0
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex ac462c39..762f3415 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -1192,4 +1192,38 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable {         callLog.append("linkTypeSuggestions")         return try linkTypeSuggestionsResult.get()     }++    // MARK: - App Intents (`app-intents`)++    /// The URLs `pageMatch` was asked about, in order, and its answer.+    var pageMatchURLs: [String] = []+    var pageMatchResult: Result<PageMatch?, Error> = .success(nil)++    func pageMatch(rawURL: String) async throws -> PageMatch? {+        pageMatchURLs.append(rawURL)+        callLog.append("pageMatch")+        return try pageMatchResult.get()+    }++    /// Every draft `createWorkUnlessPresent` was sent — the add intent's only+    /// write — and its answer.+    var createWorkUnlessPresentDrafts: [NewWorkDraft] = []+    var createWorkUnlessPresentResult: Result<CreateWorkOutcome, Error> = .failure(+        MockError.notConfigured)++    func createWorkUnlessPresent(_ draft: NewWorkDraft) async throws -> CreateWorkOutcome {+        createWorkUnlessPresentDrafts.append(draft)+        callLog.append("createWorkUnlessPresent")+        return try createWorkUnlessPresentResult.get()+    }++    /// The ids `workSummaries(ids:)` was asked for, and the works it knows.+    var workSummaryRequests: [[UUID]] = []+    var workSummariesByID: [UUID: WorkSummary] = [:]++    func workSummaries(ids: [UUID]) async throws -> [WorkSummary] {+        workSummaryRequests.append(ids)+        callLog.append("workSummaries")+        return ids.compactMap { workSummariesByID[$0] }+    } }
Asterism/AsterismTests/IntentLibraryBrokerTests.swift Added +486 / -0
diff --git a/Asterism/AsterismTests/IntentLibraryBrokerTests.swift b/Asterism/AsterismTests/IntentLibraryBrokerTests.swiftnew file mode 100644index 00000000..27e5b3a8--- /dev/null+++ b/Asterism/AsterismTests/IntentLibraryBrokerTests.swift@@ -0,0 +1,486 @@+import AsterismCore+import Foundation+import SwiftData+import Testing+@testable import Asterism++/// Task 8 of `app-intents`: the broker every intent reaches the library+/// through (Decision 4, Reqs 6.2, 6.4, 6.5).+///+/// A step runs on the resident repository when the app is ready, on a cold+/// `openForExtension` session for exactly one step when it is not, and never+/// while a bootstrap is opening the library. The cold arm is driven over a real+/// library in a temporary root, created by `openForApp` before the model under+/// test exists — which is what a scene-less intent launch finds on disk.+@Suite("IntentLibraryBroker", .serialized)+@MainActor+struct IntentLibraryBrokerTests {++    // MARK: - Fixtures++    /// A fictional container id; the identity lint forbids naming a real one.+    private static let fixtureContainerID = "iCloud.example.fixture"++    private func tempRoot() -> URL {+        FileManager.default.temporaryDirectory+            .appending(path: "asterism-intent-broker-\(UUID())")+    }++    private func configuration(mirroring: Bool, at root: URL) -> LibraryConfiguration {+        LibraryConfiguration(+            rootDirectory: root,+            cloudKitContainerID: mirroring ? Self.fixtureContainerID : nil)+    }++    /// Creates and certifies a library in `root`, then lets go of it, so the+    /// marker and the store are on disk and nothing holds them.+    private func createLibrary(at root: URL) async throws {+        let repository = try await LibraryRepository.openForApp(+            configuration(mirroring: false, at: root)).repository+        await repository.shutdown()+    }++    private func pendingMarkers(_ configuration: LibraryConfiguration) throws -> [String] {+        try ExportOwedMarker(directory: configuration.exportOwedURL).pending().map(\.name)+    }++    /// Ordered labels written from inside steps, which run off the main actor.+    private final class Recorder: @unchecked Sendable {+        private let lock = NSLock()+        private var stored: [String] = []+        var events: [String] { lock.withLock { stored } }+        func append(_ event: String) { lock.withLock { stored.append(event) } }+    }++    /// The shared helper, under the name this suite has always used.+    private typealias ContainerGate = MirroredContainerGate++    /// Bounded polling; the sleep is what hands the main actor to the task+    /// under test.+    private func waitUntil(+        _ what: String, timeout: TimeInterval = 15, _ condition: () -> Bool,+        sourceLocation: SourceLocation = #_sourceLocation+    ) async {+        let deadline = Date().addingTimeInterval(timeout)+        while Date() < deadline {+            if condition() { return }+            try? await Task.sleep(for: .milliseconds(2))+        }+        Issue.record("Timed out waiting for \(what)", sourceLocation: sourceLocation)+    }++    /// Runs a step that must be refused as unavailable, and reports whether+    /// the step body was ever entered.+    private func expectUnavailable(+        _ model: AppLibraryModel, sourceLocation: SourceLocation = #_sourceLocation+    ) async -> Bool {+        let entered = Recorder()+        do {+            _ = try await model.intentBroker.withLibrary(writes: false) { _ in entered.append("entered") }+            Issue.record("The step ran on a library that is unavailable", sourceLocation: sourceLocation)+        } catch {+            guard case .unavailable = error else {+                Issue.record("Expected .unavailable, got \(error)", sourceLocation: sourceLocation)+                return !entered.events.isEmpty+            }+            // What App Intents shows when a query or `perform` throws it.+            #expect(+                String(localized: error.localizedStringResource) == IntentOutcome.unavailableSentence,+                sourceLocation: sourceLocation)+        }+        return !entered.events.isEmpty+    }++    private nonisolated static func draft(_ title: String) -> NewWorkDraft {+        NewWorkDraft(+            displayTitle: title, hostname: "https://example.com/\(UUID())", readingStatus: .toRead)+    }++    // MARK: - The resident library++    @Test("A step on a ready model runs on the resident repository and refreshes nothing")+    func residentReadRunsOnTheResidentRepository() async throws {+        let mock = MockLibraryProvider()+        let model = AppLibraryModel(readyRepository: mock)++        let sameObject = try await model.intentBroker.withLibrary(writes: false) { library in+            (library as? MockLibraryProvider) === mock+        }++        #expect(sameObject)+        #expect(mock.refreshDiagnosticsCallCount == 0, "a read is not a mutation")+        #expect(mock.todayPresentationCallCount == 0)+        #expect(!model.intentBroker.isBusy)+    }++    @Test("A resident write refreshes the diagnoses and snapshots, as the New Work form does")+    func residentWriteRefreshes() async throws {+        let mock = MockLibraryProvider()+        let model = AppLibraryModel(readyRepository: mock)+        let generation = model.snapshotGeneration++        _ = try await model.intentBroker.withLibrary(writes: true) { _ in 1 }+        // Started after the answer and outside the turn, so it is awaited here.+        #expect(!model.intentBroker.isBusy, "the turn is not held for the refresh")+        await model.intentBroker.pendingWriteRefresh?.value++        #expect(mock.refreshDiagnosticsCallCount == 1)+        #expect(mock.todayPresentationCallCount == 1)+        #expect(model.snapshotGeneration == generation + 1)+    }++    @Test("A step whose answer says it wrote nothing refreshes nothing")+    func residentStepThatDidNotWriteDoesNotRefresh() async throws {+        let mock = MockLibraryProvider()+        let model = AppLibraryModel(readyRepository: mock)+        let generation = model.snapshotGeneration++        let answer = try await model.intentBroker.withLibrary(wroteIf: { $0 > 0 }) { _ in 0 }++        #expect(answer == 0)+        #expect(model.intentBroker.pendingWriteRefresh == nil)+        #expect(mock.refreshDiagnosticsCallCount == 0)+        #expect(model.snapshotGeneration == generation)+    }++    @Test("A step error that is not about availability reaches the caller as .failed")+    func stepErrorsPropagate() async throws {+        let model = AppLibraryModel(readyRepository: MockLibraryProvider())+        do {+            _ = try await model.intentBroker.withLibrary(writes: false) { _ -> Int in+                throw LibraryRepositoryError.invalidInput(operation: "test", reason: "refused")+            }+            Issue.record("the refusal was swallowed")+        } catch {+            guard case .failed(let underlying) = error else {+                Issue.record("Expected .failed, got \(error)")+                return+            }+            #expect(+                underlying as? LibraryRepositoryError+                    == .invalidInput(operation: "test", reason: "refused"))+        }+    }++    // MARK: - The cold session (Decision 4)++    @Test("A cold step opens a session of its own, and shuts it down after the step")+    func coldStepOpensAndShutsDown() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        try await createLibrary(at: root)+        let configuration = configuration(mirroring: false, at: root)+        let model = AppLibraryModel(configuration: configuration)++        let opened = try await model.intentBroker.withLibrary(writes: false) { library in+            library as? LibraryRepository+        }++        let repository = try #require(opened, "the cold step is handed a real repository")+        await #expect(throws: LibraryRepositoryError.self, "and it was shut down after the step") {+            _ = try await repository.works()+        }+        #expect(model.state == .loading, "the foreground's state never moves")+        #expect(!model.hasOpenForegroundRepository, "nothing is published into the foreground")+        #expect(try pendingMarkers(configuration).isEmpty, "a read owes no export")+        #expect(!model.intentBroker.isBusy)+    }++    @Test("A cold write leaves an ExportOwed marker, and the work is in the library")+    func coldWriteMarksExportOwed() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        try await createLibrary(at: root)+        let configuration = configuration(mirroring: false, at: root)+        let model = AppLibraryModel(configuration: configuration)++        let outcome = try await model.intentBroker.withLibrary(writes: true) { library in+            try await library.createWorkUnlessPresent(Self.draft("Cold Intent Work"))+        }++        guard case .created = outcome else {+            Issue.record("Expected a created work, got \(outcome)")+            return+        }+        #expect(try pendingMarkers(configuration).count == 1)+        let found = try await model.intentBroker.withLibrary(writes: false) { library in+            try await library.workSummaries(titleContaining: "Cold Intent")+        }+        #expect(found.map(\.displayTitle) == ["Cold Intent Work"])+        #expect(try pendingMarkers(configuration).count == 1, "the read after it owes nothing more")+    }++    @Test("A cold step on an empty root is unavailable, and creates no store")+    func coldStepNeverCreatesAStore() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        let configuration = configuration(mirroring: false, at: root)+        let model = AppLibraryModel(configuration: configuration)++        let entered = await expectUnavailable(model)++        #expect(!entered)+        #expect(!FileManager.default.fileExists(atPath: configuration.storeURL.path))+        #expect(!FileManager.default.fileExists(atPath: configuration.readinessMarkerURL.path))+    }++    @Test("A cold step over a store with no readiness marker is unavailable")+    func coldStepWithoutAMarkerIsUnavailable() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        try await createLibrary(at: root)+        let configuration = configuration(mirroring: false, at: root)+        try FileManager.default.removeItem(at: configuration.readinessMarkerURL)+        let model = AppLibraryModel(configuration: configuration)++        let entered = await expectUnavailable(model)++        #expect(!entered)+        #expect(!FileManager.default.fileExists(atPath: configuration.readinessMarkerURL.path),+                "an intent never re-marks a library")+    }++    @Test("An unavailable model refuses the step without running it")+    func unavailableStateThrows() async throws {+        let model = AppLibraryModel(startupFailureMessage: "No App Group")+        await model.bootstrap()+        guard case .unavailable = model.state else {+            Issue.record("The fixture did not reach the unavailable state")+            return+        }++        let entered = await expectUnavailable(model)++        #expect(!entered)+    }++    @Test("A cold step runs on an open background-export session rather than opening its own")+    func coldStepReusesTheBackgroundSession() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        try await createLibrary(at: root)+        let configuration = configuration(mirroring: true, at: root)+        try ExportOwedMarker(directory: configuration.exportOwedURL).mark()+        let containers = ContainerGate(holds: false)+        let model = AppLibraryModel(configuration: configuration)+        model.mirroringOpenHooks = containers.hooks++        let pass = Task { await model.runBackgroundExport() }+        await waitUntil("the pass to open a session of its own") { model.backgroundSession != nil }+        let session = try #require(model.backgroundSession?.repository)++        let used = try await model.intentBroker.withLibrary(writes: false) { library in+            library as? LibraryRepository+        }++        #expect(used === session, "the step ran on the pass's session")+        #expect(model.backgroundSession?.repository === session, "and left it with the pass")+        _ = try await session.works()+        #expect(containers.constructionCount == 1)+        pass.cancel()+        _ = await pass.value+        #expect(model.backgroundSession == nil)+    }++    @Test("A step that arrives while a pass is opening its session borrows it, and opens nothing")+    func stepDuringThePassOpenBorrowsTheSession() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        try await createLibrary(at: root)+        let configuration = configuration(mirroring: true, at: root)+        try ExportOwedMarker(directory: configuration.exportOwedURL).mark()+        let containers = ContainerGate(holds: true)+        let model = AppLibraryModel(configuration: configuration)+        model.mirroringOpenHooks = containers.hooks++        let pass = Task { await model.runBackgroundExport() }+        // The pass holds the broker's turn for the length of its open.+        await waitUntil("the pass to take the turn for its open") { model.intentBroker.isBusy }+        #expect(model.backgroundSession == nil, "the open is still in flight")+        let recorder = Recorder()+        let step = Task {+            try await model.intentBroker.withLibrary(writes: false) { library in+                recorder.append("ran")+                return library as? LibraryRepository+            }+        }+        try? await Task.sleep(for: .milliseconds(50))+        #expect(recorder.events.isEmpty, "the step waits for the open rather than opening cold")++        containers.release()+        let used = try await step.value+        let session = try #require(model.backgroundSession?.repository)++        // Had the step opened cold, it would hold an `openForExtension`+        // repository of its own, not the pass's.+        #expect(used === session, "the step ran on the pass's session")+        #expect(containers.constructionCount == 1)+        pass.cancel()+        _ = await pass.value+        #expect(model.backgroundSession == nil)+        #expect(!model.intentBroker.isBusy)+    }++    // MARK: - Bootstrap (Req 6.4)++    @Test("A step during a bootstrap waits for the library to open, then runs on it")+    func stepDuringBootstrapWaitsForTheResidentLibrary() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        let configuration = configuration(mirroring: true, at: root)+        let containers = ContainerGate(holds: true)+        let model = AppLibraryModel(configuration: configuration)+        model.mirroringOpenHooks = containers.hooks++        let boot = Task { await model.bootstrap() }+        await waitUntil("the bootstrap to be in flight") { model.bootstrapInFlight }+        let recorder = Recorder()+        let step = Task {+            try await model.intentBroker.withLibrary(writes: false) { _ in+                let state = await model.state+                let resident = await model.hasOpenForegroundRepository+                recorder.append("ran ready=\(state == .ready) resident=\(resident)")+            }+        }+        try? await Task.sleep(for: .milliseconds(50))+        #expect(recorder.events.isEmpty, "nothing runs while the library is opening")++        containers.release()+        await boot.value+        try await step.value++        #expect(recorder.events == ["ran ready=true resident=true"])+        #expect(containers.constructionCount == 1)+    }++    @Test("A bootstrap waits for a cold step in flight and never cancels it")+    func bootstrapDrainsTheColdStep() async throws {+        let root = tempRoot()+        defer { try? FileManager.default.removeItem(at: root) }+        try await createLibrary(at: root)+        let configuration = configuration(mirroring: true, at: root)+        let containers = ContainerGate(holds: false)+        let model = AppLibraryModel(configuration: configuration)+        model.mirroringOpenHooks = containers.hooks++        let gate = SubmissionGate()+        let recorder = Recorder()+        let step = Task {+            try await model.intentBroker.withLibrary(writes: true) { library in+                recorder.append("step started")+                await gate.wait()+                let outcome = try await library.createWorkUnlessPresent(Self.draft("Drained Work"))+                recorder.append("step finished")+                return outcome+            }+        }+        await waitUntil("the cold step to start") { recorder.events == ["step started"] }+        let boot = Task { await model.bootstrap() }+        await waitUntil("the bootstrap to be in flight") { model.bootstrapInFlight }+        try? await Task.sleep(for: .milliseconds(50))+        #expect(containers.constructionCount == 0, "the mirrored library waits for the step")++        gate.open()+        let outcome = try await step.value+        await boot.value++        guard case .created = outcome else {+            Issue.record("The step was not allowed to finish its write: \(outcome)")+            return+        }+        #expect(recorder.events == ["step started", "step finished"])+        #expect(model.state == .ready)+        #expect(containers.constructionCount == 1)+    }++    // MARK: - Admission++    @Test("Two concurrent steps run one at a time, in the order they arrived")+    func concurrentStepsRunInOrder() async throws {+        let model = AppLibraryModel(readyRepository: MockLibraryProvider())+        let gate = SubmissionGate()+        let recorder = Recorder()++        let first = Task {+            try await model.intentBroker.withLibrary(writes: false) { _ in+                recorder.append("first started")+                await gate.wait()+                recorder.append("first finished")+            }+        }+        await waitUntil("the first step to start") { recorder.events == ["first started"] }+        let second = Task {+            try await model.intentBroker.withLibrary(writes: false) { _ in recorder.append("second") }+        }+        try? await Task.sleep(for: .milliseconds(50))+        #expect(recorder.events == ["first started"], "the second waits for the first")+        #expect(model.intentBroker.isBusy)++        gate.open()+        try await first.value+        try await second.value++        #expect(recorder.events == ["first started", "first finished", "second"])+        #expect(!model.intentBroker.isBusy)+    }++    @Test("drain resolves only after the step in flight has finished")+    func drainWaitsForTheStepInFlight() async throws {+        let model = AppLibraryModel(readyRepository: MockLibraryProvider())+        let gate = SubmissionGate()+        let recorder = Recorder()++        let step = Task {+            try await model.intentBroker.withLibrary(writes: false) { _ in+                recorder.append("started")+                await gate.wait()+                recorder.append("finished")+            }+        }+        await waitUntil("the step to start") { recorder.events == ["started"] }+        let drain = Task {+            await model.intentBroker.drain()+            recorder.append("drained")+        }+        try? await Task.sleep(for: .milliseconds(50))+        #expect(recorder.events == ["started"])++        gate.open()+        try await step.value+        await drain.value++        #expect(recorder.events == ["started", "finished", "drained"])+    }++    @Test("drain with nothing in flight resolves at once")+    func drainWithNothingInFlight() async {+        let model = AppLibraryModel(readyRepository: MockLibraryProvider())+        await model.intentBroker.drain()+        #expect(!model.intentBroker.isBusy)+    }++    @Test("A background export pass skips while a step holds the library")+    func exportSkipsWhileBusy() async throws {+        let model = AppLibraryModel(readyRepository: MockLibraryProvider())+        let gate = SubmissionGate()+        let recorder = Recorder()+        let step = Task {+            try await model.intentBroker.withLibrary(writes: false) { _ in+                recorder.append("started")+                await gate.wait()+            }+        }+        await waitUntil("the step to start") { recorder.events == ["started"] }++        let acquisition = await model.acquire()++        gate.open()+        try await step.value+        guard case .skipped(.unavailable(let reason)) = acquisition else {+            Issue.record("Expected the pass to skip, got \(acquisition)")+            return+        }+        #expect(reason == AppLibraryModel.intentHoldsLibraryReason)+        #expect(!model.backgroundPassHoldsLibrary)+    }+}
Asterism/AsterismTests/OpenTargetFlowTests.swift Added +197 / -0
diff --git a/Asterism/AsterismTests/OpenTargetFlowTests.swift b/Asterism/AsterismTests/OpenTargetFlowTests.swiftnew file mode 100644index 00000000..ac6169e4--- /dev/null+++ b/Asterism/AsterismTests/OpenTargetFlowTests.swift@@ -0,0 +1,197 @@+import AsterismCore+import Foundation+import Testing+@testable import Asterism++/// Task 17 of `app-intents`: the open intents' decisions, without the App+/// Intents runtime (Reqs 4.1–4.6).+///+/// The flow is handed a broker over a mock library, a real `AppNavigation`,+/// and a foreground closure that records whether it was called. Whether the+/// system allows foregrounding is a parameter, as `systemContext.currentMode`+/// gives it to the intent.+@Suite("OpenTargetFlow")+@MainActor+struct OpenTargetFlowTests {++    // MARK: - Fixtures++    private final class Foreground {+        var calls = 0+    }++    @MainActor+    private struct Harness {+        let model: AppLibraryModel+        let navigation = AppNavigation()+        let foreground = Foreground()++        func flow(canContinueInForeground: Bool = true) -> OpenTargetFlow {+            let foreground = foreground+            return OpenTargetFlow(+                broker: model.intentBroker, navigation: navigation,+                canContinueInForeground: canContinueInForeground,+                continueInForeground: { foreground.calls += 1 })+        }+    }++    /// `nonisolated`: it is a default argument, which is evaluated outside the+    /// suite's main actor.+    private nonisolated static let work = WorkSummary(+        id: UUID(), displayTitle: "Open Serial", readingStatus: .reading, workStatus: .ongoing)++    private func harness(holding works: [WorkSummary] = [work]) -> (Harness, MockLibraryProvider) {+        let mock = MockLibraryProvider()+        for work in works { mock.workSummariesByID[work.id] = work }+        return (Harness(model: AppLibraryModel(readyRepository: mock)), mock)+    }++    // MARK: - Not found (Req 4.4)++    @Test("A work the library no longer holds is not found, and the app stays in the background")+    func missingWorkIsNotFound() async throws {+        let (harness, mock) = harness(holding: [])+        let missing = UUID()++        let outcome = try await harness.flow().run(.work(missing))++        #expect(outcome.dialog == OpenTargetFlow.notFoundSentence)+        #expect(!outcome.foregrounded)+        #expect(harness.foreground.calls == 0)+        #expect(harness.navigation.intentRoute == nil)+        #expect(mock.workSummaryRequests == [[missing]])+    }++    // MARK: - Unavailable (Req 4.6, Q22)++    @Test("An unavailable library skips the check and routes, and the app comes forward")+    func unavailableLibrarySkipsTheCheckAndRoutes() async throws {+        let model = AppLibraryModel(startupFailureMessage: "No App Group")+        await model.bootstrap()+        let harness = Harness(model: model)+        let id = UUID()++        let outcome = try await harness.flow().run(.work(id))++        #expect(harness.navigation.intentRoute+            == IntentRoute(target: .work(id), revision: harness.navigation.revision))+        #expect(outcome.foregrounded)+        #expect(harness.foreground.calls == 1)+    }++    @Test("A library still opening skips the check and routes at once, without waiting for the open")+    func openingLibrarySkipsTheCheckAndRoutes() async throws {+        let root = FileManager.default.temporaryDirectory+            .appending(path: "asterism-open-target-\(UUID())")+        defer { try? FileManager.default.removeItem(at: root) }+        let containers = MirroredContainerGate(holds: true)+        let model = AppLibraryModel(configuration: LibraryConfiguration(+            rootDirectory: root, cloudKitContainerID: "iCloud.example.fixture"))+        model.mirroringOpenHooks = containers.hooks+        let boot = Task { await model.bootstrap() }+        let deadline = Date().addingTimeInterval(15)+        while !model.bootstrapInFlight, Date() < deadline {+            try? await Task.sleep(for: .milliseconds(2))+        }+        try #require(model.bootstrapInFlight, "the fixture has a bootstrap in flight")+        let harness = Harness(model: model)+        let id = UUID()++        let outcome = try await harness.flow().run(.work(id))++        #expect(model.bootstrapInFlight, "answered while the library was still opening")+        #expect(model.state == .loading)+        #expect(outcome.dialog == "Opening that work.")+        #expect(outcome.foregrounded)+        #expect(harness.foreground.calls == 1)+        #expect(harness.navigation.intentRoute+            == IntentRoute(target: .work(id), revision: harness.navigation.revision))++        containers.release()+        await boot.value+    }++    // MARK: - A failed foregrounding++    private struct ForegroundFailed: Error {}++    @Test("A foregrounding that throws takes back the route it left, and the error reaches the intent")+    func failedForegroundClearsTheRoute() async throws {+        let (harness, _) = harness()+        let flow = OpenTargetFlow(+            broker: harness.model.intentBroker, navigation: harness.navigation,+            canContinueInForeground: true,+            continueInForeground: { throw ForegroundFailed() })++        await #expect(throws: ForegroundFailed.self) {+            _ = try await flow.run(.work(Self.work.id))+        }+        #expect(harness.navigation.intentRoute == nil, "a failed open leaves no route to move the window")+    }++    // MARK: - An edit in progress (Req 4.5, Q15, Q37)++    @Test("An edit in progress is answered, the app comes forward, and nothing is routed")+    func editingAnswersAndRoutesNothing() async throws {+        let (harness, _) = harness()+        harness.navigation.showingSettings = true++        let outcome = try await harness.flow().run(.work(Self.work.id))++        #expect(outcome.dialog == OpenTargetFlow.editingSentence)+        #expect(outcome.foregrounded)+        #expect(harness.foreground.calls == 1)+        #expect(harness.navigation.intentRoute == nil)+        #expect(harness.navigation.showingSettings, "the sheet is left as it was")+    }++    // MARK: - The route (Reqs 4.1, 4.2)++    @Test("Open work routes to the work at the current revision and names it")+    func openWorkRoutesAtTheCurrentRevision() async throws {+        let (harness, _) = harness()+        harness.navigation.selectedTab = .works+        let revision = harness.navigation.revision+        #expect(revision > 0, "the fixture moved the revision")++        let outcome = try await harness.flow().run(.work(Self.work.id))++        #expect(harness.navigation.intentRoute+            == IntentRoute(target: .work(Self.work.id), revision: revision))+        #expect(outcome.dialog == "Opening “Open Serial”.")+        #expect(outcome.foregrounded)+        #expect(harness.foreground.calls == 1)+    }++    @Test("Open Today routes to Today without reading the library")+    func openTodayRoutesWithoutACheck() async throws {+        let (harness, mock) = harness()++        let outcome = try await harness.flow().run(.today)++        #expect(harness.navigation.intentRoute+            == IntentRoute(target: .today, revision: harness.navigation.revision))+        #expect(outcome.dialog == "Opening Today.")+        #expect(mock.workSummaryRequests.isEmpty)+        #expect(harness.foreground.calls == 1)+    }++    // MARK: - Foregrounding not allowed++    @Test("Where the system does not allow foregrounding, the answer stands and the route waits")+    func noForegroundWhenNotAllowed() async throws {+        let (harness, _) = harness()++        let opened = try await harness.flow(canContinueInForeground: false).run(.work(Self.work.id))+        #expect(!opened.foregrounded)+        #expect(harness.foreground.calls == 0)+        #expect(harness.navigation.intentRoute?.target == .work(Self.work.id), "the route waits")++        harness.navigation.intentRoute = nil+        harness.navigation.showingNewWork = true+        let editing = try await harness.flow(canContinueInForeground: false).run(.today)+        #expect(editing.dialog == OpenTargetFlow.editingSentence)+        #expect(!editing.foregrounded)+        #expect(harness.foreground.calls == 0)+    }+}
Asterism/AsterismTests/WorkEntityQueryTests.swift Added +201 / -0
diff --git a/Asterism/AsterismTests/WorkEntityQueryTests.swift b/Asterism/AsterismTests/WorkEntityQueryTests.swiftnew file mode 100644index 00000000..c5bf3997--- /dev/null+++ b/Asterism/AsterismTests/WorkEntityQueryTests.swift@@ -0,0 +1,201 @@+import AppIntents+import AsterismCore+import Foundation+import Testing+@testable import Asterism++/// Task 12 of `app-intents`: works as Shortcuts values (Reqs 5.1–5.4, 6.3).+///+/// The query runs over a broker whose model holds a **real** repository in a+/// temporary root, so the comparisons are the Core reads' own and a rename is+/// seen the way Siri would see it. Protected data is injected: the unit bundle+/// runs on a simulator that is never locked.+@Suite("WorkEntityQuery", .serialized)+@MainActor+struct WorkEntityQueryTests {++    // MARK: - Fixtures++    private struct Library {+        let root: URL+        let repository: LibraryRepository+        let model: AppLibraryModel++        func close() async {+            await repository.shutdown()+            try? FileManager.default.removeItem(at: root)+        }+    }++    private func openLibrary() async throws -> Library {+        let root = FileManager.default.temporaryDirectory+            .appending(path: "asterism-work-entity-query-\(UUID())")+        let repository = try await LibraryRepository.openForApp(+            LibraryConfiguration(rootDirectory: root, cloudKitContainerID: nil)+        ).repository+        return Library(+            root: root, repository: repository,+            model: AppLibraryModel(readyRepository: repository))+    }++    @discardableResult+    private func addWork(+        _ title: String, _ status: ReadingStatus, in library: Library+    ) async throws -> WorkSnapshot {+        try await library.repository.createWork(+            NewWorkDraft(+                displayTitle: title, hostname: "https://example.com/\(UUID())",+                readingStatus: status))+    }++    private func query(+        _ library: Library, protectedDataAvailable: Bool = true+    ) -> WorkEntityQuery {+        let broker = library.model.intentBroker+        return WorkEntityQuery(lookup: {+            WorkEntityLookup(broker: broker, isProtectedDataAvailable: { protectedDataAvailable })+        })+    }++    // MARK: - entities(for:) (Reqs 4.4, 5.3)++    @Test("entities(for:) answers in the order asked and omits an id the library does not hold")+    func entitiesForIdsOmitsMissing() async throws {+        let library = try await openLibrary()+        let first = try await addWork("First Serial", .reading, in: library)+        let second = try await addWork("Second Serial", .finished, in: library)++        let found = try await query(library).entities(for: [second.id, UUID(), first.id])+        await library.close()++        #expect(found.map(\.id) == [second.id, first.id])+        #expect(found.map(\.title) == ["Second Serial", "First Serial"])+    }++    @Test("A work value shows its current title and both statuses (Reqs 5.1, 5.3)")+    func entityCarriesTitleAndStatuses() async throws {+        let library = try await openLibrary()+        let work = try await addWork("Catching Serial", .catchingUp, in: library)++        let found = try await query(library).entities(for: [work.id])+        await library.close()++        let entity = try #require(found.first)+        #expect(entity.title == "Catching Serial")+        #expect(entity.readingStatus == "Catching up")+        #expect(entity.workStatus == "Ongoing")+    }++    // MARK: - Find works (Req 5.2)++    @Test("The string query and the property query's title contains-comparator find the same works")+    func stringAndPropertyQueriesAgree() async throws {+        let library = try await openLibrary()+        let mere = try await addWork("La Mère Folle", .reading, in: library)+        let finished = try await addWork("Grand-mère's Kitchen", .finished, in: library)+        try await addWork("Unrelated", .reading, in: library)+        let query = query(library)++        let byString = try await query.entities(matching: "MERE")+        let byProperty = try await query.entities(+            matching: ["MERE"], mode: .and, sortedBy: [], limit: nil)+        await library.close()++        #expect(Set(byString.map(\.id)) == [mere.id, finished.id], "finished works are found too")+        #expect(byProperty.map(\.id) == byString.map(\.id))+    }++    @Test("Several contains-comparators combine by their mode, and the limit caps the answer")+    func propertyQueryModesAndLimit() async throws {+        let library = try await openLibrary()+        let both = try await addWork("Alpha Beta", .reading, in: library)+        let alpha = try await addWork("Alpha Only", .reading, in: library)+        let beta = try await addWork("Beta Only", .reading, in: library)+        let query = query(library)++        let and = try await query.entities(+            matching: ["alpha", "beta"], mode: .and, sortedBy: [], limit: nil)+        let or = try await query.entities(+            matching: ["alpha", "beta"], mode: .or, sortedBy: [], limit: nil)+        let limited = try await query.entities(+            matching: ["alpha", "beta"], mode: .or, sortedBy: [], limit: 2)+        await library.close()++        #expect(and.map(\.id) == [both.id])+        #expect(or.map(\.id) == [both.id, alpha.id, beta.id], "title order")+        #expect(limited.map(\.id) == [both.id, alpha.id])+    }++    // MARK: - Suggested works (Req 5.4)++    @Test("suggestedEntities are the reading and catching-up works")+    func suggestedAreReadingAndCatchingUp() async throws {+        let library = try await openLibrary()+        let reading = try await addWork("B Reading", .reading, in: library)+        let catching = try await addWork("A Catching", .catchingUp, in: library)+        try await addWork("C To Read", .toRead, in: library)+        try await addWork("D Finished", .finished, in: library)++        let suggested = try await query(library).suggestedEntities()+        await library.close()++        #expect(suggested.map(\.id) == [catching.id, reading.id])+    }++    // MARK: - Locked (Req 6.3, Q34)++    @Test("Every query throws the locked error while protected data is unavailable")+    func queriesThrowWhileLocked() async throws {+        let library = try await openLibrary()+        let work = try await addWork("Hidden Serial", .reading, in: library)+        let query = query(library, protectedDataAvailable: false)++        await #expect(throws: IntentLockedError.self) { _ = try await query.entities(for: [work.id]) }+        await #expect(throws: IntentLockedError.self) { _ = try await query.entities(matching: "Hidden") }+        await #expect(throws: IntentLockedError.self) {+            _ = try await query.entities(matching: ["Hidden"], mode: .and, sortedBy: [], limit: nil)+        }+        await #expect(throws: IntentLockedError.self) { _ = try await query.suggestedEntities() }+        await library.close()+    }++    @Test("An unavailable library is reported as unavailable, not as no works")+    func unavailableLibraryThrows() async throws {+        let model = AppLibraryModel(startupFailureMessage: "No App Group")+        await model.bootstrap()+        let broker = model.intentBroker+        let query = WorkEntityQuery(lookup: {+            WorkEntityLookup(broker: broker, isProtectedDataAvailable: { true })+        })++        await #expect(throws: IntentLibraryError.self) { _ = try await query.suggestedEntities() }+    }++    // MARK: - Shortcut parameters (Req 5.4)++    @Test("refresh updates the App Shortcut parameters only when the id-to-title set changes")+    func shortcutParametersRefreshOnlyOnChange() {+        var updates = 0+        let parameters = ShortcutParameters(update: { updates += 1 })+        let reading = TestFixtures.makeWork(displayTitle: "Reading", readingStatus: .reading)+        let catching = TestFixtures.makeWork(displayTitle: "Catching", readingStatus: .catchingUp)+        let finished = TestFixtures.makeWork(displayTitle: "Finished", readingStatus: .finished)++        parameters.refresh(works: [reading, catching, finished])+        #expect(updates == 1, "the first set is always registered")++        parameters.refresh(works: [catching, reading])+        #expect(updates == 1, "same set in another order")++        parameters.refresh(works: [reading, catching, finished, TestFixtures.makeWork(readingStatus: .toRead)])+        #expect(updates == 1, "a work outside the two statuses changes nothing")++        let renamed = TestFixtures.makeWork(+            id: reading.id, displayTitle: "Reading, renamed", readingStatus: .reading)+        parameters.refresh(works: [renamed, catching])+        #expect(updates == 2, "a rename changes the set")++        parameters.refresh(works: [renamed])+        #expect(updates == 3, "a work leaving the set changes it")+    }+}
Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swift Added +142 / -0
diff --git a/Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swift b/Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swiftnew file mode 100644index 00000000..f7fcfce9--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swift@@ -0,0 +1,142 @@+import Foundation++/// One work releasing today, as the "chapters releasing today" intent answers+/// it (`app-intents` Req 1.1).+public struct ReleaseAnswer: Equatable, Sendable {+    public let workID: UUID+    public let title: String+    /// Whether the Today screen's row for this work reads as noted on the day.+    public let notedToday: Bool++    public init(workID: UUID, title: String, notedToday: Bool) {+        self.workID = workID+        self.title = title+        self.notedToday = notedToday+    }+}++/// One note made today, as the "notes from today" intent answers it+/// (`app-intents` Req 2.1).+public struct NoteAnswer: Equatable, Sendable {+    public let entryID: UUID+    /// The work's display title, or the capture title of an entry with no work.+    public let title: String+    /// The chapter title, else the chapter number, else nil (Q18).+    public let chapterLine: String?+    /// The note text, trimmed; never blank (Req 2.2).+    public let note: String++    public init(entryID: UUID, title: String, chapterLine: String?, note: String) {+        self.entryID = entryID+        self.title = title+        self.chapterLine = chapterLine+        self.note = note+    }+}++/// The two read-only intents' answers, derived from the Today read.+///+/// **Pure, and composed from `TodayDayPlan.build`** (Q28): Siri and the Today+/// screen answer from one derivation, so they cannot disagree about which works+/// are due or which notes were made (Req 1.4). Nothing here opens a store or+/// reads a clock. `currentDay` is minted by the caller when the intent runs,+/// not taken from the day an open Today screen last published (Q17), which is+/// what keeps the answer right just after midnight.+///+/// No `AppIntents` here (Q27): the dialogs are plain strings the app target+/// wraps.+public enum IntentAnswers {+    /// How many items a dialog names before it states the count instead (Q11,+    /// Req 2.4).+    static let spokenLimit = 5++    /// The Today plan's release rows for `currentDay`, in order (Reqs 1.1, 1.4).+    ///+    /// Catch-up works are in the plan's own section and to-read works in none,+    /// so neither is releasing today (Q10).+    public static func releasingToday(+        _ presentation: TodayPresentation, currentDay: CivilDay, calendar: Calendar+    ) -> [ReleaseAnswer] {+        plan(presentation, currentDay: currentDay, calendar: calendar).releases.map { row in+            let noted: Bool+            if case .notedOnDay = row.line { noted = true } else { noted = false }+            return ReleaseAnswer(workID: row.id, title: row.title, notedToday: noted)+        }+    }++    /// The Today plan's noted section for `currentDay`, in order — future-dated+    /// rows first, as the screen folds them — without the rows whose note is+    /// blank (Reqs 2.1, 2.2).+    public static func notesToday(+        _ presentation: TodayPresentation, currentDay: CivilDay, calendar: Calendar+    ) -> [NoteAnswer] {+        let rows = plan(presentation, currentDay: currentDay, calendar: calendar).noted?.rows ?? []+        return rows.compactMap { row in+            let note = row.note.trimmingCharacters(in: .whitespacesAndNewlines)+            guard !note.isEmpty else { return nil }+            // The fallbacks the noted row itself draws with: the capture title+            // for an entry with no work, and `chapterTitle`, which the read has+            // already made title-else-sequence.+            return NoteAnswer(+                entryID: row.id, title: row.workDisplayTitle ?? row.captureTitle,+                chapterLine: row.chapterTitle, note: note)+        }+    }++    /// The releases dialog: `full` is spoken, `supporting` accompanies the+    /// shown list. Above five items `full` gives the count and the first five.+    public static func dialog(for releases: [ReleaseAnswer]) -> (full: String, supporting: String) {+        guard !releases.isEmpty else {+            let empty = "No chapters are expected today."+            return (empty, empty)+        }+        let count =+            releases.count == 1+            ? "1 chapter is expected today"+            : "\(releases.count) chapters are expected today"+        let named = spokenList(+            releases.prefix(spokenLimit).map { $0.notedToday ? "\($0.title), already noted" : $0.title })+        let full =+            releases.count > spokenLimit+            ? "\(count). The first five: \(named)."+            : "\(count): \(named)."+        return (full, "\(count).")+    }++    /// The notes dialog, one note per line after a count sentence. Above five+    /// notes only the first five are spoken (Req 2.4).+    public static func dialog(for notes: [NoteAnswer]) -> (full: String, supporting: String) {+        guard !notes.isEmpty else {+            let empty = "There are no notes from today."+            return (empty, empty)+        }+        let count = notes.count == 1 ? "You made 1 note today." : "You made \(notes.count) notes today."+        let header = notes.count > spokenLimit ? "\(count) The first five:" : count+        let lines = notes.prefix(spokenLimit).map { note in+            let name = note.chapterLine.map { "\(note.title), \($0)" } ?? note.title+            return "\(name): \(note.note)"+        }+        return (([header] + lines).joined(separator: "\n"), count)+    }++    // MARK: - Private++    private static func plan(+        _ presentation: TodayPresentation, currentDay: CivilDay, calendar: Calendar+    ) -> TodayDayPlan {+        TodayDayPlan.build(+            day: currentDay, currentDay: currentDay, schedule: presentation.schedule,+            presentation: presentation, calendar: calendar)+    }++    /// Items joined for speech. Semicolons rather than commas between items,+    /// because a title can hold a comma and a release item holds one of its own.+    private static func spokenList(_ items: [String]) -> String {+        switch items.count {+        case 0: return ""+        case 1: return items[0]+        case 2: return "\(items[0]) and \(items[1])"+        default: return items.dropLast().joined(separator: "; ") + "; and \(items[items.count - 1])"+        }+    }+}
Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift Modified +51 / -0
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex dd7b2c11..c848eea2 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift@@ -520,6 +520,28 @@ public protocol LibraryProviding: Sendable {     /// Commit an approved Merge contract.     func commitMerge(_ contract: WorkMergeContract) async throws -> WorkMergeCommitOutcome +    // MARK: - App Intents (`app-intents`)++    /// The works with these ids, in the order asked; a missing id is omitted+    /// (Reqs 4.4, 5.3).+    func workSummaries(ids: [UUID]) async throws -> [WorkSummary]++    /// Every work whose title contains the text, case- and+    /// diacritic-insensitively, in title order (Req 5.2).+    func workSummaries(titleContaining text: String) async throws -> [WorkSummary]++    /// Every work on one of these reading statuses, in title order (Req 5.4).+    func workSummaries(readingStatuses: Set<ReadingStatus>) async throws -> [WorkSummary]++    /// Whether a page is already in the library, as a work or as an unattached+    /// entry, compared by the capture URL key (Req 3.5).+    func pageMatch(rawURL: String) async throws -> PageMatch?++    /// `createWork`, unless the draft's URL is in the library by the time of+    /// the write; the check and the write share one lock and one save+    /// (Reqs 3.4, 3.5).+    func createWorkUnlessPresent(_ draft: NewWorkDraft) async throws -> CreateWorkOutcome+     // MARK: - Teardown      /// Releases whatever this provider holds open, so a re-open is the only@@ -695,6 +717,35 @@ public extension LibraryProviding {             operation: "a related-work link operation",             reason: "this library provider does not implement links")     }++    // MARK: App Intents++    // Throwing defaults for the reason the series ones throw: an empty list from+    // a double that never implemented the read would present as "no works", a+    // fact about the library rather than about the double.+    func workSummaries(ids: [UUID]) async throws -> [WorkSummary] {+        throw Self.intentsUnsupported+    }++    func workSummaries(titleContaining text: String) async throws -> [WorkSummary] {+        throw Self.intentsUnsupported+    }++    func workSummaries(readingStatuses: Set<ReadingStatus>) async throws -> [WorkSummary] {+        throw Self.intentsUnsupported+    }++    func pageMatch(rawURL: String) async throws -> PageMatch? { throw Self.intentsUnsupported }++    func createWorkUnlessPresent(_ draft: NewWorkDraft) async throws -> CreateWorkOutcome {+        throw Self.intentsUnsupported+    }++    private static var intentsUnsupported: LibraryRepositoryError {+        .invalidInput(+            operation: "an intent read",+            reason: "this library provider does not implement intent reads")+    } }  extension LibraryRepository: LibraryProviding {}
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift Modified +9 / -3
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swiftindex 02663b28..c3c77f32 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift@@ -358,9 +358,15 @@ public extension LibraryRepository {         return try openContainer(at: configuration.storeURL)     } -    /// **The extension-role opener — the only one (Req 4.4) — under a SHARED-    /// cross-process lease**, taken with the interactive timeout rather than the-    /// bootstrap one: a share sheet that cannot get in must say so quickly.+    /// **The extension-role opener (Req 4.4) — under a SHARED cross-process+    /// lease**, taken with the interactive timeout rather than the bootstrap+    /// one: a share sheet that cannot get in must say so quickly.+    ///+    /// It has two callers, and both need exactly this: the share extension, and+    /// the app's `IntentLibraryBroker` for a cold intent step in a process with+    /// no library open (`app-intents` Decision 4). Neither may create, re-mark,+    /// migrate or mirror a store, and Siri, like a share sheet, cannot wait out+    /// the bootstrap timeout.     ///     /// A shared lease is all it needs and all it may have, because it writes     /// nothing: it requires the readiness marker recording `"8"` plus a store,
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift Modified +69 / -48
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swiftindex db251a6c..1fac96c4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift@@ -201,54 +201,10 @@ extension LibraryRepository {         captureLogger.debug("Capture lookup: hostname=\(hostname, privacy: .public)")          return try await withLockedContext(mode: .shared, operation: "capture lookup") { context in-            // v1 alias: the immutable raw URL (Q21). Same-URL re-shares always-            // match this against `conservativeIdentityKey`, forever.-            var candidates: [String] = [rawURL]--            if let site = try Self.fetchSites(hostname: hostname, context: context).first,-               let currentRule = site.currentURLRule,-               // `try?`: a rule whose stored bytes will not decode is not-               // applied, and the lookup falls back to the conservative alias-               // alone. Capture must never fail because of a rule (Req 4.4) —-               // that is M1's guarantee, and the share extension has nowhere to-               // put such a failure but the reader's face.-               let definition = try? currentRule.definition {-                // v2 candidate: an identity+sequence rule identifies the chapter-                // without a title (Safari page shares supply one; others may not).-                if definition.suppliesIdentity,-                   let extraction = try? URLRuleApplicator.apply(definition, to: ExactScalarString(rawURL)),-                   let sequence = extraction.chapterSequence,-                   let derived = try? URLDerivedEntryIdentity(-                       hostname: ExactScalarString(hostname),-                       workIdentity: extraction.workIdentity, chapterSequence: sequence) {-                    candidates.append(EntryIdentityKeyV2Codec.encode(derived))-                }-                // v3 candidate: only when a capture title is supplied, so the-                // sequence-only key can embed the title-derived Work name (Q21).-                if let captureTitle,-                   let activePattern = site.activePattern,-                   let stored = try? activePattern.storedDefinition {-                    let titleRule = ComposedTitleRule(stored)-                    let derivation = ComposedDeriver.derive(-                        captureTitle: captureTitle, rawURL: rawURL, hostname: hostname,-                        titleRule: titleRule, urlRule: ComposedURLRule(definition: definition))-                    if derivation.identity.version >= 2 {-                        candidates.append(derivation.identity.key)-                    }-                }-            }--            // Match candidates against both the identity key and the conservative-            // alias, so an upgraded (v2/v3) Entry and a title-less same-URL re-share-            // both resolve to the existing chapter.-            let descriptor = FetchDescriptor<Entry>(-                predicate: #Predicate<Entry> {-                    $0.hostname == hostname-                        && (candidates.contains($0.entryIdentityKey)-                            || candidates.contains($0.conservativeIdentityKey))-                }-            )-            let matches = try context.fetch(descriptor)+            let candidates = try Self.captureCandidates(+                rawURL: rawURL, hostname: hostname, captureTitle: captureTitle, context: context)+            let matches = try Self.captureMatches(+                candidates: candidates, hostname: hostname, context: context)             captureLogger.debug("Capture lookup: \(matches.count) match(es)")             let canonicalWorkIDs = try Self.canonicalWorkIDs(                 normalising: matches, context: context)@@ -289,6 +245,71 @@ extension LibraryRepository {         }     } +    /// The identity keys a capture of `rawURL` would match an existing Entry+    /// by: the raw URL itself, plus the candidates the hostname's current rules+    /// derive from it. Shared by `captureLookup` and the add intent's duplicate+    /// check (`app-intents` Req 3.5), so the two cannot disagree about whether+    /// a page is already in the library.+    static func captureCandidates(+        rawURL: String, hostname: String, captureTitle: String?, context: ModelContext+    ) throws -> [String] {+        // v1 alias: the immutable raw URL (Q21). Same-URL re-shares always+        // match this against `conservativeIdentityKey`, forever.+        var candidates: [String] = [rawURL]++        if let site = try Self.fetchSites(hostname: hostname, context: context).first,+           let currentRule = site.currentURLRule,+           // `try?`: a rule whose stored bytes will not decode is not+           // applied, and the lookup falls back to the conservative alias+           // alone. Capture must never fail because of a rule (Req 4.4) —+           // that is M1's guarantee, and the share extension has nowhere to+           // put such a failure but the reader's face.+           let definition = try? currentRule.definition {+            // v2 candidate: an identity+sequence rule identifies the chapter+            // without a title (Safari page shares supply one; others may not).+            if definition.suppliesIdentity,+               let extraction = try? URLRuleApplicator.apply(definition, to: ExactScalarString(rawURL)),+               let sequence = extraction.chapterSequence,+               let derived = try? URLDerivedEntryIdentity(+                   hostname: ExactScalarString(hostname),+                   workIdentity: extraction.workIdentity, chapterSequence: sequence) {+                candidates.append(EntryIdentityKeyV2Codec.encode(derived))+            }+            // v3 candidate: only when a capture title is supplied, so the+            // sequence-only key can embed the title-derived Work name (Q21).+            if let captureTitle,+               let activePattern = site.activePattern,+               let stored = try? activePattern.storedDefinition {+                let titleRule = ComposedTitleRule(stored)+                let derivation = ComposedDeriver.derive(+                    captureTitle: captureTitle, rawURL: rawURL, hostname: hostname,+                    titleRule: titleRule, urlRule: ComposedURLRule(definition: definition))+                if derivation.identity.version >= 2 {+                    candidates.append(derivation.identity.key)+                }+            }+        }+        return candidates+    }++    /// The Entry rows on `hostname` that `candidates` match.+    ///+    /// Candidates are matched against both the identity key and the+    /// conservative alias, so an upgraded (v2/v3) Entry and a title-less+    /// same-URL re-share both resolve to the existing chapter.+    static func captureMatches(+        candidates: [String], hostname: String, context: ModelContext+    ) throws -> [Entry] {+        let descriptor = FetchDescriptor<Entry>(+            predicate: #Predicate<Entry> {+                $0.hostname == hostname+                    && (candidates.contains($0.entryIdentityKey)+                        || candidates.contains($0.conservativeIdentityKey))+            }+        )+        return try context.fetch(descriptor)+    }+     /// Builds a lookup disposition from the matched Entries. Shared by     /// `captureLookup` and the `commitCapture` pre-insert race guard (Q27).     ///
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift Added +272 / -0
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swiftnew file mode 100644index 00000000..ad03bb23--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift@@ -0,0 +1,272 @@+import Foundation+import SwiftData++/// A work as Siri and Shortcuts see it (`app-intents` Req 5.1): its identity,+/// its title and its two statuses, and nothing that needs the entries.+public struct WorkSummary: Sendable, Hashable, Identifiable {+    public let id: UUID+    public let displayTitle: String+    public let readingStatus: ReadingStatus+    public let workStatus: WorkStatus++    public init(+        id: UUID, displayTitle: String, readingStatus: ReadingStatus, workStatus: WorkStatus+    ) {+        self.id = id+        self.displayTitle = displayTitle+        self.readingStatus = readingStatus+        self.workStatus = workStatus+    }++    /// `WorkSnapshot.titleOrder`, the Works list's collation, through its one+    /// body.+    public static func titleOrder(_ left: WorkSummary, _ right: WorkSummary) -> Bool {+        WorkSnapshot.titleOrder(left.displayTitle, left.id, right.displayTitle, right.id)+    }+}++/// What a page is already in the library as (`app-intents` Req 3.5).+public enum PageMatch: Sendable, Hashable {+    /// A work holds the page as its confirmed URL, or an entry of the work+    /// was captured from it (Q31).+    case work(WorkSummary)+    /// Only an entry with no work was captured from it.+    case unattachedEntry(captureTitle: String)+}++/// What `createWorkUnlessPresent` did.+public enum CreateWorkOutcome: Sendable, Equatable {+    case created(WorkSnapshot)+    /// The page was already in the library when the write was attempted, and+    /// nothing was written.+    case present(PageMatch)+}++extension LibraryRepository {++    // MARK: - The add intent (Reqs 3.4–3.6)++    /// Whether `rawURL` is already in the library, and as what (Req 3.5).+    ///+    /// Refused with `invalidInput` for a URL that is not HTTP(S) or has no+    /// host, as capture refuses it.+    public func pageMatch(rawURL: String) async throws -> PageMatch? {+        let hostname = try Self.pageHostname(rawURL)+        return try await withLockedContext(mode: .shared, operation: "matching a page") {+            context in+            try Self.pageMatch(rawURL: rawURL, hostname: hostname, context: context)+        }+    }++    /// `createWork`, unless the draft's URL is already in the library by then+    /// (Reqs 3.4, 3.5).+    ///+    /// The check and the write run under **one exclusive lock and one save**,+    /// so a capture or a work committed after the intent's own `pageMatch` —+    /// while the reader was confirming the title — still prevents the+    /// creation. Everything else is `createWork`'s: the same refusals before+    /// the lock, and the same body under it. A draft holding a bare hostname+    /// names no page, so there is nothing to match and it is created as+    /// `createWork` would create it.+    public func createWorkUnlessPresent(_ draft: NewWorkDraft) async throws -> CreateWorkOutcome {+        let (hostname, workURL) = try Self.validatedNewWork(draft)+        let pageHostname = try workURL.map(Self.pageHostname)+        return try await withLockedContext(+            mode: .exclusive, operation: "creating Work unless present"+        ) { context in+            if let workURL, let pageHostname,+               let match = try Self.pageMatch(+                   rawURL: workURL, hostname: pageHostname, context: context)+            {+                return .present(match)+            }+            return .created(+                try self.insertWork(draft, hostname: hostname, workURL: workURL, context: context))+        }+    }++    /// The host a page is matched within, from the URL as capture derives it.+    private static func pageHostname(_ rawURL: String) throws -> String {+        do {+            // Both, as `captureLookup` does: the key is what the work arm+            // compares, and a URL it cannot read is not a page.+            _ = try EntryIdentityNormalizer.key(forRawURL: rawURL)+            return try HostnameNormalizer.fromRawURL(rawURL)+        } catch {+            throw LibraryRepositoryError.invalidInput(+                operation: "matching a page", reason: String(describing: error))+        }+    }++    /// Req 3.5's two arms, within the page's host.+    ///+    /// - **Works:** the capture URL key of each confirmed Work URL on the host+    ///   against the page's (Q35). Work URLs are stored as typed, so a raw+    ///   comparison would miss scheme and host case, trackers and an added+    ///   `https://`; a trailing slash or a fragment is still a different page,+    ///   as it is for capture.+    /// - **Entries:** capture's own match, through `captureCandidates`, so the+    ///   intent and the share sheet cannot disagree about a chapter.+    ///+    /// A work wins over an unattached entry, and an entry with a work reports+    /// the work (Q31). Among works the first in title order is named; among+    /// unattached entries, the least by UUID, so the answer is deterministic.+    static func pageMatch(+        rawURL: String, hostname: String, context: ModelContext+    ) throws -> PageMatch? {+        let pageKey = try EntryIdentityNormalizer.key(forRawURL: rawURL)+        var workIDs: Set<UUID> = []++        let memberships = try context.fetch(+            FetchDescriptor<WorkSiteMembership>(+                predicate: #Predicate { $0.hostname == hostname }))+        for membership in memberships {+            // No `work != nil` clause: `workID` is kept while the relationship+            // is nil (`multi-site-works` Q37) and is the key preferred below. A `workID` with no+            // Work row is dropped by the `workSummaries(rows)` fetch, so a+            // dangling reference is tolerated and never named.+            // `try?`: a stored URL this parser cannot read is not this page.+            guard let stored = membership.workURLString,+                  (try? EntryIdentityNormalizer.key(forRawURL: stored)) == pageKey,+                  let workID = membership.workID ?? membership.work?.id+            else { continue }+            workIDs.insert(workID)+        }++        let entries = try captureMatches(+            candidates: captureCandidates(+                rawURL: rawURL, hostname: hostname, captureTitle: nil, context: context),+            hostname: hostname, context: context)+        var unattached: [EntryGroup] = []+        for group in entryGroups(+            entries, canonicalWorkIDs: try canonicalWorkIDs(normalising: entries, context: context)+        ).values {+            if let workID = group.carrier.work?.id {+                workIDs.insert(workID)+            } else {+                unattached.append(group)+            }+        }++        if !workIDs.isEmpty {+            let rows = try fetchWorks(ids: Array(workIDs), context: context)+            if let first = try workSummaries(rows, context: context).values+                .min(by: WorkSummary.titleOrder)+            {+                return .work(first)+            }+        }+        return unattached+            .min { $0.id.uuidString.lowercased() < $1.id.uuidString.lowercased() }+            .map { .unattachedEntry(captureTitle: $0.representative.captureTitle) }+    }++    // MARK: - Work summaries (Req 5)++    /// The works with these ids, in the order asked, each once. An id with no+    /// row — never stored, or collapsed into another work — is omitted, which+    /// is what lets the system report a saved work as not found (Reqs 4.4, 5.3).+    public func workSummaries(ids: [UUID]) async throws -> [WorkSummary] {+        let wanted = Array(Set(ids))+        guard !wanted.isEmpty else { return [] }+        let byID = try await withLockedContext(+            mode: .shared, operation: "reading work summaries"+        ) { context -> [UUID: WorkSummary] in+            try Self.workSummaries(Self.fetchWorks(ids: wanted, context: context), context: context)+        }+        var seen: Set<UUID> = []+        return ids.compactMap { id in+            guard seen.insert(id).inserted else { return nil }+            return byID[id]+        }+    }++    /// Every Work row whose id is one of `ids`, fetched in chunks of the bulk+    /// batch size so the `IN` list of one fetch stays bounded.+    static func fetchWorks(ids: [UUID], context: ModelContext) throws -> [Work] {+        var rows: [Work] = []+        for slice in chunks(of: ids, size: bulkOperationBatchSize) {+            let chunk = Array(slice)+            rows += try context.fetch(+                FetchDescriptor<Work>(predicate: #Predicate { chunk.contains($0.id) }))+        }+        return rows+    }++    /// Every work whose display title contains `text`, compared case- and+    /// diacritic-insensitively, whatever its statuses, in title order+    /// (Req 5.2). A blank `text` matches every work.+    public func workSummaries(titleContaining text: String) async throws -> [WorkSummary] {+        let needle = text.trimmingCharacters(in: .whitespacesAndNewlines)+        return try await allWorkSummaries(operation: "finding works by title") { summary in+            needle.isEmpty+                || summary.displayTitle.range(+                    of: needle, options: [.caseInsensitive, .diacriticInsensitive]) != nil+        }+    }++    /// Every work whose reading status is one of `readingStatuses`, in title+    /// order — the works Siri takes a spoken name for (Req 5.4).+    public func workSummaries(+        readingStatuses: Set<ReadingStatus>+    ) async throws -> [WorkSummary] {+        try await allWorkSummaries(operation: "reading works by status") {+            readingStatuses.contains($0.readingStatus)+        }+    }++    /// The whole Work table as summaries, filtered and in title order.+    ///+    /// **Work rows only.** The filter is on presented fields, so it runs after+    /// the grouping rather than in a predicate: a torn group's rows can+    /// disagree about exactly the title and the status being matched.+    private func allWorkSummaries(+        operation: String, _ isIncluded: @escaping @Sendable (WorkSummary) -> Bool+    ) async throws -> [WorkSummary] {+        try await withLockedContext(mode: .shared, operation: operation) { context in+            try Self.workSummaries(context.fetch(FetchDescriptor<Work>()), context: context)+                .values+                .filter(isIncluded)+                .sorted(by: WorkSummary.titleOrder)+        }+    }++    /// One summary per UUID group, presented from the row `WorkSnapshot`+    /// presents a group from: the carrier, which for a single row is the row+    /// itself (Q41 of `duplicate-reconciliation`). Nothing here reads a work's+    /// entries.+    ///+    /// **A single-row bucket takes a fast path**, as `storyPositionInputs`+    /// does (Q34 of `character-ranking`): its row is its own carrier, so the+    /// summary is the row's own fields. Grouping it would build authored content+    /// for every row — faulting each work's site memberships — to answer a+    /// question only a duplicated work can make interesting. Only a bucket of+    /// more than one row is grouped, and the type directory is fetched only+    /// when there is one.+    static func workSummaries(+        _ rows: [Work], context: ModelContext+    ) throws -> [UUID: WorkSummary] {+        let buckets = Dictionary(grouping: rows, by: \.id)+        var types: WorkTypeDirectory?+        var summaries: [UUID: WorkSummary] = [:]+        for (id, rows) in buckets {+            guard rows.count > 1 else {+                summaries[id] = summary(rows[0])+                continue+            }+            if types == nil { types = try workTypeDirectory(context: context) }+            guard let types, let group = workGroup(id: id, rows: rows, types: types) else {+                continue+            }+            summaries[id] = summary(group.carrier)+        }+        return summaries+    }++    private static func summary(_ presented: Work) -> WorkSummary {+        WorkSummary(+            id: presented.id, displayTitle: presented.displayTitle,+            readingStatus: presented.readingStatus, workStatus: presented.workStatus)+    }++}
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift Modified +64 / -39
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex d063a67e..03a3aa6d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -1133,6 +1133,22 @@ public actor LibraryRepository {     }      public func createWork(_ draft: NewWorkDraft) async throws -> WorkSnapshot {+        let (hostname, workURL) = try Self.validatedNewWork(draft)+        return try await withLockedContext(mode: .exclusive, operation: "creating Work") { context in+            try self.insertWork(draft, hostname: hostname, workURL: workURL, context: context)+        }+    }++    /// The New Work form's refusals, made before the lock is taken: a blank+    /// title, neither form in the site-or-URL field, and a URL whose host+    /// disagrees with the one it derives. Returns the hostname the work is+    /// created on and the Work URL to store, if the field held a URL.+    ///+    /// Shared with `createWorkUnlessPresent` (`app-intents` Req 3.6), so the+    /// add intent refuses exactly what the form refuses.+    static func validatedNewWork(+        _ draft: NewWorkDraft+    ) throws -> (hostname: String, workURL: String?) {         guard !draft.displayTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {             throw LibraryRepositoryError.invalidInput(operation: "creating Work", reason: "display title is blank")         }@@ -1176,47 +1192,56 @@ public actor LibraryRepository {                     reason: "That address is on a host this library cannot read, not \(hostname).")             }         }+        return (hostname, workURL)+    } -        return try await withLockedContext(mode: .exclusive, operation: "creating Work") { context in-            let site = try Self.siteForWrite(hostname: hostname, context: context)-            let timestamp = MillisecondInstant.quantize(clock.now())-            // The Work points at the row the lookup returned — or at the one this-            // call inserted, never at whichever row a later fetch would order-            // first (Req 1.4) — and is born holding its first site membership-            // (Req 1.3).-            let work = Work.create(-                in: context, title: draft.displayTitle, hostname: hostname, site: site,-                timestamp: timestamp)-            // `to-read` [2.1](../../../../specs/to-read/requirements.md#2.1),-            // before the one save this call already makes. `Work.create` is-            // deliberately left alone: every other creation path goes through it-            // — Move To a new work, the capture commit's `.create` arm, import —-            // and none of them may mint a to-read work-            // ([2.2](../../../../specs/to-read/requirements.md#2.2)).-            work.readingStatus = draft.readingStatus-            // Req 4: a URL the reader typed into the form is reader-confirmed,-            // the standing a manual replacement on the work detail has, so it-            // is stored as this membership's Work URL as typed — query,-            // fragment, scheme case and userinfo kept (Q8) — with the assumed-            // `https://` where the scheme was omitted. Beside the reading-            // status and for its reason: `Work.create` is the one door every-            // other creation path goes through, and none of them carries a URL.-            if let workURL { work.membership(for: hostname)?.workURLString = workURL }-            do { try saveStrategy.save(context) }-            catch {-                throw LibraryRepositoryError.libraryUnavailable(-                    operation: "atomically saving Work and Site",-                    reason: String(describing: error)-                )-            }-            return try Self.snapshot(-                work, types: Self.workTypeDirectory(context: context),-                series: Self.seriesDirectory(context: context),-                // A Work created this instant carries no credit: credits are-                // authored on the work's detail, which this snapshot is the way-                // to (`work-creators` Decision 6).-                credits: .empty)+    /// `createWork`'s write, inside a lock the caller holds: the work, its+    /// site where the library has none yet, and one save.+    ///+    /// A body rather than the whole method so `createWorkUnlessPresent` can run+    /// its duplicate check and this write under one exclusive lock and one+    /// save (`app-intents` Req 3.5).+    func insertWork(+        _ draft: NewWorkDraft, hostname: String, workURL: String?, context: ModelContext+    ) throws -> WorkSnapshot {+        let site = try Self.siteForWrite(hostname: hostname, context: context)+        let timestamp = MillisecondInstant.quantize(clock.now())+        // The Work points at the row the lookup returned — or at the one this+        // call inserted, never at whichever row a later fetch would order+        // first (Req 1.4) — and is born holding its first site membership+        // (Req 1.3).+        let work = Work.create(+            in: context, title: draft.displayTitle, hostname: hostname, site: site,+            timestamp: timestamp)+        // `to-read` [2.1](../../../../specs/to-read/requirements.md#2.1),+        // before the one save this call already makes. `Work.create` is+        // deliberately left alone: every other creation path goes through it+        // — Move To a new work, the capture commit's `.create` arm, import —+        // and none of them may mint a to-read work+        // ([2.2](../../../../specs/to-read/requirements.md#2.2)).+        work.readingStatus = draft.readingStatus+        // Req 4: a URL the reader typed into the form is reader-confirmed,+        // the standing a manual replacement on the work detail has, so it+        // is stored as this membership's Work URL as typed — query,+        // fragment, scheme case and userinfo kept (Q8) — with the assumed+        // `https://` where the scheme was omitted. Beside the reading+        // status and for its reason: `Work.create` is the one door every+        // other creation path goes through, and none of them carries a URL.+        if let workURL { work.membership(for: hostname)?.workURLString = workURL }+        do { try saveStrategy.save(context) }+        catch {+            throw LibraryRepositoryError.libraryUnavailable(+                operation: "atomically saving Work and Site",+                reason: String(describing: error)+            )         }+        return try Self.snapshot(+            work, types: Self.workTypeDirectory(context: context),+            series: Self.seriesDirectory(context: context),+            // A Work created this instant carries no credit: credits are+            // authored on the work's detail, which this snapshot is the way+            // to (`work-creators` Decision 6).+            credits: .empty)     }      /// The Works list and the unattached Entries beside it, both bucketed into
Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift Modified +11 / -2
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swiftindex 91c44997..bdeeb9b9 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Snapshots.swift@@ -216,10 +216,19 @@ public struct WorkSnapshot: Equatable, Sendable {     /// waiting to disagree with the first. A strict total order, so     /// `sorted { titleOrder($1, $0) }` is exactly its reverse.     public static func titleOrder(_ left: WorkSnapshot, _ right: WorkSnapshot) -> Bool {-        switch left.displayTitle.localizedStandardCompare(right.displayTitle) {+        titleOrder(left.displayTitle, left.id, right.displayTitle, right.id)+    }++    /// The same collation over a title and an id, for a value that carries+    /// only those two — `WorkSummary` (`app-intents`). One body, so the two+    /// orders cannot drift apart.+    static func titleOrder(+        _ leftTitle: String, _ leftID: UUID, _ rightTitle: String, _ rightID: UUID+    ) -> Bool {+        switch leftTitle.localizedStandardCompare(rightTitle) {         case .orderedAscending: return true         case .orderedDescending: return false-        default: return left.id.uuidString.lowercased() < right.id.uuidString.lowercased()+        default: return leftID.uuidString.lowercased() < rightID.uuidString.lowercased()         }     } 
Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swift Added +320 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swiftnew file mode 100644index 00000000..b5afd100--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swift@@ -0,0 +1,320 @@+import Foundation+import Testing++@testable import AsterismCore++/// The two read-only intents' answers (`app-intents` Reqs 1 and 2), as pure+/// functions over the Today read.+///+/// Every expectation that names a set or an order is stated against+/// `TodayDayPlan.build` itself rather than a hand-written list, because Req 1.4+/// is an equality with the Today screen: the answer is right exactly when it is+/// the plan the screen would draw for the same day.+@Suite("Intent answers")+struct IntentAnswersTests {++    // MARK: - Fixtures++    private static func calendar() -> Calendar {+        var calendar = Calendar(identifier: .gregorian)+        calendar.timeZone = TimeZone(identifier: "UTC")!+        return calendar+    }++    private static func instant(+        _ year: Int, _ month: Int, _ dayOfMonth: Int, hour: Int = 12, minute: Int = 0+    ) -> Date {+        let components = DateComponents(+            year: year, month: month, day: dayOfMonth, hour: hour, minute: minute)+        guard let date = Self.calendar().date(from: components) else {+            preconditionFailure("\(year)-\(month)-\(dayOfMonth) does not exist in UTC")+        }+        return date+    }++    private static func day(_ year: Int, _ month: Int, _ dayOfMonth: Int) -> CivilDay {+        CivilDay(Self.instant(year, month, dayOfMonth), calendar: Self.calendar())+    }++    /// 2026-03-12 is a Thursday.+    private static let thursday = Self.day(2026, 3, 12)++    private static func id(_ index: Int) -> UUID {+        UUID(uuidString: String(format: "%08X-0000-4000-8000-000000000000", index))!+    }++    private static func entry(+        id: UUID = UUID(), sharedAt: Date, chapterTitle: String? = nil+    ) -> EntrySnapshot {+        EntrySnapshot(+            id: id, captureTitle: "capture", captureTitleSource: .host,+            rawURLString: "https://example.test/1", canonicalURLString: nil,+            hostname: "example.test", entryIdentityKey: "k", identityKeyVersion: 1,+            chapterTitle: chapterTitle, chapterTitleProvenance: .absent, note: "",+            rating: nil, firstCapturedAt: sharedAt, lastSharedAt: sharedAt,+            modifiedAt: sharedAt, workID: nil, workAssignmentProvenance: .absent,+            intentionallyUnattached: false, chapterSequence: nil)+    }++    private static func work(+        id: UUID, title: String, releaseDays: [ReleaseDay],+        readingStatus: ReadingStatus = .reading, entries: [EntrySnapshot] = []+    ) -> WorkSnapshot {+        WorkSnapshot(+            id: id, displayTitle: title, lastParsedTitle: nil,+            memberships: [WorkSiteMembershipSnapshot(id: UUID(), hostname: "example.test")],+            genericNotes: "", genreTags: [], titleProvenance: .parsed,+            createdAt: .distantPast, modifiedAt: .distantPast, entries: entries,+            readingStatus: readingStatus, releaseDays: releaseDays)+    }++    private static func row(+        id: UUID = UUID(), sharedAt: Date, captureTitle: String = "capture",+        workTitle: String? = nil, chapterTitle: String? = nil, note: String = ""+    ) -> TodayPresentationRow {+        TodayPresentationRow(+            id: id, entry: Self.entry(id: id, sharedAt: sharedAt), captureTitle: captureTitle,+            hostname: "example.test", workDisplayTitle: workTitle, chapterTitle: chapterTitle,+            unresolvedCandidateTitle: nil, siteMode: .taught, isActionable: false,+            actionType: .none, note: note, rating: nil, lastSharedAt: sharedAt)+    }++    /// A presentation as the read builds it: groups newest day first, and the+    /// schedule built from the works snapshot.+    private static func presentation(+        works: [WorkSnapshot], days: [(CivilDay, [TodayPresentationRow])]+    ) -> TodayPresentation {+        let calendar = Self.calendar()+        return TodayPresentation(+            groups: days.map {+                TodayPresentationGroup(day: $0.0.date(in: calendar), calendar: calendar, rows: $0.1)+            },+            actionableCount: 0,+            schedule: TodaySchedule.build(works: works, calendar: calendar))+    }++    /// The library every release case reads: works due on several weekdays, a+    /// catch-up work and a to-read work due on Thursday, and one Thursday work+    /// noted on Thursday.+    private static let works: [WorkSnapshot] = [+        Self.work(+            id: Self.id(1), title: "Zephyr", releaseDays: [.thursday],+            entries: [Self.entry(sharedAt: Self.instant(2026, 3, 12), chapterTitle: "Ch. 9")]),+        Self.work(id: Self.id(2), title: "Anchor", releaseDays: [.thursday, .monday]),+        Self.work(id: Self.id(3), title: "Marrow", releaseDays: [.friday]),+        Self.work(+            id: Self.id(4), title: "Behind", releaseDays: [.thursday],+            readingStatus: .catchingUp),+        Self.work(+            id: Self.id(5), title: "Planned", releaseDays: [.thursday], readingStatus: .toRead),+        Self.work(+            id: Self.id(6), title: "Lately", releaseDays: [.thursday],+            entries: [Self.entry(sharedAt: Self.instant(2026, 3, 11), chapterTitle: "Ch. 2")]),+    ]++    // MARK: - Chapters releasing today (Req 1)++    /// Reqs 1.1 and 1.4: for every weekday of one week, the answer is the plan's+    /// release rows, in the plan's order, and nothing else.+    @Test("Releasing today equals the plan's release rows on every weekday")+    func releasingTodayEqualsThePlan() {+        let calendar = Self.calendar()+        let presentation = Self.presentation(works: Self.works, days: [])+        for offset in 0..<7 {+            let day = Self.thursday.adding(days: offset, calendar: calendar)+            let plan = TodayDayPlan.build(+                day: day, currentDay: day, schedule: presentation.schedule,+                presentation: presentation, calendar: calendar)+            let answer = IntentAnswers.releasingToday(+                presentation, currentDay: day, calendar: calendar)+            #expect(answer.map(\.workID) == plan.releases.map(\.id), "on \(day)")+            #expect(answer.map(\.title) == plan.releases.map(\.title), "on \(day)")+        }+    }++    /// Q10 and the to-read spec: a catch-up work is listed by Today every day in+    /// its own section and a to-read work in none, so neither is due today even+    /// on its own release weekday.+    @Test("Releasing today excludes catching-up and to-read works")+    func releasingTodayExcludesCatchUpAndToRead() {+        let calendar = Self.calendar()+        let answer = IntentAnswers.releasingToday(+            Self.presentation(works: Self.works, days: []), currentDay: Self.thursday,+            calendar: calendar)+        #expect(answer.map(\.title) == ["Anchor", "Lately", "Zephyr"])+        #expect(!answer.contains { $0.title == "Behind" || $0.title == "Planned" })+    }++    /// Req 1.1's second half: noted today is the plan's `.notedOnDay` arm, so a+    /// work noted yesterday is not.+    @Test("notedToday is the plan's noted-on-day line")+    func notedTodayFollowsTheLine() {+        let answer = IntentAnswers.releasingToday(+            Self.presentation(works: Self.works, days: []), currentDay: Self.thursday,+            calendar: Self.calendar())+        let noted = Dictionary(uniqueKeysWithValues: answer.map { ($0.title, $0.notedToday) })+        #expect(noted == ["Anchor": false, "Lately": false, "Zephyr": true])+    }++    /// Req 1.4's midnight clause: an open Today screen may still show the+    /// previous day, but the intent is answered for the day it runs on. The+    /// presentation below was published on Thursday and holds only Thursday's+    /// rows; asked for Friday it answers Friday's releases, and Thursday's note+    /// does not make anything noted today.+    @Test("A current day minted after midnight gives that day's answer")+    func afterMidnightAnswersTheNewDay() {+        let calendar = Self.calendar()+        let friday = Self.thursday.adding(days: 1, calendar: calendar)+        let presentation = Self.presentation(+            works: Self.works,+            days: [(Self.thursday, [Self.row(sharedAt: Self.instant(2026, 3, 12), note: "x")])])++        let releases = IntentAnswers.releasingToday(+            presentation, currentDay: friday, calendar: calendar)+        #expect(releases.map(\.title) == ["Marrow"])+        #expect(releases.allSatisfy { !$0.notedToday })+        #expect(IntentAnswers.notesToday(presentation, currentDay: friday, calendar: calendar)+            .isEmpty)+    }++    // MARK: - Notes from today (Req 2)++    /// Reqs 2.1 and 2.2: the noted section's order, future-dated rows first, with+    /// blank and whitespace-only notes left out.+    @Test("Notes today keep the noted section's order and drop blank notes")+    func notesTodayKeepTheOrderAndDropBlanks() {+        let calendar = Self.calendar()+        let future = Self.row(+            sharedAt: Self.instant(2026, 3, 14), workTitle: "Future", note: "ahead")+        let first = Self.row(+            sharedAt: Self.instant(2026, 3, 12, hour: 18), workTitle: "First", note: "one")+        let blank = Self.row(sharedAt: Self.instant(2026, 3, 12, hour: 15), workTitle: "Blank")+        let spaces = Self.row(+            sharedAt: Self.instant(2026, 3, 12, hour: 14), workTitle: "Spaces", note: " \n\t ")+        let second = Self.row(+            sharedAt: Self.instant(2026, 3, 12, hour: 9), workTitle: "Second", note: "two")+        let yesterday = Self.row(+            sharedAt: Self.instant(2026, 3, 11), workTitle: "Yesterday", note: "old")+        let presentation = Self.presentation(+            works: [],+            days: [+                (Self.day(2026, 3, 14), [future]),+                (Self.thursday, [first, blank, spaces, second]),+                (Self.day(2026, 3, 11), [yesterday]),+            ])++        let plan = TodayDayPlan.build(+            day: Self.thursday, currentDay: Self.thursday, schedule: presentation.schedule,+            presentation: presentation, calendar: calendar)+        let notes = IntentAnswers.notesToday(+            presentation, currentDay: Self.thursday, calendar: calendar)++        #expect(notes.map(\.title) == ["Future", "First", "Second"])+        #expect(notes.map(\.note) == ["ahead", "one", "two"])+        // The same order as the section the screen draws, minus the blanks.+        let kept = plan.noted?.rows.filter {+            !$0.note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+        }+        #expect(notes.map(\.entryID) == kept?.map(\.id))+    }++    /// Req 2.1's fallbacks, Q18: an unattached entry is named by its capture+    /// title, and the chapter line is the row's chapter title — which the read+    /// has already made title-else-sequence — or nothing.+    @Test("An unattached entry is named by its capture title, and the chapter line may be absent")+    func notesTodayFallBack() {+        let calendar = Self.calendar()+        let attached = Self.row(+            sharedAt: Self.instant(2026, 3, 12, hour: 18), captureTitle: "Page title",+            workTitle: "A Serial", chapterTitle: "Chapter 3", note: "good")+        let unattached = Self.row(+            sharedAt: Self.instant(2026, 3, 12, hour: 9), captureTitle: "Loose page",+            note: "hm")+        let notes = IntentAnswers.notesToday(+            Self.presentation(works: [], days: [(Self.thursday, [attached, unattached])]),+            currentDay: Self.thursday, calendar: calendar)++        #expect(notes == [+            NoteAnswer(entryID: attached.id, title: "A Serial", chapterLine: "Chapter 3", note: "good"),+            NoteAnswer(entryID: unattached.id, title: "Loose page", chapterLine: nil, note: "hm"),+        ])+    }++    // MARK: - Dialogs (Reqs 1.2, 2.3, 2.4)++    private static func releases(_ count: Int) -> [ReleaseAnswer] {+        (1...max(count, 1)).prefix(count).map {+            ReleaseAnswer(workID: Self.id($0), title: "Work \($0)", notedToday: $0 == 1)+        }+    }++    private static func notes(_ count: Int) -> [NoteAnswer] {+        (1...max(count, 1)).prefix(count).map {+            NoteAnswer(+                entryID: Self.id($0), title: "Work \($0)",+                chapterLine: $0 == 2 ? nil : "Ch. \($0)", note: "note \($0)")+        }+    }++    @Test("The empty answers are the fixed sentences")+    func emptyDialogs() {+        let releases = IntentAnswers.dialog(for: [ReleaseAnswer]())+        #expect(releases.full == "No chapters are expected today.")+        #expect(releases.supporting == "No chapters are expected today.")+        let notes = IntentAnswers.dialog(for: [NoteAnswer]())+        #expect(notes.full == "There are no notes from today.")+        #expect(notes.supporting == "There are no notes from today.")+    }++    @Test("One item is named, with its noted flag or chapter line")+    func oneItemDialogs() {+        let releases = IntentAnswers.dialog(for: Self.releases(1))+        #expect(releases.full == "1 chapter is expected today: Work 1, already noted.")+        #expect(releases.supporting == "1 chapter is expected today.")+        let notes = IntentAnswers.dialog(for: Self.notes(1))+        #expect(notes.full == "You made 1 note today.\nWork 1, Ch. 1: note 1")+        #expect(notes.supporting == "You made 1 note today.")+    }++    @Test("Five items are all named")+    func fiveItemDialogs() {+        let releases = IntentAnswers.dialog(for: Self.releases(5))+        #expect(+            releases.full+                == "5 chapters are expected today: Work 1, already noted; Work 2; Work 3; Work 4; and Work 5.")+        #expect(releases.supporting == "5 chapters are expected today.")+        let notes = IntentAnswers.dialog(for: Self.notes(5))+        #expect(+            notes.full == """+                You made 5 notes today.+                Work 1, Ch. 1: note 1+                Work 2: note 2+                Work 3, Ch. 3: note 3+                Work 4, Ch. 4: note 4+                Work 5, Ch. 5: note 5+                """)+    }++    /// Req 2.4 (and the same cut for releases, Q11): above five the dialog+    /// gives the count and the first five in order.+    @Test("Six items give the count and the first five")+    func sixItemDialogs() {+        let releases = IntentAnswers.dialog(for: Self.releases(6))+        #expect(+            releases.full+                == "6 chapters are expected today. The first five: Work 1, already noted; Work 2; Work 3; Work 4; and Work 5.")+        #expect(!releases.full.contains("Work 6"))+        #expect(releases.supporting == "6 chapters are expected today.")+        let notes = IntentAnswers.dialog(for: Self.notes(6))+        #expect(+            notes.full == """+                You made 6 notes today. The first five:+                Work 1, Ch. 1: note 1+                Work 2: note 2+                Work 3, Ch. 3: note 3+                Work 4, Ch. 4: note 4+                Work 5, Ch. 5: note 5+                """)+        #expect(notes.supporting == "You made 6 notes today.")+    }+}
Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift Added +424 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swiftnew file mode 100644index 00000000..0339335c--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift@@ -0,0 +1,424 @@+import Foundation+import SwiftData+import Testing++@testable import AsterismCore++/// The repository reads the intents resolve works through (`app-intents`+/// Req 5), and the add intent's duplicate check and commit (Req 3.4–3.6).+@Suite("Intent reads", .serialized)+struct IntentReadsTests {++    // MARK: - workSummaries (Req 5)++    /// One summary per UUID group, and it is the group the Works list presents:+    /// a torn same-UUID pair whose rows disagree about the title and the reading+    /// status is one summary, carrying what `works()` shows for it.+    @Test("One summary per work group, presented as the Works list presents it")+    func oneSummaryPerGroup() async throws {+        let fixture = try await IntentReadsFixture()+        let torn = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Torn", hostname: "example.com"))+        _ = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Plain", hostname: "other.example"))+        try await fixture.seedTwin(of: torn.id, title: "Torn, other copy", readingStatus: .finished)++        let listed = try await fixture.repository.works().works+        let summaries = try await fixture.repository.workSummaries(ids: listed.map(\.id))++        #expect(summaries.count == 2)+        #expect(Set(summaries.map(\.id)).count == 2)+        for work in listed {+            let summary = try #require(summaries.first { $0.id == work.id })+            #expect(summary.displayTitle == work.displayTitle)+            #expect(summary.readingStatus == work.readingStatus)+            #expect(summary.workStatus == work.workStatus)+        }+        // The torn group really is torn: otherwise the case proves nothing.+        #expect(listed.first { $0.id == torn.id }?.groupState.isTorn == true)+    }++    /// Req 5.2: contains, case- and diacritic-insensitive, finished and+    /// abandoned works included, in the Works list's title order.+    @Test("titleContaining matches case- and diacritic-insensitively, in title order")+    func titleContainingMatchesLoosely() async throws {+        let fixture = try await IntentReadsFixture()+        for title in ["La Mère", "Mereland", "A Merest Chance", "Other"] {+            _ = try await fixture.repository.createWork(+                NewWorkDraft(displayTitle: title, hostname: "example.com"))+        }+        try await fixture.setReadingStatus(.abandoned, ofTitle: "Mereland")++        let lower = try await fixture.repository.workSummaries(titleContaining: "mere")+        #expect(lower.map(\.displayTitle) == ["A Merest Chance", "La Mère", "Mereland"])+        let accented = try await fixture.repository.workSummaries(titleContaining: "MÈRE")+        #expect(accented.map(\.displayTitle) == lower.map(\.displayTitle))+        #expect(try await fixture.repository.workSummaries(titleContaining: "nothing").isEmpty)+    }++    /// Reqs 4.4 and 5.3: an id that is not in the library — never was, or its+    /// rows went with a duplicate collapse — is omitted, and the rest keep the+    /// order they were asked for in.+    @Test("The ids read omits missing and collapsed ids")+    func idsReadOmitsMissing() async throws {+        let fixture = try await IntentReadsFixture()+        let kept = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Kept", hostname: "example.com"))+        let collapsed = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Collapsed", hostname: "example.com"))+        let second = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Second", hostname: "example.com"))+        try await fixture.deleteRows(of: collapsed.id)++        let summaries = try await fixture.repository.workSummaries(+            ids: [second.id, UUID(), collapsed.id, kept.id])+        #expect(summaries.map(\.id) == [second.id, kept.id])+    }++    /// Req 5.4: the suggested works are the ones reading or catching up.+    @Test("The reading-status read returns only the statuses asked for")+    func readingStatusFilter() async throws {+        let fixture = try await IntentReadsFixture()+        for status in ReadingStatus.allCases {+            _ = try await fixture.repository.createWork(+                NewWorkDraft(displayTitle: "\(status)", hostname: "example.com"))+            try await fixture.setReadingStatus(status, ofTitle: "\(status)")+        }++        let suggested = try await fixture.repository.workSummaries(+            readingStatuses: [.reading, .catchingUp])+        #expect(suggested.map(\.displayTitle) == ["catchingUp", "reading"])+        #expect(Set(suggested.map(\.readingStatus)) == [.reading, .catchingUp])+    }++    // MARK: - pageMatch (Req 3.5)++    /// Capture's own match: the raw URL against the conservative alias.+    @Test("An unattached entry matches by its raw URL")+    func entryMatchesByRawURL() async throws {+        let fixture = try await IntentReadsFixture()+        _ = try await fixture.repository.capture(+            CaptureDraft(+                captureTitle: "Chapter One", captureTitleSource: .manual,+                rawURLString: "https://example.com/chapter-1"))++        #expect(+            try await fixture.repository.pageMatch(rawURL: "https://example.com/chapter-1")+                == .unattachedEntry(captureTitle: "Chapter One"))+        #expect(try await fixture.repository.pageMatch(rawURL: "https://example.com/chapter-2") == nil)+    }++    /// Capture's other candidate: the site's URL rule identifies the chapter+    /// from a URL that is not the captured one. The entry has a work, so the+    /// work is what is reported (Q31).+    @Test("An entry matches by the site's rule candidate, and reports its work")+    func entryMatchesByRuleCandidate() async throws {+        let fixture = try await IntentReadsFixture()+        // Teaching needs the site to exist.+        _ = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Other", hostname: "example.com"))+        try await fixture.teachWorkIdentity()+        let entry = try await fixture.captureThroughRules(+            title: "A Serial", rawURL: "https://example.com/read?id=42&chapter=2")+        let workID = try #require(entry.workID)++        let match = try await fixture.repository.pageMatch(+            rawURL: "https://example.com/read?chapter=2&id=42")+        guard case .work(let summary) = match else {+            Issue.record("expected a work match, got \(String(describing: match))")+            return+        }+        #expect(summary.id == workID)+        #expect(+            try await fixture.repository.pageMatch(+                rawURL: "https://example.com/read?chapter=3&id=42") == nil)+    }++    /// Q35: a work URL is stored as typed, so the comparison is by the capture+    /// URL key on both sides — scheme and host case, a tracking parameter and+    /// the `https://` the form added all compare equal, and a fragment or a+    /// trailing slash is still a different page.+    @Test("A work matches by the capture URL key of its confirmed URL")+    func workMatchesByKey() async throws {+        let fixture = try await IntentReadsFixture()+        // Typed without a scheme: stored as `https://example.com/story`.+        let work = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Stored", hostname: "example.com/story"))+        #expect(work.memberships.first?.workURLString == "https://example.com/story")+        let expected = PageMatch.work(WorkSummary(+            id: work.id, displayTitle: "Stored", readingStatus: .reading, workStatus: .ongoing))++        for page in [+            "https://example.com/story",+            "HTTPS://Example.COM/story",+            "https://example.com/story?utm_source=feed",+        ] {+            #expect(try await fixture.repository.pageMatch(rawURL: page) == expected, "for \(page)")+        }+        for page in ["https://example.com/story#top", "https://example.com/story/"] {+            #expect(try await fixture.repository.pageMatch(rawURL: page) == nil, "for \(page)")+        }+    }++    /// `multi-site-works` Q37: a membership's `workID` is kept while its `work`+    /// relationship is nil — a row whose inverse has not arrived — and it is the+    /// key the match prefers, so such a row still names its work.+    @Test("A membership with a nil work relationship matches by its workID")+    func membershipMatchesByWorkIDWithoutRelationship() async throws {+        let fixture = try await IntentReadsFixture()+        let work = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Stored", hostname: "https://example.com/story"))+        let workID = work.id+        try await fixture.withStore { context in+            let membership = try #require(+                try context.fetch(FetchDescriptor<WorkSiteMembership>()).first)+            membership.work = nil+            membership.workID = workID+        }+        try await fixture.withStore { context in+            let membership = try #require(+                try context.fetch(FetchDescriptor<WorkSiteMembership>()).first)+            #expect(membership.work == nil)+            #expect(membership.workID == workID)+            #expect(membership.workURLString == "https://example.com/story")+        }++        let match = try await fixture.repository.pageMatch(rawURL: "https://example.com/story")+        guard case .work(let summary) = match else {+            Issue.record("expected a work match, got \(String(describing: match))")+            return+        }+        #expect(summary.id == workID)+    }++    /// Q31: the reader asked whether the work is in the library, so a work+    /// match is the answer even where an unattached capture of the page exists.+    @Test("A work match wins over an unattached entry")+    func workBeatsEntry() async throws {+        let fixture = try await IntentReadsFixture()+        _ = try await fixture.repository.capture(+            CaptureDraft(+                captureTitle: "Loose", captureTitleSource: .manual,+                rawURLString: "https://example.com/story"))+        let work = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Stored", hostname: "https://example.com/story"))++        let match = try await fixture.repository.pageMatch(rawURL: "https://example.com/story")+        guard case .work(let summary) = match else {+            Issue.record("expected a work match, got \(String(describing: match))")+            return+        }+        #expect(summary.id == work.id)+    }++    @Test("A page that is not an HTTP(S) URL is refused")+    func pageMatchRefusesNonHTTP() async throws {+        let fixture = try await IntentReadsFixture()+        await #expect(throws: LibraryRepositoryError.self) {+            try await fixture.repository.pageMatch(rawURL: "ftp://example.com/story")+        }+    }++    // MARK: - createWorkUnlessPresent (Reqs 3.4, 3.5, 3.6)++    /// Req 3.4: with no match the work is created as the New Work form creates+    /// it — to read, ongoing, the page as its confirmed URL, the site created.+    @Test("With no match it creates the work createWork would")+    func createsAsCreateWorkWould() async throws {+        let fixture = try await IntentReadsFixture()+        let outcome = try await fixture.repository.createWorkUnlessPresent(+            NewWorkDraft(+                displayTitle: "A Serial", hostname: "https://Example.com/story?id=7",+                readingStatus: .toRead))++        guard case .created(let created) = outcome else {+            Issue.record("expected a creation, got \(outcome)")+            return+        }+        #expect(created.displayTitle == "A Serial")+        #expect(created.readingStatus == .toRead)+        #expect(created.workStatus == .ongoing)+        #expect(created.memberships.map(\.hostname) == ["example.com"])+        #expect(created.memberships.first?.workURLString == "https://Example.com/story?id=7")+        let counts = try await fixture.repository.debugCounts()+        #expect(counts.works == 1)+        #expect(counts.sites == 1)+        #expect(try await fixture.repository.works().works.map(\.id) == [created.id])+    }++    /// Req 3.5's last clause: the check is repeated when the work is written,+    /// so a capture committed after the intent's first look still prevents the+    /// creation. Here the first look never happened at all.+    @Test("A match committed before the write makes it answer present")+    func matchAtCommitPreventsCreation() async throws {+        let fixture = try await IntentReadsFixture()+        _ = try await fixture.repository.capture(+            CaptureDraft(+                captureTitle: "Chapter One", captureTitleSource: .manual,+                rawURLString: "https://example.com/chapter-1"))++        let outcome = try await fixture.repository.createWorkUnlessPresent(+            NewWorkDraft(+                displayTitle: "A Serial", hostname: "https://example.com/chapter-1",+                readingStatus: .toRead))++        #expect(outcome == .present(.unattachedEntry(captureTitle: "Chapter One")))+        #expect(try await fixture.repository.debugCounts().works == 0)+    }++    @Test("An existing work makes it answer present with that work")+    func existingWorkIsPresent() async throws {+        let fixture = try await IntentReadsFixture()+        let work = try await fixture.repository.createWork(+            NewWorkDraft(displayTitle: "Stored", hostname: "https://example.com/story"))++        let outcome = try await fixture.repository.createWorkUnlessPresent(+            NewWorkDraft(+                displayTitle: "Again", hostname: "https://example.com/story?utm_source=x",+                readingStatus: .toRead))++        #expect(outcome == .present(.work(WorkSummary(+            id: work.id, displayTitle: "Stored", readingStatus: .reading, workStatus: .ongoing))))+        #expect(try await fixture.repository.debugCounts().works == 1)+    }++    /// Req 3.6: the New Work form's refusals are the intent's — a blank title,+    /// a URL whose host disagrees with the derived one, and a commit the save+    /// boundary refuses — and each writes nothing.+    @Test("Refusals propagate and write nothing")+    func refusalsPropagate() async throws {+        let fixture = try await IntentReadsFixture()+        for draft in [+            NewWorkDraft(+                displayTitle: "  ", hostname: "https://example.com/story", readingStatus: .toRead),+            NewWorkDraft(+                displayTitle: "Work", hostname: "https://example.com./story",+                readingStatus: .toRead),+        ] {+            await #expect(throws: LibraryRepositoryError.self) {+                try await fixture.repository.createWorkUnlessPresent(draft)+            }+        }+        let counts = try await fixture.repository.debugCounts()+        #expect(counts.works == 0)+        #expect(counts.sites == 0)++        let refusing = try await IntentReadsFixture(saveStrategy: RefusingSaveStrategy())+        await #expect(throws: LibraryRepositoryError.self) {+            try await refusing.repository.createWorkUnlessPresent(+                NewWorkDraft(+                    displayTitle: "Work", hostname: "https://example.com/story",+                    readingStatus: .toRead))+        }+        #expect(try await refusing.repository.debugCounts().works == 0)+    }+}++/// A save boundary that refuses every commit, as a gate refusing the diagnosis+/// a commit introduced does: roll back, then throw.+private struct RefusingSaveStrategy: RepositorySaveStrategy {+    func save(_ context: ModelContext) throws {+        context.rollback()+        throw CocoaError(.fileWriteUnknown)+    }+}++// MARK: - Fixture++private struct IntentReadsFixture {+    let directory: IntentReadsTemporaryDirectory+    let configuration: LibraryConfiguration+    let repository: LibraryRepository++    init(saveStrategy: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws {+        directory = try IntentReadsTemporaryDirectory()+        configuration = LibraryConfiguration(rootDirectory: directory.url)+        repository = try await LibraryRepository.openForApp(+            configuration, clock: FixedRepositoryClock(Date(timeIntervalSince1970: 100)),+            saveStrategy: saveStrategy+        ).repository+    }++    /// Teaches `example.com` a whole-title pattern and a URL rule naming the+    /// work by `id` and the chapter by `chapter`, as `RepositoryWorksTests` does.+    func teachWorkIdentity() async throws {+        let request = ComposedTeachingRequest(+            titleDefinition: .wholeTitle,+            urlDefinition: .workAndSequence(+                work: URLFieldSelector(locator: .query(name: ExactScalarString("id"))),+                sequence: URLFieldSelector(locator: .query(name: ExactScalarString("chapter")))))+        let contract = try await repository.projectComposedTeaching(+            hostname: "example.com", request: request)+        guard case .committed = try await repository.commitComposedTeaching(contract) else {+            throw CocoaError(.fileWriteUnknown)+        }+    }++    /// The taught capture path, which is the one that resolves a Work.+    func captureThroughRules(title: String, rawURL: String) async throws -> EntrySnapshot {+        let contract = try await repository.projectCapture(+            hostname: "example.com", captureTitle: title, captureTitleSource: .safariDocument,+            rawURLString: rawURL, canonicalURLString: nil, note: "", rating: nil)+        guard case .committed(let snapshot) = try await repository.commitCapture(contract) else {+            throw CocoaError(.fileWriteUnknown)+        }+        return snapshot+    }++    /// Writes straight to the store, under the library lock, the way another+    /// device's rows arrive: no repository path is involved.+    func withStore(_ body: (ModelContext) throws -> Void) async throws {+        let lease = try await CrossProcessLibraryLock.acquire(+            mode: .exclusive, at: configuration.lockURL, timeout: .seconds(1))+        defer { withExtendedLifetime(lease) {} }+        let context = ModelContext(try LibraryRepository.openContainer(at: configuration.storeURL))+        try body(context)+        try context.save()+    }++    /// A second row for `workID` with its own title and reading status: the+    /// torn group two devices produce.+    func seedTwin(of workID: UUID, title: String, readingStatus: ReadingStatus) async throws {+        try await withStore { context in+            let original = try #require(+                try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID }))+                    .first)+            let membership = try #require(original.membershipValues.first)+            let twin = Work.create(+                in: context, id: workID, title: title, hostname: membership.hostname,+                site: membership.site, timestamp: original.createdAt)+            twin.readingStatus = readingStatus+        }+    }++    func setReadingStatus(_ status: ReadingStatus, ofTitle title: String) async throws {+        try await withStore { context in+            for work in try context.fetch(+                FetchDescriptor<Work>(predicate: #Predicate { $0.displayTitle == title }))+            {+                work.readingStatus = status+            }+        }+    }++    /// Every row of one work, gone — what a collapse leaves of a loser.+    func deleteRows(of workID: UUID) async throws {+        try await withStore { context in+            for work in try context.fetch(+                FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID }))+            {+                context.delete(work)+            }+        }+    }+}++private final class IntentReadsTemporaryDirectory {+    let url: URL+    init() throws {+        url = FileManager.default.temporaryDirectory.appending(+            path: "AsterismIntentReadsTests-\(UUID())", directoryHint: .isDirectory)+        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+    }+    deinit { try? FileManager.default.removeItem(at: url) }+}
Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift Modified +81 / -0
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swiftindex fff1f50a..c6d68c43 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/M4ToleratedScalePerformanceTests.swift@@ -37,6 +37,18 @@ import Testing struct M4ToleratedScalePerformanceTests {     private let extensionOpenBudget = Duration.seconds(1)     private let todayPublishBudget = Duration.seconds(2)+    /// `app-intents` Req 6.6, and Q21's reason for 2 s rather than 1 s: the+    /// Today read alone is ~0.85 s over this fixture, so 1 s would fail on the+    /// second-slowest-of-20 percentile's noise.+    ///+    /// The budget, asserted outside any known-issue block, is the arm's only+    /// bound, as it is for `todayPublication`: the arm meets it plainly, so a+    /// separate regression ceiling would either sit above it and assert nothing,+    /// or sit under it and redefine the requirement (`app-intents` Q43). Two+    /// release runs on 2026-09-24, both on a loaded host (load average 10–24),+    /// measured `intent-releasing-today` at 0.914 s and `intent-notes-today` at+    /// 0.888–0.904 s, beside `todayPublication` at 0.911 s in the same run.+    private let intentAnswerBudget = Duration.seconds(2)     private let captureBudget = Duration.milliseconds(100)     /// **Not Req 5.4's budget.** The 100 ms above is asserted inside     /// `withKnownIssue` for the *projection* measurement only (Q18): the@@ -226,6 +238,75 @@ struct M4ToleratedScalePerformanceTests {         #expect(past.placement == .notedFirst)     } +    // MARK: - `app-intents` Req 6.6 — the two read-only intents' answers++    /// Req 6.6: "chapters releasing today", excluding the store open — the one+    /// Today read and the pure answer over it — against a 2 s median budget+    /// over the same fixture, calendar and current day as `todayPublication`.+    ///+    /// The store is opened outside the timing, because a cold open cannot be+    /// measured on the host (Q21); a cold intent pays it on top, on the device.+    @Test("Answering chapters releasing today ≤ 2 s over the M4 fixture (app-intents Req 6.6)")+    func intentReleasingToday() async throws {+        let store = try await M4PerformanceStore(state: nil)+        let repository = try await store.openApp()+        let (calendar, currentDay) = try Self.intentDay()++        let measured = try await measureDistributionAsync(iterations: iterations) {+            let presentation = try await repository.todayPresentation(calendar: calendar)+            _ = IntentAnswers.releasingToday(+                presentation, currentDay: currentDay, calendar: calendar)+        }++        expectWithinBudget("intent-releasing-today", measured, intentAnswerBudget)++        // A measurement of the answer only while there is one: an empty release+        // list would meet the budget by doing nothing.+        let answer = IntentAnswers.releasingToday(+            try await repository.todayPresentation(calendar: calendar),+            currentDay: currentDay, calendar: calendar)+        #expect(!answer.isEmpty)+    }++    /// Req 6.6's other read: "notes from today", the same shape.+    ///+    /// **The fixture's entries are bare** — none carries a note — so the answer+    /// itself is empty. What the interval holds is still the whole of the+    /// intent's work: the Today read, the plan's noted section for the current+    /// day (the fixture's shifted entries) and the blank-note filter over every+    /// row of it, which is asserted non-empty below so the arm cannot pass by+    /// reading an empty day.+    @Test("Answering notes from today ≤ 2 s over the M4 fixture (app-intents Req 6.6)")+    func intentNotesToday() async throws {+        let store = try await M4PerformanceStore(state: nil)+        let repository = try await store.openApp()+        let (calendar, currentDay) = try Self.intentDay()++        let measured = try await measureDistributionAsync(iterations: iterations) {+            let presentation = try await repository.todayPresentation(calendar: calendar)+            _ = IntentAnswers.notesToday(presentation, currentDay: currentDay, calendar: calendar)+        }++        expectWithinBudget("intent-notes-today", measured, intentAnswerBudget)++        let presentation = try await repository.todayPresentation(calendar: calendar)+        let plan = TodayDayPlan.build(+            day: currentDay, currentDay: currentDay, schedule: presentation.schedule,+            presentation: presentation, calendar: calendar)+        #expect(plan.noted?.rows.count == LibraryRepository.m4FixtureShiftedEntryCount)+    }++    /// `todayPublication`'s injected calendar and current day (Q45 of+    /// `update-schedule`), so the intent arms read the same day over the same+    /// fixture whatever the tester's region.+    private static func intentDay() throws -> (Calendar, CivilDay) {+        var calendar = Calendar(identifier: .gregorian)+        calendar.timeZone = try #require(TimeZone(identifier: "UTC"))+        let currentDay = CivilDay(+            Date(timeIntervalSince1970: LibraryRepository.m4FixtureNoteShift), calendar: calendar)+        return (calendar, currentDay)+    }+     // 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
scripts/verify-identity.sh Modified +61 / -0
diff --git a/scripts/verify-identity.sh b/scripts/verify-identity.shindex c58a4e5a..0c04897e 100755--- a/scripts/verify-identity.sh+++ b/scripts/verify-identity.sh@@ -590,6 +590,8 @@ check_targets() {         check_target_info_plist "$uuid" "$name" "$role"         if [ "$role" = "extension" ]; then             check_extension_isolation "$uuid" "$name"+        else+            check_app_display_names "$uuid" "$name"         fi     done @@ -1162,6 +1164,65 @@ check_package_model_imports() {     done <"$hits" } +# ------------------------------------------------------------------------------+# Check 7 — the app's two configurations carry different display names+#           (app-intents Req 7.3, Q25).+#+# App Shortcut phrases name the app by its display name. With both apps called+# "Asterism", a phrase spoken on a device holding both resolves to either, and+# nothing fails at build time — Siri simply picks one. The value is not pinned:+# the lint only asks that each configuration declares one, unconditionally, and+# that the two differ.+# ------------------------------------------------------------------------------++readonly DISPLAY_NAME_SETTING="INFOPLIST_KEY_CFBundleDisplayName"+readonly DISPLAY_NAME_PLIST_KEY="CFBundleDisplayName"++check_app_display_names() {+    local uuid="$1" target="$2"+    local list index config cfgname key value development="" personal=""++    list="$(pbx "objects.$uuid.buildConfigurationList")"+    [ -n "$list" ] || return  # target_setting_values already failed on this++    index=0+    while config="$(pbx "objects.$list.buildConfigurations.$index")" && [ -n "$config" ]; do+        index=$((index + 1))+        cfgname="$(object_name_of "$config")"+        value=""+        while IFS= read -r key; do+            [ -n "$key" ] || continue+            if is_conditional_key "$key"; then+                fail "$target's $cfgname configuration assigns '$key'; the display name must be unconditional, or the two apps can share a name on the platforms the condition matches (Req 7.3)"+                continue+            fi+            value="$(pbx "objects.$config.buildSettings.$DISPLAY_NAME_SETTING")"+        done <<< "$(setting_keys_in "$config" "$DISPLAY_NAME_SETTING")"++        if [ -z "$value" ]; then+            fail "$target's $cfgname configuration declares no $DISPLAY_NAME_SETTING; both apps would fall back to PRODUCT_NAME and share one name in Siri (Req 7.3)"+            continue+        fi+        case "$cfgname" in+            Development) development="$value" ;;+            Personal) personal="$value" ;;+        esac+    done++    if [ -n "$development" ] && [ "$development" = "$personal" ]; then+        fail "$target's Development and Personal configurations both declare $DISPLAY_NAME_SETTING '$development'; the two apps' phrases would resolve to either app (Req 7.3)"+    fi++    # A literal key in the target's own Info.plist outranks the generated one.+    local file+    while IFS= read -r file; do+        [ -n "$file" ] || continue+        if plutil -extract "$DISPLAY_NAME_PLIST_KEY" raw -o - "$REPO_ROOT/Asterism/$file" >/dev/null 2>&1; then+            fail "$REPO_ROOT/Asterism/$file carries $DISPLAY_NAME_PLIST_KEY; it would override both configurations' $DISPLAY_NAME_SETTING with one value (Req 7.3)"+        fi+    done <<< "$(target_setting_values "$uuid" "$target" "INFOPLIST_FILE")"+}+ # ------------------------------------------------------------------------------  check_project_level_settings

Docs (12)

CHANGELOG.md Modified +52 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex add46702..7509b72f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -236,6 +236,58 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).  ### Added +- **App Intents, phase 4: the `Development` app is Devsterism (T-2367).**+  The `Development` app's display name is now Devsterism, so Siri phrases+  that name the app reach one app when both are installed. `make+  verify-identity` fails when the two configurations declare the same+  display name or none. CLAUDE.md's configuration table shows the names,+  and its Sync section names the intent broker as the app's own+  mirroring-off opener.++- **App Intents, phase 3: the intents (T-2367).** Siri, Spotlight and+  Shortcuts get five actions with App Shortcuts phrases: Chapters Releasing+  Today and Notes from Today (answered in the background from the Today+  derivation), Add as To Read (checks the page against the library, fetches+  its title and offers it for confirmation, and creates the work only if+  the page is still absent at the write), Open Today, and Open Work. Works+  are Shortcuts values with a Find Works action, and the reading and+  catching-up works are registered as spoken names. Every intent needs an+  unlocked device, and the open intents do nothing while an edit is in+  progress. How long the cold path takes on the Mac is not measured yet;+  that run needs shortcuts made in the Shortcuts app and is listed for the+  owner.++- **App Intents, phase 2: the library broker and intent routes+  (T-2367).** `IntentLibraryBroker` is the one way an intent will reach+  the library: one step at a time in arrival order, on the resident+  repository when the app has its library open, otherwise on a one-step+  `openForExtension` session with mirroring off (or on an open+  background-export session), leaving an `ExportOwed` marker after a+  write. Bootstrap drains it before it releases a library and never+  cancels a step, and a background export skips while a step holds it.+  Cold steps log their open and step times and whether a scene was+  connected under `category:AppIntents`. `AsterismApp.init` registers the+  model and navigation for the intents. `AppNavigation` gains an intent+  route that is dropped when the reader has moved since, when an edit is+  in progress, or when the work is unknown; the editors and every local+  sheet register as edit sessions. No intent exists yet.++- **App Intents, phase 1: the Core reads and answers (T-2367).** The+  answers the Siri and Shortcuts intents will speak are now pure Core+  functions: `IntentAnswers` derives "chapters releasing today" and "notes+  from today" from `todayPresentation` and `TodayDayPlan.build` for the day+  the intent runs, so they cannot disagree with the Today screen, and+  builds their dialogs (the count and the first five above five items).+  `LibraryRepository+Intents` adds `WorkSummary` reads by id, by title and+  by reading status, fetching Work rows only; `pageMatch`, which finds a+  page as a work (by normalised work URL, membership `workID` included) or+  as an entry (by capture's own match); and `createWorkUnlessPresent`,+  which repeats that check and creates the work under one lock and one+  save. `createWork` and `captureLookup` were split so both paths share one+  body. Two M4 arms, `intent-releasing-today` (0.914 s) and+  `intent-notes-today` (0.888–0.904 s), sit under a 2 s budget. No intent+  is wired into the app yet.+ - **A site or a URL when creating a work, in the app (T-2365,   `specs/new-work-url-field/`, task 4).** The New Work form's second field   is titled "Site or URL", which the Mac draws and VoiceOver reads on
CLAUDE.md Modified +15 / -9
diff --git a/CLAUDE.md b/CLAUDE.mdindex 964d855a..c852a257 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -68,7 +68,7 @@ invocations where a target exists. - `make test-quick` — unit-test bundle only (simulator), preceded by `build-mac`: a macOS compile failure fails it (Req 9.1). The Mac build is never installed or launched. `SKIP_MAC=1` drops that dependency loudly and owes a clean `make build-mac` before the push. - `make test` / `make test-ui` — full suites (simulator, iPhone); they skip the iPad-only suites by name - `make test-ui-ipad` — the wide-layout and wide-layout-accessibility suites on `IPAD_SIMULATOR` (simulator, safe)-- `make test-performance-m4` — M4 Core budgets, host only, no device, safe to run. **~21 minutes** (1,093 s of test time measured 2026-08-28, 1,120 s over 28 tests on 2026-08-30 after `character-ranking` added its own, and **1,120.6 s over 32 tests on 2026-09-05** after T-1910 added four Work-bearing preview arms — all quiet-host runs, all `EXIT=0` with the same eight known issues, so the 21 minutes still holds and the four added arms cost no measurable wall time. T-2093 took the settling pass from ~7.3 s to ~1.7 s per sample; three contended runs on 2026-09-05 measured 1,136 s, 1,237 s and 1,085 s over the same 32 tests, all `EXIT=0` with **seven** known issues. A *loaded* run of those same 32 tests took 1,380 s and breached a regression ceiling on an untouched arm; that is host contention, not a band. Add a ~190 s release build to any of them): most of it is the worst-case single-hostname consolidation in `M4ScalePerformanceTests` (5 samples, each paying its own ~40 s divert before a ~40 s measurement) and the Req 10.1 settling pass (10 samples, each re-seeding 1,350 duplicate rows plus an untimed observation pass). The V4→V5 migration measurement is **gone** — `retire-migration-chain` deleted the pass it timed along with the suite. **The target exits 0 on a quiet host**, with the accepted breaches reported as `withKnownIssue` known issues rather than failures — **ten** since `work-thumbnails` (four before `multi-site-works`, nine after it, eight after `drop-superseded-columns`, seven after T-2093, eight after `series-and-related-works`, nine after `work-creators`), and **eleven on a loaded host**, because `creator-converge-noop` is wrapped `isIntermittent` and only records when the host is busy. Three are long-standing: Req 5.5's three diagnosis re-derivations. Three are Req 5.4's capture-projection arms (0.093–0.102 s pre-V8 → 0.160–0.170 s at V9 → 0.169–0.176 s at V10 → **0.179–0.205 s at V12** → 0.158–0.164 s at V13 on a quieter host, the one on a path the reader waits on; V12's three new tables and V13's two are empty on that path and cost it nothing the run's own host variance does not explain, still well inside a 250 ms ceiling). The seventh is the **full**-tier no-op reconcile, and V9 recovered most of it: 1.07 s → **0.0296–0.0302 s** once `V8PopulationPass` was deleted with the columns and `MembershipReconciler.heal` was gated on the diagnosis, which is still 3.0× a 10 ms ceiling drawn before the library had a membership table; V10 left it there (0.0301 s), V12 did too (0.0308 s) and so did V13 (0.0302 s). Req 10.1's *observation* pass **retired** with that fall (2.69 s → 1.01 s, back inside its 2 s budget, and 1.02 s at V10), and its **settling** pass retired at T-2093: 88% of that pass was SwiftData maintaining `Site.entries` inside the deletion phase's one `save` (6.42 s before the fix, 0.41 s after; the measured 8.0 ms per deleted row over a 5,000-row Site is supporting evidence, not the arithmetic — only the 250 Entry losers of the 300 deleted rows sit in `Site.entries`), and detaching a chunk's doomed rows from their Site in one rewrite of that array took it from 7.3 s to ~1.6 s, inside its 2 s budget, with the 11 s floor under the known issue gone too (`specs/bugfixes/settling-pass-budget/`, Decision 32). The eighth is `series-and-related-works` Req 14.6's link dedupe, a 10 ms budget measured at 0.0100–0.0112 s over 500 links — the low end is `place-extraction`'s run at 0.010032 s, 0.3% over the budget and the closest it has come to fitting, which would turn a quiet host into a *second* way to be red: the whole-table fetch the phase opens with is 79–83% of that, so the budget sits under what SwiftData charges to materialise the rows (Q59 of that spec). The ninth is `work-creators` Req 11.6's credit dedupe, a 50 ms budget measured at 0.0591–0.0651 s over ~2,000 credits, of which the whole-table fetch is 76% (Q73 of that spec, 130 ms ceiling). The intermittent eleventh is that spec's `creator-converge-noop`, in budget at 0.0081–0.0100 s against 10 ms across five samples and never more than 19% clear of it, so it is asserted `isIntermittent` with a 20 ms ceiling (Q74). The tenth is `work-thumbnails` Q80's **`backup-export-thumbnails` peak**: the real exporter over the covered fixture writes a **51.1 MB** archive and peaks **330–462 MB** over its baseline, past the 400 MB Q61 accepted from an estimate, recorded rather than re-based, with a 600 MB regression ceiling asserted outside the block. It is deliberately **not** `isIntermittent`, which means a run whose peak lands *under* 400 MB fails the target with `Known issue was not recorded` — that fired for the first time on 2026-09-13, on a memory-pressured host at 330.2 MB, and a lower peak there is the allocator reclaiming sooner, not the export getting cheaper (`specs/work-thumbnails/verification-run.md` §2.2). Its sibling `backup-import-thumbnails` **meets** the 400 MB plainly at 63.5–159.2 MB, with a settled baseline of 103–144 MB over five runs on one host (`specs/work-thumbnails/verification-run.md` §4.1), and `thumbnail-bytes-read` (fifty on-demand cover reads, Req 7.2) is reported only, 0.032–0.231 s under the 3 s class ceiling. Its other creator arms are `credits-resolve-and-filter` at 0.0144–0.0154 s under a 20 ms budget, `dedupe-credits-fetch` at 0.0477–0.0496 s reported only, `creator-detail` at 0.0363–0.0376 s under 50 ms, and the two read arms `works-snapshot-creators` (1.75–2.11 s) and `creators-list` (0.274–0.284 s) under the 3 s class ceiling. `series-and-related-works` adds `M4SeriesScalePerformanceTests`, `work-creators` adds `M4CreatorScalePerformanceTests` and `empty-library` adds `M4EmptyLibraryPerformanceTests` — one suite, one test, the `empty-library-m4` arm, which empties the covered fixture's **7,009 rows** three times over and costs the target ~50 s. Run **on its own** it measures **5.544–5.942 s** of median over five runs, every sample 5.541–6.244 s, and it is strikingly load-insensitive: those five spanned a one-minute load average of 5 to 241 and moved 7.2%, the loudest run *below* the second-loudest. Run **inside the target**, after twenty minutes of other suites have been through the page cache, the same arm reads **7.712 s** — which is why its regression ceiling is **16 s** (2.07× the in-target median) rather than the 12 s the solo band alone would have given; reported rather than budgeted (Q18 of that spec). `specs/empty-library/verification-run.md` has the runs, the per-phase split — entries 71.6%, memberships 23.8%, works 4.5% — and what the design's first risk turned out to be: no undetached inverse dominates, because children go before parents, so every parent's inverse array is already empty by the time the parent is deleted, and the works phase is the *cheapest* per row in the list. So the suite count is **8** and the test count **47**: `empty-library` added `M4EmptyLibraryPerformanceTests` and its one arm, and `launch-to-today` added `launchReads` — Req 1.3's two reported-only arms, `launch-reads-full` and `launch-reads-today`, one more test in `M4ToleratedScalePerformanceTests` and no new suite — on top of the 45 `update-schedule` reached by adding `todayPublication`, Req 10.5's Today composition arm, likewise one more test in that suite and no new suite, itself on top of the 44 `work-thumbnails` reached by adding three arms and no suite — `thumbnail-bytes-read`, `backup-export-thumbnails` and `backup-import-thumbnails`, all three in `M4DuplicateScalePerformanceTests` and all three reported rather than budgeted, together worth 2.5–4 minutes of the run. **Both `empty-library` and `launch-to-today` were measured against a 46-test target and each reported 46 in its own branch; 47 is the two of them together.** It was 41 at `place-extraction`, measured as one run at **1,070 s**; the three runs made on the `work-thumbnails` branch measured **1,896 s, 2,683 s and 5,037 s** on a machine that was never quiet, so they set no band and moved none — two of them disagree with each other by 1.7× on the same arms, and an arm that never opens a store doubled (`specs/work-thumbnails/verification-run.md` §2.3). **A quiet-host run of the covered fixture is still owed**, and since `catch-up-mode` that fixture also holds 66 base works on `catchingUp`, which `WorkAuthoredContent.isBare` counts as authored, so every band below the `todayPublication` arm (**0.896 s** since `launch-to-today` amended it, see below; 0.84 s on a loaded host before that, `specs/catch-up-mode/verification-run.md`) is unverified against the fixture as it now stands. That arm is `place-ranking-200x50` at **0.0035 s** against a 10 ms budget and a 50 ms ceiling, recorded beside its sibling `character-ranking-200x50` at **0.0037 s** — the ranker is one generic implementation over `RecordRow` and the point of the arm is that the second conformance costs what the first does. The character arm's own number moved up from 0.0023–0.0025 s in the same change, which is the cost of `CharacterRanking` becoming `RecordRanking`; read 0.0037 s as its new resting place, not as a regression. Every one has a regression ceiling asserted *outside* its known-issue block, so a run that drifts further still fails; `RUNS=3` completes all three runs. `launch-to-today` added the two `launchReads` arms and **amended** `todayPublication`. The `launchReads` pair is reported with no budget and times the repository reads that stand between the store being open and Today being drawable: `launch-reads-full` (`todayPresentation` + `works` + `siteNames`) at **2.435 s** and `launch-reads-today` (`todayPresentation` + `siteNames`) at **0.852 s**, against 2.497 s for the full arm on the before commit measured twelve minutes earlier on the same host — a **1.645 s, 65.9%** fall in what the reader waits on, with the full arm itself unmoved (−2.5%), so the works read was relocated and not removed (`specs/launch-to-today/verification-run.md` §4). Read them as read time and not as time-to-first-Today: the store open, the capture drain and every app-side derivation sit outside them, and on a real library far fewer than 466 of 1,000 works qualify for Today. `todayPublication` no longer makes its own `works()` read or its own `TodaySchedule.build` call — `todayPresentation` builds the schedule and the work titles inside the read since Decision 2 of that spec — and it measures **0.896 s** median at spread 1.08×, inside its 2 s budget with 1.10 s of headroom, agreeing with the 0.903 s an independent run measured the same day. That whole-target run was 1,272.6 s over the 46 tests the target then had, `EXIT=0`, nine known issues; `empty-library`'s arm has since added about 50 s and a forty-seventh test. See `specs/launch-to-today/verification-run.md` for the launch figures and the one like-for-like before/after pair this target has been given, `specs/work-thumbnails/verification-run.md` for the current numbers and for what a contended host does to all of them, `specs/place-extraction/verification-run.md` for the last quiet-host band, `specs/work-creators/verification-run.md` and `specs/bugfixes/settling-pass-budget/` for the previous ones, `specs/series-and-related-works/verification-run.md` for the ones before those, `specs/work-and-reading-status/verification-run.md` §4 for the previous ones, `specs/drop-superseded-columns/verification-run.md` and `specs/multi-site-works/verification-run.md` §4 and §7 for the previous ones, and `docs/agent-notes/testing.md` for recording a band.+- `make test-performance-m4` — M4 Core budgets, host only, no device, safe to run. **~21 minutes** (1,093 s of test time measured 2026-08-28, 1,120 s over 28 tests on 2026-08-30 after `character-ranking` added its own, and **1,120.6 s over 32 tests on 2026-09-05** after T-1910 added four Work-bearing preview arms — all quiet-host runs, all `EXIT=0` with the same eight known issues, so the 21 minutes still holds and the four added arms cost no measurable wall time. T-2093 took the settling pass from ~7.3 s to ~1.7 s per sample; three contended runs on 2026-09-05 measured 1,136 s, 1,237 s and 1,085 s over the same 32 tests, all `EXIT=0` with **seven** known issues. A *loaded* run of those same 32 tests took 1,380 s and breached a regression ceiling on an untouched arm; that is host contention, not a band. Add a ~190 s release build to any of them): most of it is the worst-case single-hostname consolidation in `M4ScalePerformanceTests` (5 samples, each paying its own ~40 s divert before a ~40 s measurement) and the Req 10.1 settling pass (10 samples, each re-seeding 1,350 duplicate rows plus an untimed observation pass). The V4→V5 migration measurement is **gone** — `retire-migration-chain` deleted the pass it timed along with the suite. **The target exits 0 on a quiet host**, with the accepted breaches reported as `withKnownIssue` known issues rather than failures — **ten** since `work-thumbnails` (four before `multi-site-works`, nine after it, eight after `drop-superseded-columns`, seven after T-2093, eight after `series-and-related-works`, nine after `work-creators`), and **eleven on a loaded host**, because `creator-converge-noop` is wrapped `isIntermittent` and only records when the host is busy. Three are long-standing: Req 5.5's three diagnosis re-derivations. Three are Req 5.4's capture-projection arms (0.093–0.102 s pre-V8 → 0.160–0.170 s at V9 → 0.169–0.176 s at V10 → **0.179–0.205 s at V12** → 0.158–0.164 s at V13 on a quieter host, the one on a path the reader waits on; V12's three new tables and V13's two are empty on that path and cost it nothing the run's own host variance does not explain, still well inside a 250 ms ceiling). The seventh is the **full**-tier no-op reconcile, and V9 recovered most of it: 1.07 s → **0.0296–0.0302 s** once `V8PopulationPass` was deleted with the columns and `MembershipReconciler.heal` was gated on the diagnosis, which is still 3.0× a 10 ms ceiling drawn before the library had a membership table; V10 left it there (0.0301 s), V12 did too (0.0308 s) and so did V13 (0.0302 s). Req 10.1's *observation* pass **retired** with that fall (2.69 s → 1.01 s, back inside its 2 s budget, and 1.02 s at V10), and its **settling** pass retired at T-2093: 88% of that pass was SwiftData maintaining `Site.entries` inside the deletion phase's one `save` (6.42 s before the fix, 0.41 s after; the measured 8.0 ms per deleted row over a 5,000-row Site is supporting evidence, not the arithmetic — only the 250 Entry losers of the 300 deleted rows sit in `Site.entries`), and detaching a chunk's doomed rows from their Site in one rewrite of that array took it from 7.3 s to ~1.6 s, inside its 2 s budget, with the 11 s floor under the known issue gone too (`specs/bugfixes/settling-pass-budget/`, Decision 32). The eighth is `series-and-related-works` Req 14.6's link dedupe, a 10 ms budget measured at 0.0100–0.0112 s over 500 links — the low end is `place-extraction`'s run at 0.010032 s, 0.3% over the budget and the closest it has come to fitting, which would turn a quiet host into a *second* way to be red: the whole-table fetch the phase opens with is 79–83% of that, so the budget sits under what SwiftData charges to materialise the rows (Q59 of that spec). The ninth is `work-creators` Req 11.6's credit dedupe, a 50 ms budget measured at 0.0591–0.0651 s over ~2,000 credits, of which the whole-table fetch is 76% (Q73 of that spec, 130 ms ceiling). The intermittent eleventh is that spec's `creator-converge-noop`, in budget at 0.0081–0.0100 s against 10 ms across five samples and never more than 19% clear of it, so it is asserted `isIntermittent` with a 20 ms ceiling (Q74). The tenth is `work-thumbnails` Q80's **`backup-export-thumbnails` peak**: the real exporter over the covered fixture writes a **51.1 MB** archive and peaks **330–462 MB** over its baseline, past the 400 MB Q61 accepted from an estimate, recorded rather than re-based, with a 600 MB regression ceiling asserted outside the block. It is deliberately **not** `isIntermittent`, which means a run whose peak lands *under* 400 MB fails the target with `Known issue was not recorded` — that fired for the first time on 2026-09-13, on a memory-pressured host at 330.2 MB, and a lower peak there is the allocator reclaiming sooner, not the export getting cheaper (`specs/work-thumbnails/verification-run.md` §2.2). Its sibling `backup-import-thumbnails` **meets** the 400 MB plainly at 63.5–159.2 MB, with a settled baseline of 103–144 MB over five runs on one host (`specs/work-thumbnails/verification-run.md` §4.1), and `thumbnail-bytes-read` (fifty on-demand cover reads, Req 7.2) is reported only, 0.032–0.231 s under the 3 s class ceiling. Its other creator arms are `credits-resolve-and-filter` at 0.0144–0.0154 s under a 20 ms budget, `dedupe-credits-fetch` at 0.0477–0.0496 s reported only, `creator-detail` at 0.0363–0.0376 s under 50 ms, and the two read arms `works-snapshot-creators` (1.75–2.11 s) and `creators-list` (0.274–0.284 s) under the 3 s class ceiling. `series-and-related-works` adds `M4SeriesScalePerformanceTests`, `work-creators` adds `M4CreatorScalePerformanceTests` and `empty-library` adds `M4EmptyLibraryPerformanceTests` — one suite, one test, the `empty-library-m4` arm, which empties the covered fixture's **7,009 rows** three times over and costs the target ~50 s. Run **on its own** it measures **5.544–5.942 s** of median over five runs, every sample 5.541–6.244 s, and it is strikingly load-insensitive: those five spanned a one-minute load average of 5 to 241 and moved 7.2%, the loudest run *below* the second-loudest. Run **inside the target**, after twenty minutes of other suites have been through the page cache, the same arm reads **7.712 s** — which is why its regression ceiling is **16 s** (2.07× the in-target median) rather than the 12 s the solo band alone would have given; reported rather than budgeted (Q18 of that spec). `specs/empty-library/verification-run.md` has the runs, the per-phase split — entries 71.6%, memberships 23.8%, works 4.5% — and what the design's first risk turned out to be: no undetached inverse dominates, because children go before parents, so every parent's inverse array is already empty by the time the parent is deleted, and the works phase is the *cheapest* per row in the list. So the suite count is **8** and the test count **49**: `app-intents` added `intentReleasingToday` and `intentNotesToday` — Req 6.6's two arms, `intent-releasing-today` at **0.914 s** and `intent-notes-today` at **0.888–0.904 s** (two release runs on a loaded host), each the Today read plus the pure answer against a 2 s budget that is its only bound, as it is for `todayPublication` (Q43 of that spec), two more tests in `M4ToleratedScalePerformanceTests` and no new suite — on top of the 47 below, where `empty-library` added `M4EmptyLibraryPerformanceTests` and its one arm, and `launch-to-today` added `launchReads` — Req 1.3's two reported-only arms, `launch-reads-full` and `launch-reads-today`, one more test in `M4ToleratedScalePerformanceTests` and no new suite — on top of the 45 `update-schedule` reached by adding `todayPublication`, Req 10.5's Today composition arm, likewise one more test in that suite and no new suite, itself on top of the 44 `work-thumbnails` reached by adding three arms and no suite — `thumbnail-bytes-read`, `backup-export-thumbnails` and `backup-import-thumbnails`, all three in `M4DuplicateScalePerformanceTests` and all three reported rather than budgeted, together worth 2.5–4 minutes of the run. **Both `empty-library` and `launch-to-today` were measured against a 46-test target and each reported 46 in its own branch; 47 is the two of them together.** It was 41 at `place-extraction`, measured as one run at **1,070 s**; the three runs made on the `work-thumbnails` branch measured **1,896 s, 2,683 s and 5,037 s** on a machine that was never quiet, so they set no band and moved none — two of them disagree with each other by 1.7× on the same arms, and an arm that never opens a store doubled (`specs/work-thumbnails/verification-run.md` §2.3). **A quiet-host run of the covered fixture is still owed**, and since `catch-up-mode` that fixture also holds 66 base works on `catchingUp`, which `WorkAuthoredContent.isBare` counts as authored, so every band below the `todayPublication` arm (**0.896 s** since `launch-to-today` amended it, see below; 0.84 s on a loaded host before that, `specs/catch-up-mode/verification-run.md`) is unverified against the fixture as it now stands. That arm is `place-ranking-200x50` at **0.0035 s** against a 10 ms budget and a 50 ms ceiling, recorded beside its sibling `character-ranking-200x50` at **0.0037 s** — the ranker is one generic implementation over `RecordRow` and the point of the arm is that the second conformance costs what the first does. The character arm's own number moved up from 0.0023–0.0025 s in the same change, which is the cost of `CharacterRanking` becoming `RecordRanking`; read 0.0037 s as its new resting place, not as a regression. Every one has a regression ceiling asserted *outside* its known-issue block, so a run that drifts further still fails; `RUNS=3` completes all three runs. `launch-to-today` added the two `launchReads` arms and **amended** `todayPublication`. The `launchReads` pair is reported with no budget and times the repository reads that stand between the store being open and Today being drawable: `launch-reads-full` (`todayPresentation` + `works` + `siteNames`) at **2.435 s** and `launch-reads-today` (`todayPresentation` + `siteNames`) at **0.852 s**, against 2.497 s for the full arm on the before commit measured twelve minutes earlier on the same host — a **1.645 s, 65.9%** fall in what the reader waits on, with the full arm itself unmoved (−2.5%), so the works read was relocated and not removed (`specs/launch-to-today/verification-run.md` §4). Read them as read time and not as time-to-first-Today: the store open, the capture drain and every app-side derivation sit outside them, and on a real library far fewer than 466 of 1,000 works qualify for Today. `todayPublication` no longer makes its own `works()` read or its own `TodaySchedule.build` call — `todayPresentation` builds the schedule and the work titles inside the read since Decision 2 of that spec — and it measures **0.896 s** median at spread 1.08×, inside its 2 s budget with 1.10 s of headroom, agreeing with the 0.903 s an independent run measured the same day. That whole-target run was 1,272.6 s over the 46 tests the target then had, `EXIT=0`, nine known issues; `empty-library`'s arm has since added about 50 s and a forty-seventh test. See `specs/launch-to-today/verification-run.md` for the launch figures and the one like-for-like before/after pair this target has been given, `specs/work-thumbnails/verification-run.md` for the current numbers and for what a contended host does to all of them, `specs/place-extraction/verification-run.md` for the last quiet-host band, `specs/work-creators/verification-run.md` and `specs/bugfixes/settling-pass-budget/` for the previous ones, `specs/series-and-related-works/verification-run.md` for the ones before those, `specs/work-and-reading-status/verification-run.md` §4 for the previous ones, `specs/drop-superseded-columns/verification-run.md` and `specs/multi-site-works/verification-run.md` §4 and §7 for the previous ones, and `docs/agent-notes/testing.md` for recording a band. - `make test-performance-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** @@ -126,10 +126,10 @@ clears the convergence residue are verified by hand from  ### Configurations are not interchangeable -| Configuration | Scheme | Bundle ID | App Group | CloudKit container | Optimization |-|---|---|---|---|---|---|-| `Development` | `Asterism Development` | `me.nore.ig.Asterism.dev` | `group.me.nore.ig.Asterism.dev` | `iCloud.me.nore.ig.Asterism.dev` | `-Onone`, `ENABLE_TESTABILITY=YES` |-| `Personal` | `Asterism Personal` | `me.nore.ig.Asterism` | `group.me.nore.ig.Asterism` | `iCloud.me.nore.ig.Asterism` | `-O`, `wholemodule` |+| Configuration | Scheme | Display name | Bundle ID | App Group | CloudKit container | Optimization |+|---|---|---|---|---|---|---|+| `Development` | `Asterism Development` | Devsterism | `me.nore.ig.Asterism.dev` | `group.me.nore.ig.Asterism.dev` | `iCloud.me.nore.ig.Asterism.dev` | `-Onone`, `ENABLE_TESTABILITY=YES` |+| `Personal` | `Asterism Personal` | Asterism | `me.nore.ig.Asterism` | `group.me.nore.ig.Asterism` | `iCloud.me.nore.ig.Asterism` | `-O`, `wholemodule` |  **Both configurations mirror to CloudKit** since tasks 26/27 of `specs/cloudkit-mirroring/`. A `Development` install is therefore **no longer@@ -138,8 +138,10 @@ installed shares the dev library, so installing it on a second phone merges that phone's dev data in. `Personal` syncs the real library. Both containers are in CloudKit's development environment. -These install as **separate apps with separate data**, both named "Asterism" on-the home screen (`PRODUCT_NAME` is shared). Performance measurement must use+These install as **separate apps with separate data**. `PRODUCT_NAME` is+shared, but the display name is not: two apps with one name would give Siri two+answers to one phrase (`app-intents` Req 7.3), and `make verify-identity` fails+if the two values are missing or equal. Performance measurement must use `Personal` — `Development` is unoptimized and its numbers mean nothing about the shipped app. Unit tests must use `Development` — `Personal` has no testability, and the `Asterism Personal` scheme deliberately excludes the unit-test bundle@@ -364,8 +366,12 @@ so every bootstrap phase runs mirroring-off, the long-lived mirrored container is constructed only after the readiness marker is published, and every re-open tears the previous container down first. The share extension opens the same store with mirroring off, after checking the marker and before-constructing any container, holding a shared lease. Its writes reach CloudKit-through the app's mirror the next time the app is in the foreground, or+constructing any container, holding a shared lease. The app has one+mirroring-off opener of its own on the same terms: `IntentLibraryBroker`, which+opens through `openForExtension` for a cold intent step when no scene has+bootstrapped the library, and shuts that session down after the step. The+extension's writes reach CloudKit through the app's mirror the next time the+app is in the foreground, or sooner when a background-export grant spends itself on the `ExportOwed/` marker the extension leaves. Turning mirroring off in-app is unsupported; rollback is the dashboard's environment reset plus the pre-flight archive.
docs/agent-notes/schema-migration.md Modified +2 / -1
diff --git a/docs/agent-notes/schema-migration.md b/docs/agent-notes/schema-migration.mdindex 313f2120..4aedbc2e 100644--- a/docs/agent-notes/schema-migration.md+++ b/docs/agent-notes/schema-migration.md@@ -4,7 +4,8 @@ Schema **V16** is live (since `specs/remove-article-mode/`), with **V15** frozen beside it as the `from` side of one lightweight stage. The readiness marker set is `["15", "16"]`, and the archive generation is **15/16** — moved by that feature's archive commit, one commit after the schema. The app opens-`openForApp` and the share extension `openForExtension` — one opener per role,+`openForApp`; the share extension and the app's intent broker (`app-intents`,+a cold intent step) open `openForExtension` — one opener per role, both over the same schema and the same file layout (`retire-migration-chain`'s Req 4). Read the "Current state" section; everything under "History" is background for the *next* schema bump and describes states that no longer exist.
docs/agent-notes/testing.md Modified +7 / -0
diff --git a/docs/agent-notes/testing.md b/docs/agent-notes/testing.mdindex 885ee095..51ac31a1 100644--- a/docs/agent-notes/testing.md+++ b/docs/agent-notes/testing.md@@ -1661,6 +1661,13 @@ new parameterised case does not appear by name in the run output, do not assume the filter matched it — count the cases. A plain test with several expectations is the safe form when the argument is a tuple. +**It is not only tuples.** `app-intents` (2026-09-24) hit the same absence with+`@Test(arguments: [String])` — eight sheet-flag names, run through+`make test-only`: the other thirteen tests of the suite were listed, that one+was not mentioned at all. Rewritten as one test looping over+`(name, closure)` pairs, it ran. Prefer the loop for any argument list in the+app bundle.+ ## Four UI cases fail at `main`'s tip `215c843`, and were green the day before  Recorded 2026-09-17 on the `catch-up-mode` branch, so the next branch does not
specs/OVERVIEW.md Modified +15 / -0
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex ed8d6fff..29a35684 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -53,6 +53,7 @@ | [Remove Article Mode](#remove-article-mode) | 2026-09-21 | Done — `make test` carries UI failures `main` owns, so Req 7.1 is not met as written (Q34) | Full spec (T-2336). Removes articles mode: the one-way Site state, its UI and repository operations, `SiteMode.articles` with every arm over it, and the `article` default work type. Schema V16 drops `Site.junkSuffixRule`, the one column only the mode used, and the archive moves to 15/16; 14/15 backups stop importing. No conversion is built, because no articles Site exists (Decision 1, Q10). Three commits: remove the mode, schema V16, archive and documents. | | [To Read](#to-read) | 2026-09-21 | Done | Full spec (T-2354). A fifth reading status, `toRead`, which the New Work form gives every work it creates and the reader can set in edit mode. A capture or a Move To into a to-read work makes it `reading` in the same commit; nothing else promotes. To-read works stay off Today's plan. No schema, marker or archive generation change. The share-sheet path is deferred to T-2363. | | [New Work URL Field](#new-work-url-field) | 2026-09-22 | Done | Smolspec (T-2365). The New Work form's site field accepts a bare hostname or an HTTP(S) URL with the scheme optional; a URL reduces to the host capture derives and is stored as that site's Work URL after the validator's on-host check. The field is relabelled with the URL keyboard, and `LibraryRepositoryError` becomes `LocalizedError` so every form shows a readable message. No schema change. The confirm-same-story dedup prompt is T-2366. |+| [App Intents](#app-intents) | 2026-09-23 | Done | Full spec (T-2367). Siri and Shortcuts answer which chapters release today and which notes were made today, add a web page as a to-read work, and open Today or a work. Intents run in the app process; a cold step opens the library as the share extension does and leaves an `ExportOwed` marker after a write. `Development` is renamed Devsterism so the two apps' phrases differ. No schema change. |  --- @@ -877,3 +878,17 @@ Smolspec (T-2365). The New Work form's site field accepts a bare hostname or an - [tasks.md](new-work-url-field/tasks.md) - [decision_log.md](new-work-url-field/decision_log.md) - [implementation.md](new-work-url-field/implementation.md)++## App Intents++**Created:** 2026-09-23 · **Status:** Done — 19 tasks in four phases; the owner's Mac cold-path timing and phone runbook are owed (`prerequisites.md`).++Full spec (T-2367). Five App Intents, a `WorkEntity` with a Find Works action, and five App Shortcuts, all in the app process (Decision 1). Answers are pure Core functions over `todayPresentation` and `TodayDayPlan.build` for the day the intent runs, so Siri and the Today screen agree; notes are the Today noted section's, blank notes dropped. "Add as to read" checks for the page by capture's entry match and by normalised work URL, fetches the title, offers a choice, and creates under one lock with a second check (Decision 3, Q35). The library is reached per step through `IntentLibraryBroker`: the resident repository, or a one-step `openForExtension` session with mirroring off and an `ExportOwed` marker after a write; bootstrap drains, never cancels (Decision 4, superseding Decision 2). Every intent requires an unlocked device; open intents stop when a sheet or edit mode is open (Q37). The `Development` app is renamed Devsterism, enforced by `make verify-identity`. Two 2 s M4 arms. No schema, marker or archive change.++- [requirements.md](app-intents/requirements.md)+- [design.md](app-intents/design.md)+- [tasks.md](app-intents/tasks.md)+- [decision_log.md](app-intents/decision_log.md)+- [prerequisites.md](app-intents/prerequisites.md)+- [runbook.md](app-intents/runbook.md)+- [implementation.md](app-intents/implementation.md)
specs/app-intents/decision_log.md Added +213 / -0
diff --git a/specs/app-intents/decision_log.md b/specs/app-intents/decision_log.mdnew file mode 100644index 00000000..3e5c9be8--- /dev/null+++ b/specs/app-intents/decision_log.md@@ -0,0 +1,213 @@+# Decision Log: App Intents++## Quick Decisions++| ID | Date | Decision | Rationale |+|----|------|----------|-----------|+| Q1 | 2026-09-23 | Full spec, not a smolspec (T-2367) | Owner's pick on the scope assessment. The intents need a way into the library under the one-mirroring-process rule (in-app or an extension), which decides the whole change; note-date semantics and the to-read title source were open |+| Q2 | 2026-09-23 | The spec is named `app-intents` | Owner's pick; matches the ticket |+| Q3 | 2026-09-23 | "Notes from today" means entries shared today, as the Today screen's noted section shows them, not entries first captured today | Owner's pick. Siri and Today then agree; a re-shared older chapter is noted today on the Today screen as well |+| Q4 | 2026-09-23 | The add intent fetches the page title and asks the reader to confirm an editable title before creating | Owner's pick. A landing page's `<title>` is usually not a work title, and `createWork` refuses a blank one |+| Q5 | 2026-09-23 | Scope is four capabilities: chapters releasing today, notes from today, add a page as to read, and open Today or a work | Owner's pick |+| Q6 | 2026-09-23 | Fixed intents plus works as Shortcuts values; no Spotlight or semantic index | Owner's pick. An entity lets Siri resolve "open <work>" and lets Shortcuts chain actions; an index is a larger, separate surface |+| Q7 | 2026-09-23 | Siri speaks each note as work title, chapter title and note text; entries without a note are left out | Owner's pick |+| Q8 | 2026-09-23 | If the page URL already belongs to a work, the add intent says so with the work's status and creates nothing | Owner's pick. The New Work form creates a second work; a voice action should not |+| Q9 | 2026-09-23 | The intents ship on iPhone, iPad and Mac | Owner's pick; one app target builds for all three |+| Q10 | 2026-09-23 | "Releasing today" excludes catching-up works | Today lists catching-up works every day in their own section; they are not a chapter due today |+| Q11 | 2026-09-23 | Above five qualifying notes, Siri speaks the count and the first five; the shown result lists all | Reading a long list aloud is not usable; five is a round cut that covers a typical day |+| Q12 | 2026-09-23 | Every intent requires the device to be unlocked | Owner's pick. Note text and titles are reader content; the store is readable after first unlock, so the intent's authentication policy is the only gate |+| Q13 | 2026-09-23 | The `Development` app gets a display name distinct from `Asterism`, and that name is `Devsterism` (Q26) | Owner's pick. Both apps share `PRODUCT_NAME`, so `applicationName` in a phrase resolves to "Asterism" for both and Siri cannot tell them apart. Changes the Development home-screen name too; CLAUDE.md's configuration note must be updated with it |+| Q14 | 2026-09-23 | A saved work reference whose work was collapsed into another reports not found | Owner's pick. Collapse leaves no forwarding record and is rare; adding one is a schema-level change for a corner case |+| Q15 | 2026-09-23 | An open intent while an edit view is open brings the app forward with the draft untouched and says an edit is in progress | Owner's pick. Edit views save on Save only; a navigation that discards the draft would lose the only copy of it |+| Q16 | 2026-09-23 | The add intent takes its URL from Shortcuts or the share sheet through Shortcuts; by voice it uses the page Siri supplies from the screen and asks for a URL only when none is supplied. A supplied title skips the prompt and a spoken title replaces the prefilled one | Owner's pick, amended the same day. An App Shortcut phrase cannot carry a URL. No API lets an intent read another app's screen, but Siri AI's on-screen awareness can fill a transferable `URL` parameter from Safari; where it does not (no Siri AI, or Siri does not offer the page) the prompt is the fallback on the same code path. A spoken answer is a fresh dictation, not an edit |+| Q17 | 2026-09-23 | "Today" is the civil day when the intent runs, not the day an open Today screen last published | Raised at review. The screen mints its day at publication and can show yesterday after midnight; the intent must be testable without a screen |+| Q18 | 2026-09-23 | A note from an unattached entry is named by its capture title; the chapter line falls back from title to number to nothing | Raised at review. `workDisplayTitle` and `chapterTitle` are optional on a noted row; the fallbacks are the ones the Today screen's noted rows already use |+| Q19 | 2026-09-23 | The add intent's duplicate check uses the capture URL key against work URLs and entry URLs, is repeated at commit, and an unattached-entry match creates nothing | Raised at review. Work URLs are stored as typed, so a raw comparison would miss; the check at commit closes the gap between the prompt and the write. An unattached capture is already the reader's record of the page |+| Q20 | 2026-09-23 | The add intent follows the New Work form except for the duplicate check, and schedules no reconcile beyond what the form schedules | Raised at review. The reconcile triggers are a closed list; this adds no new trigger |+| Q21 | 2026-09-23 | The two read budgets are 2 s medians excluding the store open, not 1 s | Raised at review. `launch-reads-today` already measures 0.852 s over the covered fixture, so 1 s would be flaky under the second-slowest-of-20 percentile; 2 s matches `todayPublication`'s budget. A cold store open cannot be measured on the host |+| Q22 | 2026-09-23 | Open intents do not refuse on an unavailable or opening library; they bring the app forward on its own state and navigate once ready | Raised at review. The app already draws its unavailable and opening states; refusing to open it is worse |+| Q23 | 2026-09-23 | The "open work" phrase takes a spoken name for works reading or catching up; other works are reached through the find query | Raised at review. A phrase parameter must come from suggested entities, which should be a short list; those are the works the reader opens most |+| Q24 | 2026-09-23 | ~~The cold intent session mirrors, as the background-export cold session does~~ Superseded by Q38 | Owner's pick. A work added by Siri exports without waiting for the next foreground; the cost is a mirrored container inside Siri's 30 s, tracked as a risk with mirroring off as the fallback |+| Q25 | 2026-09-23 | `make verify-identity` fails when the app target's `Development` and `Personal` display names are equal | Owner's pick. Keeps Req 7.3 from regressing silently; the lint already owns identity declarations |+| Q26 | 2026-09-23 | The `Development` display name is `Devsterism` | Owner's pick |+| Q27 | 2026-09-23 | Intent types live in the app target under `Intents/`; `AsterismCore` gains only store reads and pure answer functions, and never imports `AppIntents` | The share extensions link Core and must not carry intents; Core logic stays testable under `make test-core` |+| Q28 | 2026-09-23 | Answers are composed from `todayPresentation` plus `TodayDayPlan.build`, not a new lighter read | Req 1.4 requires equality with the screen, and one composition guarantees it; the read measures 0.77–0.85 s against a 2 s budget |+| Q29 | 2026-09-23 | Intent navigation uses a new `AppNavigation.intentRoute`, not `PendingRoute` | `PendingRoute` is taken when Settings dismisses; an intent route is taken when the library becomes ready and after the Mac restore, and is dropped if the reader moved |+| Q30 | 2026-09-23 | An edit in progress is known through an `AppNavigation.editSessions` set that editors join with a view modifier | No central editing flag exists; editor models are per-view `@State` the App cannot see |+| Q31 | 2026-09-23 | `pageMatch` prefers a work match over an entry match, and an entry that has a work reports that work | The reader asked whether the work is in the library; naming the work answers it |+| Q32 | 2026-09-23 | `OpenWorkIntent` uses `.dynamic` foreground mode and checks the work exists before foregrounding | Req 4.4 forbids foregrounding for a missing work; an `OpenIntent` foregrounds before `perform()` can check |+| Q33 | 2026-09-23 | No `AppIntentsTesting` UI tests | It needs the 27 SDK; the logic is covered by Core and app unit tests over pure functions, and the Siri surface by the owner's runbook |+| Q34 | 2026-09-23 | Entity queries return nothing on iOS while protected data is unavailable | `authenticationPolicy` covers intents, not the queries Siri calls to resolve a work; without this a locked phone could speak titles (Req 6.3) |+| Q35 | 2026-09-24 | The work arm of the duplicate check compares `EntryIdentityNormalizer.key(forRawURL:)` of both sides; a trailing slash or a fragment still makes a different page | Raised at design review. Work URLs are stored as typed, so raw equality missed scheme and host case, trackers and an added `https://`; capture itself treats slash and fragment differences as different pages, and the intent should not be looser than capture |+| Q36 | 2026-09-24 | The ~10 s after a lock during which `isProtectedDataAvailable` stays true is accepted against Req 6.3 | Raised at design review. Intents themselves are gated by `authenticationPolicy`; only query resolution relies on the flag, and the window is the system's |+| Q37 | 2026-09-24 | The open intents' edit guard counts any presented sheet or modal, plus Work/Series/Creator edit modes and an entry with an unsaved note | Owner's pick at design review. Fails safe: a draft view added later is covered without being listed; a harmless sheet also blocks, with a message |+| Q38 | 2026-09-24 | Cold intent steps open with `openForExtension` (existing-only, shared lease, mirroring off) for one step each, and a cold write leaves an `ExportOwed/` marker | Owner's re-decision at design review, superseding Q24. A mirrored cold session closed before any export ran, so it paid CloudKit setup inside Siri's 30 s for nothing; the marker is the share extension's existing path to the next export, and Req 6.5 holds. Promoted to Decision 4 |+| Q39 | 2026-09-24 | The add intent's title comes from the bounded fetch only; Req 3.1 and the Page input definition are amended to drop "the title the page input carries" | Owner's pick at design review. Siri and Shortcuts pass a Safari page to a `URL` parameter as its URL; a separate `pageTitle` parameter helps only a hand-wired shortcut |+| Q40 | 2026-09-24 | Req 5.2's find action comes from `EntityPropertyQuery` with a title contains-comparator | Raised at design review. `EntityStringQuery` alone gives Siri resolution but no standalone Shortcuts "Find" action |+| Q41 | 2026-09-24 | A supplied title that is blank or whitespace counts as not supplied | Raised at design review. Otherwise Req 3.2 would skip the prompt and `createWork` would refuse the blank title |+| Q42 | 2026-09-24 | A deferred intent route is dropped when `AppNavigation.revision` moved since it was set, when an edit is in progress, or when the work id is unknown | Raised at design review. A tab comparison misses a push on the same tab; a route set without the existence check (library unavailable) must not open an empty detail |+| Q43 | 2026-09-24 | The two intent performance arms are bounded by their 2 s budget alone, asserted outside any known-issue block; no separate regression ceiling | Raised at phase review, replacing a 1.5 s ceiling drawn under the budget. A ceiling under the budget redefines Req 6.6's budget without the requirement changing and fails loaded-host runs that meet it; `todayPublication`, which times the same read, has only its budget. First medians 0.914 s and 0.888–0.904 s on a loaded host |+| Q44 | 2026-09-24 | The five Core intent reads and writes are `async throws`, and the broker's step takes an async closure | Raised in implementation. Every repository call awaits the cross-process lock inside `withLockedContext`, so the design's synchronous `throws` signatures cannot be met without a second lock path |+| Q45 | 2026-09-24 | `workSummaries(titleContaining:)` with blank or whitespace-only text returns every work | Raised in implementation. A contains-match on an empty string matches nothing in Foundation; an empty Shortcuts search should list works, not report none |+| Q46 | 2026-09-24 | "A refusing diagnosis" in the add intent's refusals is tested as the save boundary refusing the commit | Raised in implementation. `createWork` has no diagnosis gate of its own; its refusals are the title, the site-or-URL grammar, the off-host URL and the save strategy, and `createWorkUnlessPresent` shares all four |+| Q47 | 2026-09-24 | `createWorkUnlessPresent` skips the duplicate check for a draft holding only a hostname; among several unattached entries matching a page the least UUID is named; `NoteAnswer` carries the entry's id and the trimmed note | Raised at phase review of details the design left open. A bare hostname names no page to match, and the intent always passes a URL; a least-UUID pick keeps the answer deterministic, as `titleOrder` does for works; the id costs nothing and lets a later snippet link the row |+| Q48 | 2026-09-24 | `withLibrary(writes:_:)`: the caller declares whether a step can write; a declared write refreshes the resident snapshots or marks export owed on a cold session, even when it answers `.present` | Raised in implementation. The broker cannot see inside the closure. Every write call site (the add intent's `createWorkUnlessPresent`) must pass `writes: true`; a spurious refresh or marker is harmless, a missed one leaves Today stale or the export late |+| Q49 | 2026-09-24 | `IntentLibraryError` is `.unavailable` or `.failed(any Error)`; `libraryBusy` and `libraryUnavailable` from a step, any `openForExtension` throw and an unresolvable configuration are `.unavailable`, every other error is `.failed` | Raised in implementation. The add intent needs the refusal's own reason for Req 3.6 |+| Q50 | 2026-09-24 | Broker admission is a FIFO of waiting continuations; a step queued before a bootstrap started gives its turn back when it comes up during the open and waits on `libraryReady()` | Raised in implementation. Same behaviour as the design's chain of tasks, simpler. Running cold then would open a second container beside bootstrap's, and keeping the turn would deadlock the drain |+| Q51 | 2026-09-24 | A cold step borrows an open background-export session, and `AppLibraryModel.release()` drains the broker before shutting that session down | Raised in implementation. The design said a cold step reuses the session but not who keeps it alive; draining in `release()` covers the pass's own release and bootstrap's pre-emption |+| Q52 | 2026-09-24 | `takeIntentRoute(workTitlesByID:)` takes the titles map, and ContentView takes a route on `.ready`, after the Mac restore, and when a route reaches an already-ready window; a `.today` route also clears the pushed Today entry | Raised in implementation. `AppNavigation` holds no library reference; the third trigger covers an intent run while the window is open; without the clear the compact tree kept the entry on screen |+| Q53 | 2026-09-24 | `revision` moves in `didSet`s on the six navigation properties when the value changes; restore, prune and normalise run under `withoutRevision` | Raised in implementation. Binding writes from back gestures must count as reader navigation; restoring and pruning are not the reader moving |+| Q54 | 2026-09-24 | An edit session ends when its `active` goes false or its view state is released, not on `onDisappear`; `isEditing` counts every `AppNavigation` sheet flag except `showingDiagnostics`, which is a push | Raised in implementation. A tab switched away disappears with its editor open, and ending the session there would let an open-work intent replace the stack under the draft |+| Q55 | 2026-09-24 | `ShortcutParameters.refresh` is called from `refreshAll()` only, not from `publishToday()` | Raised in implementation, amending the design and task 13. `publishToday()` holds only the Today schedule, which lists reading works with release days and catching-up works, not every reading work; refreshing there registers a partial set and then the full one a moment later |+| Q56 | 2026-09-24 | Each read intent is one broker step: the releases intent reads `todayPresentation` and `workSummaries(ids:)` in one closure; Find Works runs all its comparators in one step (`.and` intersects, `.or` unions, title order kept, descending reverses before the limit) | Raised in implementation. A cold library opens once per intent run |+| Q57 | 2026-09-24 | `IntentLockedError` is a plain error, "Unlock your device to use your Asterism library.", behind `AppLifecycle.isProtectedDataAvailable`, which is always true on the Mac | Raised in implementation. App Intents has no predefined device-locked error; the check goes through the platform seam |+| Q58 | 2026-09-24 | Intent dialog wording is as recorded under "Dialog wording" in `implementation.md`; a library refusal is "Asterism couldn't add that page." plus `LibraryRepositoryError`'s own description; a `.failed` step in a read or open intent is rethrown, only the add flow words it | Raised in implementation; the design fixed only the empty-case sentences |+| Q59 | 2026-09-24 | In the add intent's title choice, any answer other than use or change throws `CancellationError` | Raised in implementation. A backstop so no unexpected choice value can reach the write (Req 3.7) |+| Q60 | 2026-09-24 | The Mac cold-path timing (task 14) is owed by the owner, and tasks 15–18 were built without it; the keep-alive fallback is applied only if that run shows a slow cold step | Raised in implementation. The `shortcuts` CLI runs only existing shortcuts, and creating one needs the Shortcuts app. Nothing was measured or estimated; the steps are in `implementation.md` |+| Q61 | 2026-09-24 | `verify-identity`'s display-name check requires the two app configurations to declare different values; it does not pin `Devsterism` | Raised in implementation. Req 7.3 needs the names to differ; pinning would turn a deliberate rename into a two-place edit |+| Q62 | 2026-09-24 | The check also fails on a display name set only under an SDK condition and on a literal `CFBundleDisplayName` in the app's `Info.plist` | Raised in implementation. Either would let one platform's two apps share a name while the build settings look distinct |+| Q63 | 2026-09-24 | The share extensions keep their `Development` display name "Asterism Dev" | Raised in implementation. Extensions carry no intents and no phrases, so Req 7.3 does not reach them; renaming them is a separate choice |+| Q64 | 2026-09-24 | The edit guard's local-presentation audit is the set actually registered (listed in the design's audit table), not the design's first list; intents take `AppLibraryModel` and `AppNavigation` as `@Dependency` and reach the broker as `model.intentBroker` | Raised at pre-push review. Several views the first audit named present no sheet, and the ones that do were found by grep; the model is what `App.init` can build and register, and it owns the broker |+| Q65 | 2026-09-24 | The background-export pass holds the broker's admission turn around its cold open and around `release()`'s shutdown (`IntentLibraryBroker.holdingTurn`) | Raised at pre-push review; extends Q51. Without it a step admitted while the pass was opening, or between the drain and the shutdown, opened a second container beside the pass's or borrowed a closing one. A drain loop would still leave the shutdown's await open |+| Q66 | 2026-09-24 | Open Work routes at once while a bootstrap is in flight, skipping the existence check and naming "that work"; the window drops the route if the work is unknown (Q52) | Raised at pre-push review. Req 4.6 asks the app to come forward on the state it shows while opening, not to wait for the open |+| Q67 | 2026-09-24 | `withLibrary` has no `writes` default; `withLibrary(wroteIf:)` lets a step's answer say whether it wrote, and the add flow passes `.created` only, so a `.present` answer neither refreshes nor marks export owed | Raised at pre-push review; amends Q48. A default of `false` failed open for a future write step |+| Q68 | 2026-09-24 | A resident write's refresh runs after the answer, in a main-actor task outside the broker turn | Raised at pre-push review; amends Q48. The refresh (~3 s at library scale) held Siri's answer and the turn; a later step or bootstrap may now interleave with it, which the refresh already tolerates as it does any other refresh |+| Q69 | 2026-09-24 | A single-row Work bucket is summarised from the row itself; only multi-row buckets build the group and fetch the type directory | Raised at pre-push review, following `character-ranking` Q34. Building authored content faulted every work's memberships on every Siri query |+| Q70 | 2026-09-24 | `IntentLibraryError` conforms to `CustomLocalizedStringResourceConvertible`; the add intent logs `url supplied` or `url asked` on every line and a cancelled prompt logs `cancelled` | Raised at pre-push review. Entity queries surfaced a generic error for an unavailable library, and Req 6.7 wants one outcome line per run |++## Decision 1: Intents Run in the App Process++**Date**: 2026-09-23+**Status**: accepted; its "cancels and waits for" clause superseded by Decision 4 (bootstrap drains, never cancels)++### Context++App Intents can run in the app's own process (launched in the background when no window is needed) or in a separate App Intents extension. Asterism allows exactly one process to mirror the library to CloudKit — the app — and the share extension already shows the cost of a second opener: mirroring off, a shared lease, a readiness-marker check, identity lint rules, and writes that reach CloudKit only when the app next runs. A background launch of the app does not run `bootstrap()`, which is started from the window's `.task`, so an intent in the app finds no library open unless the app is resident, and a window that connects mid-intent would open the mirrored container over a store the intent holds.++### Decision++Every intent runs in the app process. A read or add intent uses the resident library when the app is ready, and otherwise opens its own session that the app's bootstrap cancels and waits for at a point between writes, as the background-export pass does. The open intents foreground the app.++### Rationale++The background-export pass already solves the same problem — scene-less work in the app process that must yield to a window's bootstrap without a second mirrored container — so the intents reuse a tested pattern instead of adding a process. The open intents must run in the app in any case, and one host keeps the entity types in the app target.++### Alternatives Considered++- **An App Intents extension for the read and add intents**: a separate process opening the store mirroring-off like the share extension - Rejected: a new target, a shared framework for the entity types, new `verify-identity` rules, and writes that wait for the app, for a faster cold answer the reader will rarely notice.+- **Mixed hosting with a new shared lock protocol**: extension for reads, app for writes - Rejected: two hosts for five intents and two different consistency stories.++### Consequences++**Positive:**+- No new process, target or entitlement; the one-mirroring-process rule holds by construction.+- A created work is an ordinary app write, change-tracked like the New Work form's.++**Negative:**+- A cold intent pays the store open inside the Siri timeout.+- The app's bootstrap gains a second session to wait for (drained, not cancelled, per Decision 4).+- A work created by a cold intent reaches other devices only on the app's next mirror run.++---++## Decision 2: Cold Intent Sessions Are Existing-Only and Yield to Bootstrap++**Date**: 2026-09-23+**Status**: superseded by Decision 4++### Context++A background intent launch runs `App.init` but no scene, so nothing opens the library. `openForApp` is the only opener the app has, and it creates a pristine store, re-marks a lagging marker and migrates — which Req 6.3 forbids an intent to do. The background-export pass already runs scene-less work on a cold session that `bootstrap()` cancels and awaits, but its session slot and skip rules are export-specific.++### Decision++Add `OpenPolicy.existingOnly` to `openForApp`, refusing any classification whose action would create, re-mark or migrate. Add an `IntentLibraryBroker` on `AppLibraryModel` that runs one repository step at a time on the resident library or on its own cold session opened with that policy; `bootstrap()` cancels and awaits its step and releases the session before opening, and a cancelled step retries once on the resident library. The broker and the export pass exclude each other: export skips while an intent holds a session, and the broker cancels and awaits a running export pass before opening, because the reader is waiting and export re-runs at its next grant. Arrivals during an intent session are deferred as during an export pass.++### Rationale++It keeps the store lifecycle in one opener with one extra refusal, and it reuses the pre-emption shape that already holds the one-mirroring-container rule for export. Per-step cancellation lands only between synchronous locked writes, so no write is half-applied.++### Alternatives Considered++- **Generalise export's session into a shared, reference-counted background session**: export and intents share one open session - Rejected: refactors a shipped, device-verified path for the rare overlap of a background-refresh grant and a Siri request.+- **Refuse intents unless the app is resident**: no cold path at all - Rejected: Siri from a locked-then-unlocked phone with the app evicted is the common case.+- **Call `openForApp` unchanged**: accept create and re-mark - Rejected: violates Req 6.3; an intent must never be the thing that makes or moves a library.++### Consequences++**Positive:**+- The one-mirroring-container rule holds by construction.+- No write is torn by a window arriving mid-intent.++**Negative:**+- A background-export pass that coincides with an intent is cancelled or skipped and waits for the next grant.+- `bootstrap()` has a second thing to cancel and await.++---++## Decision 3: The Title Prompt Is a Choice, Then a Question++**Date**: 2026-09-23+**Status**: accepted++### Context++Req 3.1 asks for a title prefilled with the fetched page title and editable. App Intents has no prefilled text prompt: `requestValue` takes no initial value, and `@Parameter(default:)` must be a build-time constant.++### Decision++When a title was fetched, ask `requestChoice` between "Use \"<title>\"", "Change title" and Cancel; "Change title", or no fetched title, asks `requestValue` for a title, repeated while blank. A title supplied with the action skips both.++### Rationale++It is the closest the framework allows to an editable prefill: the common case is one tap or "yes", and an edit is a fresh answer, which is what a spoken edit is anyway (Q16).++### Alternatives Considered++- **`requestConfirmation` then ask on decline**: decline normally means cancel, so "no" would be ambiguous - Rejected unless the choice fails by voice (a recorded risk).+- **Always ask for the title**: loses the fetched title - Rejected: the owner chose a prefilled confirmation (Q4).++### Consequences++**Positive:**+- One interaction when the fetched title is right.++**Negative:**+- The fetched title cannot be edited in place; changing it means typing or saying it whole.++---++## Decision 4: Cold Intent Steps Use the Extension Opener, One Step at a Time++**Date**: 2026-09-24+**Status**: accepted++### Context++Decision 2 gave intents a cold mirrored session opened through `openForApp` with a new existing-only policy, held for a whole intent and cancelled by bootstrap. Review found four problems. Entity queries run outside any intent, so nothing released a session they opened. Concurrent intents could close a session under each other. Cancelling a step and retrying it could report a work that step had just created as a duplicate. And the mirrored session closed before any export ran. `openForExtension` already opens an existing library under a shared lease with the interactive timeout and mirroring off, and never creates, re-marks or migrates.++### Decision++A cold intent step opens the library with `openForExtension`, runs one repository call, leaves an `ExportOwed/` marker if it wrote, and shuts the session down. Steps are admitted one at a time through a FIFO chain of held tasks. `bootstrap()` stops admission and awaits the in-flight step; it never cancels it. Background export does not start while a step is in flight, and a cold step reuses an export pass's session if one is open.++### Rationale++Every open is paired with its close inside one call, so queries and concurrent intents need no lifetime rules. A step is short and synchronous, bounded by the 2 s lease, so waiting for it is cheaper than making cancellation safe. The extension opener already has the refusals Req 6.4 needs and no side effects, so there is no new opener policy.++### Alternatives Considered++- **Decision 2's intent-scoped mirrored session with cancel-and-retry**: one open per intent - Rejected for the four problems above.+- **A reference-counted session shared by queries and intents**: fewer opens - Rejected: it needs lifetime rules for queries the system calls at arbitrary times, and it holds the store across human prompts.+- **Mirroring on with an awaited export**: prompt sync - Rejected by the owner (Q38): it slows every Siri answer for a sync Req 6.5 does not require.++### Consequences++**Positive:**+- No new opener and no new store policy; the one-mirroring-container rule holds because a cold session never mirrors.+- No write is cancelled or retried.++**Negative:**+- Every cold step pays `validateStore`; an add intent pays it twice (a recorded risk with a keep-alive fallback).+- A cold-created work reaches other devices only after the next background grant or foreground.++---
specs/app-intents/design.md Added +234 / -0
diff --git a/specs/app-intents/design.md b/specs/app-intents/design.mdnew file mode 100644index 00000000..888764a7--- /dev/null+++ b/specs/app-intents/design.md@@ -0,0 +1,234 @@+# Design: App Intents++## Overview++Five App Intents, one `AppEntity` and one find action in the app target, running in the app process (Decision 1). They reach the library through a broker on `AppLibraryModel` that runs each repository step on the resident repository, or on a short cold session opened the way the share extension opens the store (Decision 4). Their answers come from pure Core functions over the Today read, so Siri and the Today screen cannot disagree.++## Architecture++```mermaid+flowchart LR+  Siri[Siri / Shortcuts] --> I[Intents + WorkEntityQuery<br/>app target]+  I -->|@Dependency| B[IntentLibraryBroker]+  I -->|@Dependency| N[AppNavigation<br/>intentRoute, edit guard]+  B -->|state == .ready| R[(resident repository)]+  B -->|no scene: openForExtension<br/>per step, mirroring off| C[(cold session)]+  C -.cold write.-> M[ExportOwed marker]+  R & C --> Core[LibraryRepository+Intents<br/>IntentAnswers]+```++### Integration points++| Where | Change |+|---|---|+| `AsterismApp.init` | Build the `AppLibraryModel` and `AppNavigation` instances there (`_model = State(initialValue:)`, likewise navigation) so the same instances can be registered with `AppDependencyManager.shared` in `init`, Apple's documented place. |+| `AppLibraryModel.bootstrap()` (`AppLibraryModel.swift:534`) | After setting `bootstrapInFlight`, awaits the broker's in-flight step (`await broker.drain()`) before `teardownRepository()`. It does not cancel it. |+| `AppLibraryModel.acquire()` (:2078) | Returns `.skipped(.unavailable("an intent holds the library"))` while `broker.isBusy`. |+| `LibraryRepository.openForExtension` (`LibraryRepository+Bootstrap.swift:370`) | Unchanged in behaviour; its doc comment changes from "the only one" extension-role opener to naming its two callers, the share extension and the intent broker. |+| `ContentView` | Calls `navigation.takeIntentRoute(model:)` when `model.state` becomes `.ready`, and on the Mac after `restoreSelection()`, so a restore cannot overwrite the route. |+| `AppLibraryModel.refreshAll()` | Calls `ShortcutParameters.refresh(works:)` (not `publishToday()`, Q55) with the reading and catching-up works; it calls `AsterismShortcuts.updateAppShortcutParameters()` only when the id→title set differs from the last call. |+| In-stack edit modes (see edit guard) | Apply `.intentEditSession(active:)`. |+| `project.pbxproj`, app target | `Development`: `INFOPLIST_KEY_CFBundleDisplayName = Devsterism`; `Personal`: `= Asterism`. |+| `scripts/verify-identity.sh` | New check: the app target's two configurations carry different `INFOPLIST_KEY_CFBundleDisplayName` values. |+| `CLAUDE.md` | The configuration table gains a display-name column; the "both named Asterism" sentence goes; the Sync section names the intent broker as the app's one mirroring-off opener. |++### Library broker++`IntentLibraryBroker` is a `@MainActor` object owned by `AppLibraryModel`.++```swift+func withLibrary<T: Sendable>(writes: Bool = false, _ step: @escaping @Sendable (any LibraryProviding) async throws -> T) async throws(IntentLibraryError) -> T  // async step: Q44; writes: Q48+func drain() async          // bootstrap's call: resolves when no step is in flight+var isBusy: Bool { get }+```++`withLibrary` runs:++1. **Wait while opening.** If `bootstrapInFlight`, await `model.libraryReady()` before admission. `libraryReady()` resumes when `state` leaves `.loading`. This is Req 6.2's "opening".+2. **Admission.** Await the tail of the broker's FIFO queue. The queue is a chain of held `Task`s, each awaiting its predecessor. This is the mutex; the main actor alone is not one, because it is reentrant at every `await`.+3. **Resident library.** If `state == .ready`, run the step on the resident repository. If the step wrote, call `refreshDiagnosesAndSnapshots()` afterwards, as the New Work form's `onMutation` does. There is no `scheduleDuplicateReconcile()` (Req 3.9).+4. **Unavailable.** If `state == .unavailable`, throw `.unavailable`.+5. **Cold session.** Otherwise the process has no scene and was never bootstrapped:+   - Call `LibraryRepository.openForExtension(configuration)`. It takes a shared lease with the interactive timeout, requires the marker and the store, never creates, re-marks or migrates, and opens with mirroring off.+   - Run the step.+   - If the step wrote, call `ExportOwedMarker(directory: configuration.exportOwedURL).mark()`, ignoring a throw as the share extension does.+   - Call `repository.shutdown()`.+   - Any `libraryUnavailable` error or lock timeout throws `.unavailable`.++Contracts:+- **One session per step.** A cold session lives for exactly one step, and nothing holds it across a prompt or between queries. Entity queries use the same call, so they have the same lifetime.+- **Bootstrap waits, never cancels.** Steps are synchronous repository calls, bounded by the 2 s lease wait plus the call itself. `bootstrap()` sets `bootstrapInFlight` first, so no new step is admitted, and then drains the queue. The app's mirrored container is built only after the last cold session has shut down. A step is never cancelled mid-write, and so is never retried.+- **Export yields.** A background-export pass does not start while `isBusy`. The broker does not wait for a running export pass. Both only take shared or per-call locks, so they can overlap on the store, and the export pass holds its own mirrored session only in a process with no scene. A cold step that finds `backgroundSession != nil` runs on that session instead of opening its own, so two containers never exist in one process.+- **Arrivals.** A cold session has no `SyncMonitor`. On the resident path arrivals reconcile as they always do.++### Edit guard (Req 4.5)++`AppNavigation.isEditing` is true when either of these holds:+- **Any presented sheet or modal.** This covers every sheet flag `AppNavigation` holds (`showingNewWork`, `showingSettings`, `showingTeachingForHostname`, `resolvingDuplicateSet`, `mergingWorkID`, `presentedAnnouncement` and the rest; the audit is below). It also covers any `.sheet` or `.fullScreenCover` a view presents locally. Those register through `.intentEditSession(active: isPresented)`.+- **An in-stack edit mode**, registered with `.intentEditSession(active:)`: `WorkDetailView` (`model.isEditing`), `SeriesDetailView` (`model.isEditing`), `CreatorDetailView` (`model.isEditing`), and `EntryDetailView` (new `EntryDetailModel.hasUnsavedChanges`: `draftNote` or `draftRating` differs from the loaded snapshot).++The guard fails safe. A harmless sheet also blocks, and the reader gets the message. See Q37.++Audit of `AppNavigation`'s presentation state:++| State | Counts |+|---|---|+| `showingNewWork`, `showingSettings`, `showingTeachingForHostname`, `resolvingDuplicateSet`, `mergingWorkID`, `presentedAnnouncement`, every other `Bool`/optional driving `.sheet`/`.fullScreenCover`/`.popover` on `ContentView`, `CompactRootView` or `WideRootView` | yes, derived in `isEditing` |+| Local `.sheet`/`.fullScreenCover`/alert in views — as implemented: every presentation of `WorkDetailView` (one `presentsSheet` expression, the cover viewer included), `EntryDetailView`'s draft and sheets, the Work, Series and Creator edit modes, `SeriesDetailView`'s picker, `URLIdentityReviewView`'s recalculate sheet, `StatsView`'s date picker and the `DocumentExporter` share sheet (Q64) | yes, via the modifier on the presenting view |+| `selectedTab`, paths, selections | no: navigation, not drafts |++## Components and Interfaces++### Core (`AsterismCore`)++`LibraryRepository+Intents.swift`:++```swift+public struct WorkSummary: Sendable, Hashable { id, displayTitle, readingStatus, workStatus }+func workSummaries(ids: [UUID]) async throws -> [WorkSummary]              // missing ids omitted+func workSummaries(titleContaining: String) async throws -> [WorkSummary]  // case+diacritic-insensitive, titleOrder+func workSummaries(readingStatuses: Set<ReadingStatus>) async throws -> [WorkSummary]+func pageMatch(rawURL: String) async throws -> PageMatch?+func createWorkUnlessPresent(_ draft: NewWorkDraft) async throws -> CreateWorkOutcome  // .created(WorkSnapshot) | .present(PageMatch)++public enum PageMatch: Sendable { case work(WorkSummary), unattachedEntry(captureTitle: String) }+```++- **`WorkSummary`** is the group's deterministic representative, the same one `WorkSnapshot` presents, one per UUID. The reads fetch `Work` rows only, under a shared lease.+- **`pageMatch`** implements Req 3.5. It works within the URL's hostname (`HostnameNormalizer.fromRawURL`) and has two arms:+  - **Entries:** the candidate set `captureLookup` builds for the URL (the raw URL plus the site's rule candidates), compared with each entry's `entryIdentityKey` or `conservativeIdentityKey`. This is exactly capture's match.+  - **Works:** `EntryIdentityNormalizer.key(forRawURL:)` of the page URL, compared with the same key of each membership's `workURLString`. This normalises scheme, host, port and tracking parameters. A trailing slash or a fragment still makes a different page, as it does for capture (Q35).+  - A work match wins over an entry match. Among works, the first by `titleOrder` is taken. An entry that has a work reports that work (Q31).+- **`createWorkUnlessPresent`** runs `pageMatch` and `createWork`'s body inside one exclusive `withLockedContext` and one save. A match committed after the intent's first check therefore still prevents creation. `createWork` is refactored into a private context-taking body that both call; its behaviour is unchanged.++`IntentAnswers.swift`, pure functions with no store:++```swift+static func releasingToday(_ p: TodayPresentation, currentDay: CivilDay, calendar: Calendar) -> [ReleaseAnswer]  // (workID, title, notedToday)+static func notesToday(_ p: TodayPresentation, currentDay: CivilDay, calendar: Calendar) -> [NoteAnswer]       // (title, chapterLine?, note)+static func dialog(for: [ReleaseAnswer]) -> (full: String, supporting: String)+static func dialog(for: [NoteAnswer]) -> (full: String, supporting: String)+```++- **`releasingToday`** returns the release rows of `TodayDayPlan.build(day: currentDay, currentDay: currentDay, …)`, in order. `notedToday` is `line == .notedOnDay`.+- **`notesToday`** returns that plan's noted section, in order (future-dated rows first, as the screen shows them). It drops rows whose trimmed note is empty. The title is `workDisplayTitle ?? captureTitle`, and `chapterLine` is the row's `chapterTitle`, which is already title-else-sequence.+- **Dialogs:** `full` names every item when there are at most five. Above five it states the count and names the first five (Req 2.4). The empty cases use the fixed sentences of Reqs 1.2 and 2.3.+- **The day:** the intent mints `CivilDay(Date(), calendar:)` at run time with the model's `calendarSource()` (Req 1.4).++### App target (`Asterism/Asterism/Intents/`)++The share extension targets do not include this folder, and `AsterismCore` never imports `AppIntents` (Q27).++| Type | Modes | Result |+|---|---|---|+| `ChaptersReleasingTodayIntent` | `.background` | `ReturnsValue<[WorkEntity]> & ProvidesDialog & ShowsSnippetView` |+| `NotesFromTodayIntent` | `.background` | `ProvidesDialog & ShowsSnippetView` |+| `AddPageToReadIntent` | `.background` | `ReturnsValue<WorkEntity?> & ProvidesDialog` |+| `OpenTodayIntent` | `[.background, .foreground(.dynamic)]` | `ProvidesDialog` |+| `OpenWorkIntent` | `[.background, .foreground(.dynamic)]` | `ProvidesDialog` |+| `WorkEntity`, `WorkEntityQuery: EntityStringQuery, EntityPropertyQuery` | — | — |+| `AsterismShortcuts: AppShortcutsProvider` | five App Shortcuts | — |+| `IntentLog` = `PipelineLog(category: "AppIntents")` | — | — |++The add and open intents keep their decision logic in plain types, `AddPageToReadFlow` and `OpenTargetFlow`, which take the broker, navigation, the title fetcher and closures for each prompt and for foregrounding. The intents map those closures to `requestValue`, `requestChoice` and `continueInForeground`, so the flows are unit-tested without the App Intents runtime.++Every intent sets `authenticationPolicy = .requiresLocalDeviceAuthentication` (Req 6.3). Every intent declares `perform()` `@MainActor` and reads `AppLibraryModel` (for `model.intentBroker`) and `AppNavigation` through `@Dependency` (Q64). Each logs one outcome line at `.default` (notice). Reasons are public; titles, URLs and note text go through `content:` (Req 6.7).++**`WorkEntity`** carries `id: UUID` and `title`, `readingStatus` and `workStatus` as display strings. `WorkEntityQuery`:++| Member | Returns |+|---|---|+| `entities(for:)` | `workSummaries(ids:)`. A missing id is omitted, so the system reports it as not found (Reqs 4.4, 5.3). |+| `entities(matching:)` | `workSummaries(titleContaining:)` (Req 5.2). |+| `EntityPropertyQuery` | A `title` contains-comparator over the same read, which gives Shortcuts its "Find Works" action (Req 5.2). |+| `suggestedEntities()` | `workSummaries(readingStatuses: [.reading, .catchingUp])` (Req 5.4). |++Every query goes through the broker, so it waits while the library opens (Req 4.6). It throws `.unavailable` when the library is unavailable. On iOS it throws `IntentLockedError` while `UIApplication.isProtectedDataAvailable` is false, so the system asks for an unlock instead of answering "not found" (Req 6.3, Q34). The open-work App Shortcut phrase is parameterised on `\(\.$work)`.++**`AddPageToReadIntent`** takes `url: URL?` ("Web page") and `title: String?`. Whitespace-only counts as unset.++1. If `url` is nil, ask `$url.requestValue("Which page?")`. A page Siri supplies from the screen arrives as a set `url` (Req 3.8).+2. Refuse a non-HTTP(S) scheme with a dialog (Req 3.6).+3. `broker.withLibrary { try await $0.pageMatch(rawURL:) }`. A match answers per Req 3.5 and returns.+4. Choose the title:+   - If `title` is set, use it and skip the rest of this step (Req 3.2).+   - Otherwise fetch with `BoundedPageTitleFetcher().fetch(url:)?.title` (3 s, 64 KB). A throw or timeout counts as no title.+   - If a title came back, ask `requestChoice(between: ["Use “<title>”", "Change title", .cancel])`.+   - On "Change title", or when there is no fetched title, ask `$title.requestValue("What should it be called?")`, repeating while the answer is blank (Req 3.3). See Decision 3.+5. `broker.withLibrary(writes: true) { try await $0.createWorkUnlessPresent(NewWorkDraft(displayTitle:, hostname: url.absoluteString, readingStatus: .toRead)) }`. On `.present`, answer as in step 3. On `.created`, return the entity.++Cancelling any prompt throws the system cancellation before step 5, so nothing is written (Req 3.7).++**Open intents.** Both take the same path:++1. Check the target through the broker.+   - `OpenWorkIntent`: `workSummaries(ids:)`. If the work is gone, answer "I couldn't find that work" and stay in the background (Req 4.4).+   - If the broker throws `.unavailable`, skip the check (Req 4.6).+2. If `navigation.isEditing`, answer "You're editing something in Asterism." Bring the app forward without routing (Req 4.5).+3. Otherwise, set `navigation.intentRoute = IntentRoute(target:, revision: navigation.revision)` and answer "Opening …".+4. If `systemContext.currentMode.canContinueInForeground`, call `continueInForeground(alwaysConfirm: false)`. Otherwise the answer from step 2 or 3 stands and the route waits for the next activation.++`AppNavigation.revision` is incremented by every reader navigation: tab change, path push or pop, and selection. `takeIntentRoute(model:)` runs when the library is ready. It drops the route if `revision` moved since the route was set, or if `isEditing` became true. For `.work(id)`, it also drops the route if the id is not in `workTitlesByID`, silently: that id was never checked, because step 1 was skipped. Otherwise it applies the route:+- `.today`: `selectedTab = .today`, `todaySelection = .current`, clear `todayPath`.+- `.work(id)`: `showWork(id)`.++The route is applied after the Mac's `restoreSelection()`. On the Mac the `Window("Asterism", id: "main")` scene is single-instance, so it is "the frontmost Asterism window"; see Risks for reopening it.++## Error Handling++| Condition | Answer | Writes |+|---|---|---|+| `IntentLibraryError.unavailable` (no marker or store, marker not current, validation failure, lease timeout, `state == .unavailable`) | "Your Asterism library isn't available right now." Open intents foreground on the app's own state instead (Req 4.6). | none |+| Device locked | System unlock prompt, from `authenticationPolicy` on intents and `IntentLockedError` on queries | none |+| Bad scheme, or a `createWork` refusal (`invalidInput`, off-host, a refusing diagnosis) | The refusal's reason, from `LibraryRepositoryError`'s existing description | none |+| Title fetch throws or times out | Treated as no fetched title | — |+| `ExportOwedMarker.mark()` throws after a cold write | Logged; the work is written and exports on the next foreground mirror run (Req 6.5) | the work |++## Data Models++There is no store change. `WorkSummary`, `PageMatch`, `CreateWorkOutcome`, `ReleaseAnswer` and `NoteAnswer` are Sendable value types in Core. `IntentRoute` (target `.today` or `.work(UUID)`, plus a revision) is app-side and held only in memory.++## Risks and Assumptions++- Risk: `openForExtension`'s full `validateStore` on each cold step is too slow for the owner's library inside Siri's 30 s, most of all for a query followed by a write | Verify: `IntentLog` records open and step milliseconds; a `Development` phone run in the first implementation phase | If wrong: keep a cold session open for a few seconds after a step so consecutive steps share it, and record that in the decision log.+- Risk: Siri does not fill `url` from Safari's current page | Verify: phone check with `Development` on the 27 release | If wrong: no change; Req 3.8's prompt covers it.+- Risk: `requestChoice` by voice does not offer "Change title" in a usable way | Verify: phone check with `Development` | If wrong: use `requestConfirmation`, and ask for a title when the reader declines.+- Risk: on macOS, foregrounding with the `main` window closed does not reopen it | Verify: Mac check with `Development` | If wrong: a view in the `Settings` scene registers `openWindow` into `AppNavigation` at launch, and `takeIntentRoute` calls it.+- Assumption: a background intent launch runs `App.init` without connecting a scene | Verify: the first intent task logs the scene state on a phone and on the Mac.+- Assumption: `isProtectedDataAvailable` turns false soon after locking. The window of about 10 s after a lock is accepted against Req 6.3 (Q36) | Verify: phone check with `Development`.++## Testing Strategy++`make test-core` (Swift Testing, Core):++| Area | Tests |+|---|---|+| `IntentAnswers.releasingToday` | Equals the plan's release rows for fixtures across weekdays. Excludes catching-up and to-read works. Sets the `notedToday` flag. Runs for a `currentDay` after midnight, independent of any publication (1.1–1.4). |+| `IntentAnswers.notesToday` | Order, including future-dated rows first. Blank and whitespace notes dropped. An unattached entry's title falls back to the capture title. The chapter line falls back from title to sequence to nil (2.1–2.3). |+| `IntentAnswers.dialog` | Zero, one, five and six items. The empty-case sentences (1.2, 2.3, 2.4). |+| `workSummaries` | One summary per UUID group. `titleContaining` matches "Mère" with "mere". Missing ids omitted. The status filter (5.1–5.4). |+| `pageMatch` / `createWorkUnlessPresent` | Entry match by raw URL and by rule candidate. Work match despite scheme case, host case, a tracking parameter, or a URL stored with `https://` added; no match across a fragment or a trailing slash. An unattached entry. A work beating an entry. With no match, it creates `toRead`/`ongoing` with the confirmed URL, as `createWork` would. A match inserted before the commit prevents creation. Refusals propagate (3.4–3.6). |++`make test-quick` (app unit tests, `Development`):++| Area | Tests |+|---|---|+| `IntentLibraryBroker` | Resident step, with a refresh after a write. A cold step opens, runs and shuts down, and marks export owed only after a write. An unavailable library throws. A waiting step waits for opening and then runs on the resident library. Two concurrent steps run in FIFO order. `drain()` resolves only after the in-flight step finishes. Export is skipped while busy (6.2, 6.4, 6.5). |+| `AppNavigation` | `isEditing` for each sheet flag and for the modifier. `takeIntentRoute` for `.today` and `.work`. The route is dropped on a revision change, on editing, and on an unknown id. It is applied after the Mac restore (4.1, 4.2, 4.5, 4.6). |+| Shortcut parameters | `refresh` calls the update only when the set changes (5.4). |+| `AddPageToReadFlow` | Missing URL asks; bad scheme refuses; pre-check and commit matches answer; a supplied title skips prompts and a blank one counts as unset; the choice and re-ask; cancel writes nothing (3.1–3.9). |+| `OpenTargetFlow` | Not found stays in the background; unavailable skips the check; editing answers and routes nothing; the route carries the revision; no foreground when it is not allowed (4.1–4.6). |++`make test-performance-m4`: two budgeted arms in `M4ToleratedScalePerformanceTests`, modelled on `todayPublication`: `intent-releasing-today` and `intent-notes-today`. Each is `todayPresentation` plus the `IntentAnswers` call, with the store open outside the timing, a 2 s median budget asserted outside any known-issue block and no separate ceiling (6.6, Q43). The target's test count moves from 47 to 49.++`make verify-identity`: the display-name check fails when the names are equal (7.3).++By hand on `Development`, as the owner's runbook written in the tasks phase:+- Siri phrases on the phone and the Mac with both apps installed (7.1–7.3).+- Lock-screen behaviour for intents and queries (6.3).+- A Safari page and the title choice by voice (3.1, 3.8).+- Cold-step timing.+- Open Today and open work with a sheet or an edit mode open (4.5).+- A cold-created work reaching a second device after the next foreground (6.5).++`AppIntentsTesting` needs the 27 SDK and is not used (Q33).
specs/app-intents/implementation.md Added +382 / -0
diff --git a/specs/app-intents/implementation.md b/specs/app-intents/implementation.mdnew file mode 100644index 00000000..624ed681--- /dev/null+++ b/specs/app-intents/implementation.md@@ -0,0 +1,382 @@+# Implementation notes: App Intents++## Phase 3: Intents (tasks 12–18)++### What landed++All in `Asterism/Asterism/Intents/`, which only the app target compiles (the+share extensions' synchronized groups are their own folders).++| File | What it is |+|---|---|+| `WorkEntity.swift` | `WorkEntity`, `WorkEntityLookup` (the query logic, testable), `WorkEntityQuery` (`EntityStringQuery` + `EntityPropertyQuery` over the title), `IntentLockedError` |+| `ShortcutParameters.swift` | Calls `AsterismShortcuts.updateAppShortcutParameters()` only when the reading/catching-up id→title set changes |+| `ChaptersReleasingTodayIntent.swift`, `NotesFromTodayIntent.swift` | The two read intents; one broker step each |+| `AddPageToReadFlow.swift`, `AddPageToReadIntent.swift` | The add flow (plain type) and its App Intents shell |+| `OpenTargetFlow.swift`, `OpenTodayIntent.swift`, `OpenWorkIntent.swift` | The open flow and its two shells |+| `IntentOutcome.swift` | The unavailable sentence, the refusal sort, a one-sentence snippet |+| `AsterismShortcuts.swift` | Five App Shortcuts; the open-work phrase is parameterised on `\.$work` |++`AppLifecycle.isProtectedDataAvailable` is the platform seam for the lock check+(true on the Mac). `AppLibraryModel.intentCalendar` exposes the model's calendar+source so the read intents mint Today the way the screen does.++### Choices the design left open++- **`ShortcutParameters.refresh` is called from `refreshAll()` only, not from+  `publishToday()`.** `publishToday()` holds only `todayPresentation`, whose+  schedule lists the reading works *with release days* and the catching-up ones —+  not every reading work. Refreshing from it would register part of the set and+  then, at the launch tail's `refreshAll()` a moment later, the whole set: two+  registrations for one launch, the first one wrong. `refreshAll()` follows every+  launch and every mutation.+- **The read intents make one broker step each.** The releases intent reads+  `todayPresentation` and then `workSummaries(ids:)` for the returned work+  values inside the same closure, so a cold library is opened once.+- **The Find Works comparators are one broker step.** Several contains-+  comparators are read in one closure and combined (`.and` intersects, `.or`+  unions, title order kept); a descending sort reverses before the limit.+- **`IntentLockedError`** is a plain error whose message asks for an unlock.+  App Intents has no predefined "device locked" error to throw instead.+- **Intents and the entity are plain structs**, not `nonisolated`: under the+  target's default main-actor isolation, `nonisolated` on a type with+  `@Parameter`/`@Property`/`@Dependency` wrappers warns on every wrapped+  property. `perform()` is `@MainActor` as the design says.+- **Dialog wording** (not fixed by the design): "“X” is already in your library,+  as Reading."; "That page is already in your library, captured as a chapter+  that isn't part of a work."; "Added “X” as To read."; "Asterism can only add a+  web page, with an http or https address."; a library refusal is "Asterism+  couldn't add that page. " plus `LibraryRepositoryError`'s own description;+  open intents say "Opening Today." / "Opening “X”." / "Opening that work." (the+  last when the check was skipped as unavailable).+- **A failed (not unavailable) broker step** in a read or open intent is thrown+  on with its own error; only the add flow words a refusal into its dialog+  (Req 3.6).++### Task 14: cold-path verification on the Mac — owed++**Not run.** The `shortcuts` CLI can only run a shortcut that already exists,+and `shortcuts list` on this Mac holds none that runs an Asterism intent. A+`.shortcut` file can be signed from the command line, but importing it opens the+Shortcuts app's "Add Shortcut" confirmation, which needs a click — UI automation,+which this phase does not do. No timings were measured or estimated.++What was checked instead, without launching anything: `make build-mac` built+the `Development` Mac app, and its `Contents/Resources/Metadata.appintents/extract.actionsdata`+lists the five intents (`AddPageToReadIntent`, `ChaptersReleasingTodayIntent`,+`NotesFromTodayIntent`, `OpenTodayIntent`, `OpenWorkIntent`), the `WorkEntity`+entity and five App Shortcuts.++What the owner needs to do, `Development` only (the app named Devsterism after+task 19; before it, "Asterism" with bundle id `me.nore.ig.Asterism.dev`):++1. `make build-mac`, then run the built `Development` app once so the system+   registers its App Shortcuts, and quit it (⌘Q). Never the `Personal` product.+2. In the Shortcuts app on the Mac, create two shortcuts, each with one action:+   **Chapters Releasing Today** and **Notes from Today** (search the app's name).+   Name them, say, `ast-releasing` and `ast-notes`.+3. Stream the log in a terminal:+   `log stream --predicate 'subsystem == "me.nore.ig.Asterism" AND category == "AppIntents"' --level info`+   (`PipelineLog`'s subsystem is `me.nore.ig.Asterism` in both configurations;+   the category is `AppIntents`.)+4. With the app quit, run `shortcuts run ast-releasing`, then+   `shortcuts run ast-notes`. Each cold run logs one+   `cold step: open <n> ms, step <n> ms, succeeded | scene=<none|connected>`+   line from the broker and one outcome line from the intent.+5. Record here: the scene state (the design assumes `none` for a background+   launch), and the open and step milliseconds for each intent.+6. If a cold step is too slow for Siri's 30 s — most of all the add intent's+   pre-check followed by its write, two opens — apply the design's fallback+   (keep a cold session open for a few seconds after a step so consecutive+   steps share it) and log the decision.++### Tests++- `WorkEntityQueryTests` (8): over a real repository in a temporary root.+- `AddPageToReadFlowTests` (14): over `MockLibraryProvider`, which gained+  `pageMatch`, `createWorkUnlessPresent` and `workSummaries(ids:)`.+- `OpenTargetFlowTests` (6).++The broker holds its model `unowned`; a test that builds a model inside a helper+has to keep it alive for the test's length, or the first step crashes the test+host (seen here as twelve tests "failing" with nothing recorded).++## Phase 4: the display name (task 19)++`make verify-identity` was confirmed both ways on 2026-09-24 by swapping a copy of+`project.pbxproj` into place and restoring the real file afterwards:++- Development and Personal both declaring `Asterism`: exit 2, "both declare+  INFOPLIST_KEY_CFBundleDisplayName 'Asterism' … (Req 7.3)".+- Development's value removed: exit 2, "declares no INFOPLIST_KEY_CFBundleDisplayName".+- The real file: exit 0, three targets checked.++The built `Development` Mac product's `Info.plist` reads `CFBundleDisplayName =+Devsterism`. The check compares only the configurations named `Development` and+`Personal`; a renamed or third configuration would not be compared.++## Implementation explanation++Written at pre-push review (2026-09-24) over `bbdcd8b6..e60c0564`.++### Beginner level++#### What changed++Before this branch, the only way into the reading library was to open the app.+Now Siri and the Shortcuts app can use it directly. There are five new actions:++- **Chapters releasing today**: Siri lists the works that have a chapter due+  today, in the order the Today screen shows them.+- **Notes from today**: Siri reads out the notes made today. Above five it gives+  the count and the first five.+- **Add as to read**: saves a web page as a new work marked "to read", after+  confirming its title. If the page is already in the library, it says so and+  adds nothing.+- **Open Today** and **Open work**: bring the app forward on Today or on a+  named work.++Works also become a value that Shortcuts can pass between actions, and there is+a "Find Works" action that searches by title.++#### Why it matters++The reader can ask what to read, or save a serial for later, without opening+the app. The answers come from the same code the Today screen uses, so Siri and+the screen cannot disagree.++#### Key concepts++- **App Intent**: Apple's way for an app to offer actions to Siri and Shortcuts.+  The system can start the app in the background to run one, with no window.+- **Cold vs. resident**: if the app is already running with its library open+  (resident), the action uses that. If the app was started only for the action+  (cold), the action opens the library briefly, as the share extension does,+  and closes it again.+- **Broker**: a doorkeeper that lets one library action through at a time and+  decides whether to use the open library or open a short cold session.+- **Edit guard**: if the reader is in the middle of editing something, an+  "open" action brings the app forward but does not navigate away, so the+  unsaved draft is not lost.++### Intermediate level++#### Changes overview++- **Core (`AsterismCore`)**:+  - `LibraryRepository+Intents.swift` adds the reads (`workSummaries` by ids,+    title search or reading status), `pageMatch` (Req 3.5's duplicate check)+    and `createWorkUnlessPresent`.+  - `IntentAnswers.swift` holds the pure functions that turn a+    `TodayPresentation` into release and note answers and their spoken+    dialogs.+  - `createWork` was split into `validatedNewWork` (the form's refusals) and+    `insertWork` (the write in a caller's lock), so the intent refuses exactly+    what the New Work form refuses.+  - `captureLookup` was split into `captureCandidates` and `captureMatches`, so+    the duplicate check matches entries the way capture does.+  - `WorkSnapshot.titleOrder` got a title-and-id body that `WorkSummary`+    shares.+- **App target (`Asterism/Asterism/Intents/`)**:+  - The five intents, `WorkEntity` with `WorkEntityQuery`, `AsterismShortcuts`+    and `ShortcutParameters`.+  - `IntentLibraryBroker` and `IntentLog`.+  - The decision logic lives in `AddPageToReadFlow` and `OpenTargetFlow`,+    plain types that the intents wrap.+- **Plumbing**:+  - `AsterismApp.init` builds the model and navigation and registers them with+    `AppDependencyManager`.+  - `bootstrap()` drains the broker before teardown.+  - The background-export pass holds the broker's turn around its open and its+    shutdown.+  - `AppNavigation` gains `intentRoute`, `revision` and `isEditing`, and the+    `.intentEditSession(active:)` modifier. `ContentView` takes the route on+    `.ready`, after the Mac restore, and when a route arrives at a window that+    is already ready.+- **Identity**:+  - `Development` is displayed as "Devsterism".+  - `verify-identity.sh` fails when the two app configurations share a display+    name (Req 7.3).++#### Implementation approach++- **Mutual exclusion.** The broker is a FIFO of continuations on the main actor.+  The main actor alone does not exclude, because it is reentrant at every+  `await`.+- **Three arms.** A step runs:+  - on the resident repository when `state == .ready`;+  - not at all when the state is `.unavailable`;+  - on a cold `openForExtension` session otherwise.+- **Waits for bootstrap.** A step that arrives during a bootstrap waits on+  `libraryReady()`. A step that was already queued when a bootstrap started+  gives its turn back when it reaches the front. Bootstrap drains the queue and+  never cancels a step, so no write is torn and none is retried (Decision 4).+- **After a write.**+  - The caller says whether the step wrote, with `writes:` or with+    `wroteIf:`.+  - A resident write refreshes the snapshots in a task after the answer.+  - A cold write leaves an `ExportOwed/` marker.+  - Neither schedules a reconcile (Req 3.9).+- **One lock for check and write.** `createWorkUnlessPresent` runs+  `pageMatch` and `insertWork` under one exclusive lock and one save, so a+  match committed between the pre-check and the write still prevents+  creation.+- **Open intents.**+  - They check that the work exists, then set an `IntentRoute` stamped with+    `AppNavigation.revision`, then call `continueInForeground`.+  - The window drops the route if the reader navigated since+    (`revision` moved), if an edit is open, or if the work id is unknown.+  - Restore, prune and normalise run under `withoutRevision`, so only the+    reader's own moves count as navigation.++#### Trade-offs++- **App process, not an App Intents extension** (Decision 1). This adds no+  target and no second mirroring process. The cost is that a cold intent pays+  a store open inside Siri's timeout.+- **One step per cold session** (Decision 4). There are no lifetime rules for+  queries the system calls at arbitrary times. The cost is a `validateStore` on+  every cold step, twice for an add. A keep-alive fallback is held in reserve+  until the owner's Mac timing (Q60).+- **Mirroring off on cold sessions** (Q38). A cold-created work reaches+  CloudKit on the next grant or foreground, not at once.+- **The edit guard fails safe** (Q37). Any sheet blocks navigation, including a+  harmless one, and the reader is told why.+- **Answers are composed from the full Today read** (Q28). This guarantees+  equality with the screen. The cost is about 0.9 s against a 2 s budget.++### Expert level++#### Technical deep dive++- **Admission and bootstrap.** `withLibrary` loops over three steps: wait on+  `libraryReady()` if `bootstrapInFlight`, take the turn, and re-check. The+  re-check (`bootstrapInFlight && state == .loading`) releases the turn and+  loops. Without it, a queued step would either run cold beside the container+  bootstrap is building, or hold the turn and deadlock `drain()`.+  `drain()` resolves only when `release()` finds the queue empty.+- **Export interplay** (Q51, Q65).+  - `acquire()` skips a pass while `isBusy`.+  - The pass takes `holdingTurn` synchronously after that check, with no+    suspension in between, around `openColdSession`. A step that arrives+    during the open queues, then borrows `backgroundSession`.+  - `release()` shuts the session down inside `holdingTurn` and re-reads the+    session inside the turn, because a second `release()` can have taken it.+  - Together these rule out two containers in one process and a borrowed+    session that is shutting down.+- **Deferred refresh** (Q68). A resident write's refresh+  (`refreshDiagnosesAndSnapshots`, about 3 s at scale) runs in+  `pendingWriteRefresh`, outside the turn. A later step or a bootstrap may+  interleave with it, which the refresh already tolerates.+- **`pageMatch`.**+  - It works within `HostnameNormalizer.fromRawURL(url)`.+  - The entry arm reuses capture's candidate set: the raw URL plus the v2 and+    v3 rule candidates, matched against `entryIdentityKey` or+    `conservativeIdentityKey`.+  - The work arm compares `EntryIdentityNormalizer.key(forRawURL:)` on both+    sides, so scheme case, host case, trackers and an added `https://` are+    equal, while a fragment or a trailing slash still differ (Q35).+  - A work match wins over an entry match, and among works `titleOrder`+    picks. An entry that has a work reports that work (Q31). Among several+    unattached entries the least UUID is named (Q47).+- **`workSummaries`** buckets `Work` rows by UUID.+  - A single-row bucket is summarised from the row itself (Q69).+  - Only a multi-row bucket builds the group and fetches the type directory.+    Before Q69, every Siri query faulted every work's memberships.+- **Route timing.** The route is applied after the Mac's `restoreSelection()`,+  which runs under `withoutRevision`, so a restore neither overwrites the+  route nor invalidates it. A `.today` route also clears+  `selectedTodayEntryID`, because the compact tree kept the entry pushed+  (Q52).+- **Edit sessions.**+  - A session is a token in `AppNavigation.editSessions`.+  - It is registered from `onChange(of:initial:)` and removed on `active ==+    false` or by the registration's `isolated deinit`, not on `onDisappear`.+  - A tab that is switched away disappears with its editor still open (Q54).++#### Architecture impact++- `openForExtension` now has two callers, the share extension and the intent+  broker. `CLAUDE.md` names the broker as the app's one mirroring-off opener.+- Any future change to the extension opener's refusals applies to Siri too.+- `bootstrap()` and the background-export pass now both depend on the broker.+  A new scene-less library user must go through `holdingTurn`, or it+  reintroduces the two-container race.+- `AppNavigation.revision` is a new invariant. Every navigation property's+  `didSet` bumps it, so a new navigation property that does not do the same+  would let a stale route override the reader's move.+- The edit guard is opt-in for local presentations. A new sheet or edit mode+  that forgets `.intentEditSession(active:)` is not protected. The+  `AppNavigation` flags are protected structurally.++#### Potential issues++- **Cold-step latency.** It is unmeasured on the owner's library (Q60). An add+  opens twice. If the Mac run shows slow `validateStore` opens, the keep-alive+  fallback changes Decision 4's one-step lifetime.+- **Lock window.** `isProtectedDataAvailable` lags a lock by about 10 s, and+  entity queries rely on it (Q36, accepted).+- **Mac window.** Whether foregrounding reopens a closed `main` window is a+  recorded risk, covered by the runbook's section 7.+- **Collapsed works.** A saved work reference to a work that was collapsed into+  another reports not found by design (Q14).+- **Identity check.** `verify-identity` compares only the configurations named+  `Development` and `Personal`. A renamed or third configuration escapes it.++## Completeness Assessment++### Fully implemented++- **Req 1, chapters releasing today (1.1–1.4)**: `IntentAnswers.releasingToday`+  over `TodayDayPlan.build` for a freshly minted `CivilDay`, dialogs, and+  `[WorkEntity]` values.+- **Req 2, notes from today (2.1–2.4)**: `IntentAnswers.notesToday`, blank notes+  dropped, the capture-title and chapter-line fallbacks, and the five-item+  spoken cut.+- **Req 3, add as to read (3.1–3.9)**: `AddPageToReadFlow`, which covers the+  bounded title fetch, the choice then the question (Decision 3), the+  blank-title re-ask, the scheme refusal, the pre-check and the commit-time+  check under one lock, cancellation before any write, and no added reconcile.+- **Req 4, open Today and open a work (4.1–4.6)**: `OpenTargetFlow`,+  `IntentRoute` with the revision, the edit guard, the not-found answer+  without foregrounding, and routing while the library is opening or+  unavailable (Q66).+- **Req 5, works as Shortcuts values (5.1–5.4)**: `WorkEntity`, the string and+  property queries, suggested entities, and the parameterised open-work+  phrase.+- **Req 6, library safety and privacy (6.1, 6.2, 6.4–6.7)**: the broker's three+  arms, the drain and export exclusion, the `ExportOwed/` marker, the two M4+  arms inside their 2 s budget (0.914 s and 0.888–0.904 s), and `IntentLog`+  with content private outside `Development`.+- **Req 6.3, device unlocked**: `authenticationPolicy` on every intent and+  `IntentLockedError` on queries. It is not verified by hand; see below.+- **Req 7, discoverability (7.1–7.3)**: five App Shortcuts, both+  configurations, the Devsterism display name, and the `verify-identity`+  check.++### Partially implemented++These are verified by the owner, not an agent (`prerequisites.md`, Q60):++- **Task 14, the Mac cold-path timing.** It is not run, and no timings exist.+  The keep-alive fallback waits on it.+- **The phone runbook (`runbook.md`).** It covers the Siri phrases with both+  apps installed (7.1–7.3), the lock screen (6.3), a Safari page by voice+  (3.1, 3.8), open with an editor open (4.5), a cold-created work reaching+  the Mac (6.5), and reopening the Mac's main window (4.1).++### Covered only by review, with no automated test++- The `.intentEditSession` modifier's lifecycle: registration, and removal+  through `isolated deinit`.+- `ContentView`'s three route triggers: `.ready`, after the Mac restore, and a+  route that reaches a window that is already ready.+- The release intent's composition of `todayPresentation` plus+  `workSummaries(ids:)` into `[WorkEntity]` (Req 1.3). The pure answer is+  tested; the intent shell is not.+- `verify-identity`'s display-name check. It was confirmed by hand in both+  directions (phase 4 above).++### Missing++- Nothing. No requirement is unimplemented.
specs/app-intents/prerequisites.md Added +9 / -0
diff --git a/specs/app-intents/prerequisites.md b/specs/app-intents/prerequisites.mdnew file mode 100644index 00000000..2de41c98--- /dev/null+++ b/specs/app-intents/prerequisites.md@@ -0,0 +1,9 @@+# Prerequisites for App Intents++These tasks must be completed by the user before or during implementation.++## Before Testing++- [ ] Time the cold intent path on the Mac with the `Development` app, following "Task 14: cold-path verification on the Mac — owed" in `implementation.md`: create the two one-action shortcuts in the Shortcuts app, run them with `shortcuts run` while the app is quit, and record the `cold step` log lines there. If a cold step is slow, the design's keep-alive fallback is applied afterwards (Q60).++- [ ] Run `runbook.md` on the phone with the `Development` app once every task is done. Siri voice, the lock screen and Safari's current page cannot be driven by an agent.
specs/app-intents/requirements.md Added +117 / -0
diff --git a/specs/app-intents/requirements.md b/specs/app-intents/requirements.mdnew file mode 100644index 00000000..9dfd41e8--- /dev/null+++ b/specs/app-intents/requirements.md@@ -0,0 +1,117 @@+# Requirements: App Intents++## Introduction++The library can only be reached by opening the app. This feature makes Asterism's library available to Siri and the Shortcuts app: two read-only questions (which chapters release today, which notes were made today), one write (add a web page as a work to read), and two actions that open the app on Today or on a work. Transit ticket T-2367.++## Non-Goals++- No Spotlight or semantic indexing of works or notes; Siri reaches the library only through the intents below.+- No open-ended questions over note content; that is Q&A over a work's notes, T-2332.+- No widgets, Live Activities or Control Center controls.+- No intent that creates or edits an entry, a note, a character, a place or a rule, and none that edits an existing work.+- No share-sheet path in Asterism's own share extension for adding a to-read work; that stays T-2363.+- No linking of a work added by the intent to the chapters captured later; that is T-2366's matching.+- No forwarding of a saved work reference to the survivor of a duplicate collapse.+- No App Intents extension or other new process; see decision log Decision 1.+- No URL scheme or deep link that other apps can call.+- No localisation beyond English.+- No schema version, readiness marker or archive generation change.++## Definitions++- **Today**: the current civil day in the device's calendar at the moment the intent runs.+- **Releasing today**: a work that the Today screen, built for Today, shows as a release row. Catching-up works, which Today lists every day in their own section, are not releasing today.+- **Noted today**: an entry that the Today screen's noted section, built for Today, shows: an entry whose last share falls on Today, with future-dated shares folded onto Today as that section folds them.+- **Page input**: the URL the add intent receives from a Shortcuts action, from the system share sheet through Shortcuts, supplied by Siri from what is on screen, or typed or spoken by the reader; a Safari web page arrives as its URL.+- **Capture URL key**: the key the capture path uses to decide that a shared URL matches an existing entry.+- **Library unavailable**: no library created yet, a migration pending, an integrity refusal, or the library's store lock held exclusively by another operation past the interactive timeout. A library that is still being opened by the app is not unavailable; it is opening.+- **A work**: a work group as the Works list shows it; rows that share one UUID are one work.++## Requirements++### 1. Chapters Releasing Today++**User Story:** As a reader, I want to ask Siri which chapters release today, so that I know what to read without opening the app.++**Acceptance Criteria:**++1. <a name="1.1"></a>WHEN the reader runs "chapters releasing today", the system SHALL answer with every work releasing today, in the order the Today screen lists them, each by its display title and whether it has been noted today.  +2. <a name="1.2"></a>IF no work is releasing today, THEN the system SHALL answer that no chapters are expected today.  +3. <a name="1.3"></a>The intent SHALL also return the works releasing today as work values that a following Shortcuts action can take as input.  +4. <a name="1.4"></a>For a given library and a given Today, the set and order of works in the answer SHALL equal the release rows of the Today screen built for that day, including when the intent runs just after midnight while an open Today screen still shows the previous day.  ++### 2. Notes Made Today++**User Story:** As a reader, I want to ask Siri what I noted today, so that I can recall my notes without opening the app.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHEN the reader runs "notes from today", the system SHALL answer with every entry noted today that carries a non-blank note, in the order the Today screen's noted section lists them, each as its work's display title, its chapter line and its note text; an entry with no work SHALL be named by its capture title, and the chapter line SHALL be the chapter title, else the chapter number, else omitted, as the Today screen's noted rows name them.  +2. <a name="2.2"></a>An entry noted today whose note is blank SHALL NOT appear in the answer.  +3. <a name="2.3"></a>IF no entry noted today carries a non-blank note, THEN the system SHALL answer that there are no notes from today.  +4. <a name="2.4"></a>WHEN more than five notes qualify, the dialog the system provides SHALL give the count and the first five in the order of [2.1](#2.1), and the shown result SHALL list all of them.  ++### 3. Add a Page as a Work to Read++**User Story:** As a reader, I want to add the page I am looking at as a work to read from Shortcuts, so that I can save a serial for later in one step.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN the reader runs "add as to read" with a page input, the system SHALL ask the reader to confirm a title before anything is written, prefilled with the page's title fetched within 3 seconds and 64 KB, else empty.  +2. <a name="3.2"></a>IF the reader supplies a title with the action, THEN the system SHALL use it and SHALL NOT fetch or ask for a title; a title spoken at the confirmation SHALL replace the prefilled one.  +3. <a name="3.3"></a>IF the confirmed title is blank, THEN the system SHALL ask again and SHALL NOT create a work.  +4. <a name="3.4"></a>WHEN the reader confirms a non-blank title, the system SHALL create one work as the New Work form does for the same URL and title — reading status `toRead`, work status `ongoing`, the page URL as the work's confirmed URL on its site, and the site created if the library does not have it yet — except that [3.5](#3.5) is checked first.  +5. <a name="3.5"></a>IF the page URL, compared by the capture URL key, matches the confirmed URL of a work or the URL of an entry, THEN the system SHALL create nothing and SHALL answer that the page is already in the library, naming the matching work and its reading status, or, where the only match is an entry with no work, saying that the page was captured as an unattached chapter; the check SHALL be repeated when the work is written, so a match committed in between also prevents creation.  +6. <a name="3.6"></a>IF the page URL is not an HTTP or HTTPS URL, or the library refuses the work as the New Work form would refuse it, THEN the system SHALL answer with the reason and SHALL create nothing.  +7. <a name="3.7"></a>IF the reader cancels at any prompt, THEN the system SHALL write nothing.  +8. <a name="3.8"></a>WHEN the intent is started by voice, the system SHALL use the page Siri supplies from the screen as the page input, and IF none is supplied, THEN it SHALL ask for a URL.  +9. <a name="3.9"></a>WHEN a work is created, the intent SHALL return it as a work value that a following Shortcuts action can take as input, and SHALL schedule no reconcile pass beyond what the New Work form schedules.  ++### 4. Open Today and Open a Work++**User Story:** As a reader, I want to ask Siri to open Today or a named work, so that I can get to it in one step.++**Acceptance Criteria:**++1. <a name="4.1"></a>WHEN the reader runs "open Today", the system SHALL bring the app to the foreground showing the Today screen, on iPhone, iPad and Mac; on the Mac it SHALL use the frontmost Asterism window, or open one if none is open.  +2. <a name="4.2"></a>WHEN the reader runs "open work" with a work, the system SHALL bring the app to the foreground showing that work's detail page, in the same window rule as [4.1](#4.1).  +3. <a name="4.3"></a>WHEN the reader names a work by voice or text, the system SHALL resolve it with the query of [5.2](#5.2), and IF more than one work matches, THEN the system SHALL ask the reader to choose.  +4. <a name="4.4"></a>IF the work no longer exists when the intent runs, including when it was removed by a duplicate collapse, THEN the system SHALL answer that it could not be found and SHALL NOT bring the app to the foreground.  +5. <a name="4.5"></a>IF an edit view is open when an open intent runs, THEN the system SHALL bring the app to the foreground with the edit view and its draft unchanged, SHALL NOT navigate, and SHALL answer that an edit is in progress.  +6. <a name="4.6"></a>IF the library is unavailable or still opening when an open intent runs, THEN the system SHALL bring the app to the foreground on the state the app itself shows, and SHALL navigate to the target once the library is ready if it has not been navigated away from.  ++### 5. Works as Shortcuts Values++**User Story:** As a reader building a shortcut, I want to find and pass works between actions, so that I can combine Asterism with other steps.++**Acceptance Criteria:**++1. <a name="5.1"></a>The system SHALL offer works as a value type in Shortcuts, each showing its display title, reading status and work status.  +2. <a name="5.2"></a>The system SHALL offer a "find works" query that returns every work whose display title contains the search text, compared case- and diacritic-insensitively, including finished and abandoned works.  +3. <a name="5.3"></a>A work value SHALL be resolved against the library when an action uses it, so a work renamed since it was found is shown by its current title and one that no longer exists is reported as not found ([4.4](#4.4)).  +4. <a name="5.4"></a>The "open work" Siri phrase SHALL accept a spoken work name for every work whose reading status is `reading` or `catchingUp`; other works SHALL be reachable through the query of [5.2](#5.2).  ++### 6. Library Safety and Privacy++**User Story:** As a reader, I want intents to leave my library as the app does, so that using Siri can never damage, fork or expose it.++**Acceptance Criteria:**++1. <a name="6.1"></a>The intents of requirements 1, 2, 3 and 5 SHALL complete without bringing the app to the foreground.  +2. <a name="6.2"></a>IF the library is unavailable, THEN the intents of requirements 1, 2, 3 and 5 SHALL answer that the library is not available and write nothing; IF it is opening, THEN they SHALL wait for it to open.  +3. <a name="6.3"></a>Every intent SHALL require the device to be unlocked, and nothing from the library SHALL be spoken or shown while it is locked.  +4. <a name="6.4"></a>No intent SHALL create, migrate or re-mark a store. IF the app's window opens while an intent is using the library, THEN the intent SHALL finish or stop between writes before the app opens its mirrored library, with no write half-applied, and the library SHALL never be open for CloudKit mirroring twice at once.  +5. <a name="6.5"></a>A work created by the add intent SHALL reach the reader's other devices no later than the app's next foreground mirror run, as the same kind of change the New Work form makes.  +6. <a name="6.6"></a>The library read behind requirement 1 and the one behind requirement 2, excluding the store open, SHALL each complete within a 2 s median budget over the covered M4 fixture on the host in release, reported as arms of `make test-performance-m4`.  +7. <a name="6.7"></a>Each intent run SHALL be logged with its outcome at notice level; reader content (titles, URLs, note text) SHALL be readable in `Development` builds only, as the model pipelines' logs are.  ++### 7. Discoverability++**User Story:** As a reader, I want the intents available without setup, so that I can use them from Siri straight after installing.++**Acceptance Criteria:**++1. <a name="7.1"></a>Each of the five intents SHALL be offered as an App Shortcut with at least one Siri phrase containing the app's name, available in Siri, Spotlight and the Shortcuts app without the reader creating a shortcut.  +2. <a name="7.2"></a>The intents SHALL be present in both the `Development` and `Personal` apps, and each SHALL act only on the library of the app it belongs to.  +3. <a name="7.3"></a>The `Development` app SHALL carry a display name distinct from `Asterism`, so that its phrases and the `Personal` app's resolve to different apps when both are installed on one device.  
specs/app-intents/runbook.md Added +51 / -0
diff --git a/specs/app-intents/runbook.md b/specs/app-intents/runbook.mdnew file mode 100644index 00000000..c14267fd--- /dev/null+++ b/specs/app-intents/runbook.md@@ -0,0 +1,51 @@+# Runbook: App Intents on the phone++The owner's to run, after every task in `tasks.md` is done. **`Development` only**+(the app named Devsterism). No step installs, launches or drives `Personal`, and none+touches the real library. The Mac's cold-path timing is in `prerequisites.md`; the+Mac's open and phrase checks are section 7 below.++Before starting: install the latest `Development` build and open it once, so its App+Shortcuts register. Leave the installed `Personal` app on the phone as it is — do not+reinstall it — so both apps are present for Req 7.3. Filter Console on+`subsystem:me.nore.ig.Asterism category:AppIntents`.++## 1. Siri phrases resolve to the right app (Reqs 7.1–7.3)++- [ ] Say "What's releasing today in Devsterism". Devsterism answers; Asterism is not asked.+- [ ] Say "Notes from today in Devsterism". It speaks each note; above five it gives the count and five.+- [ ] Open Shortcuts and search "Devsterism". All five actions and Find Works are listed without creating a shortcut.++## 2. Lock screen (Req 6.3)++- [ ] Lock the phone, wait 15 s, and ask the releasing question. Siri asks you to unlock and says nothing about the library first.+- [ ] While still locked, say "Open <a work you are reading> in Devsterism". Siri asks you to unlock and does not speak any title.++## 3. Add a page from Safari by voice (Reqs 3.1, 3.8)++- [ ] In Safari, open a serial's landing page that is not in the dev library. Say "Add this as to read in Devsterism".+- [ ] Record whether Siri used the page or asked for a URL. Either passes; the add intent's log line says `url supplied` or `url asked`.+- [ ] At the title choice, say "Change title", then say a title. The work is created as To read with that title.+- [ ] Repeat on the same page. Siri says it is already in the library, as To read.++## 4. Open with an editor open (Req 4.5)++- [ ] Open a work, tap Edit, change a field, then ask Siri to open Today. The editor stays with your change, and Siri says an edit is in progress.++## 5. A cold-created work reaches the Mac (Req 6.5)++- [ ] Force-quit Devsterism on the phone. Add a page through the Shortcuts app.+- [ ] Open Devsterism on the phone, then open it on the Mac. The work appears on the Mac.++## 6. Open Today and a work by name (Reqs 4.1–4.3, 5.4)++- [ ] With Devsterism in the background on the Works tab, say "Open Today in Devsterism". The app comes forward on Today.+- [ ] Say "Open <a work you are reading> in Devsterism", naming it as its title reads. Siri resolves it without asking which app, and the app opens on that work.+- [ ] Say the same for a work that is on To read. Siri does not offer it as a spoken name; in Shortcuts, Open Work with Find Works still reaches it.++## 7. On the Mac (Reqs 4.1, 4.2, 7.1–7.3)++- [ ] Run the Devsterism Mac app once, then close its main window without quitting. Run Open Today from Shortcuts. Record whether the main window reopens on Today; if it does not, note it — the design names this as a risk.+- [ ] Say or type "What's releasing today in Devsterism" to Siri on the Mac. Devsterism answers.++Record anything that fails in `implementation.md` with the Console lines.
specs/app-intents/tasks.md Added +174 / -0
diff --git a/specs/app-intents/tasks.md b/specs/app-intents/tasks.mdnew file mode 100644index 00000000..8aed3ec1--- /dev/null+++ b/specs/app-intents/tasks.md@@ -0,0 +1,174 @@+---+references:+    - specs/app-intents/requirements.md+    - specs/app-intents/design.md+    - specs/app-intents/decision_log.md+---+# App Intents++## Core reads and answers++- [x] 1. Write failing tests for IntentAnswers release and note answers and their dialogs <!-- id:nhv0kxu -->+  - New Packages/AsterismCore/Tests/AsterismCoreTests/IntentAnswersTests.swift, Swift Testing+  - releasingToday equals TodayDayPlan.build release rows in order across weekdays; excludes catchingUp and toRead works; notedToday matches line == .notedOnDay+  - A currentDay minted after midnight gives that day's answer with no publication involved+  - notesToday keeps the noted section order with future-dated rows first, drops blank and whitespace notes, title falls back to captureTitle, chapterLine is chapterTitle or nil+  - dialog for 0, 1, 5 and 6 items: fixed empty sentences, count plus first five above five+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4)+  - References: specs/app-intents/design.md++- [x] 2. Implement IntentAnswers over todayPresentation and TodayDayPlan.build <!-- id:nhv0kxv -->+  - New Packages/AsterismCore/Sources/AsterismCore/IntentAnswers.swift with ReleaseAnswer and NoteAnswer value types+  - Pure functions only; no store access and no AppIntents import+  - Blocked-by: nhv0kxu (Write failing tests for IntentAnswers release and note answers and their dialogs)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.4](requirements.md#1.4), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4)++- [x] 3. Write failing tests for workSummaries reads <!-- id:nhv0kxw -->+  - New Packages/AsterismCore/Tests/AsterismCoreTests/IntentReadsTests.swift+  - One summary per UUID group, using the same representative WorkSnapshot presents, including a torn same-UUID pair+  - titleContaining matches case- and diacritic-insensitively and returns titleOrder+  - ids read omits missing and collapsed ids; readingStatuses filter returns only reading and catchingUp when asked+  - Stream: 1+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)++- [x] 4. Implement WorkSummary and the three workSummaries reads in LibraryRepository+Intents <!-- id:nhv0kxx -->+  - New Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Intents.swift; add the reads to LibraryProviding+  - Fetch Work rows only under a shared lease; no works() call+  - Blocked-by: nhv0kxw (Write failing tests for workSummaries reads)+  - Stream: 1+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4)++- [x] 5. Write failing tests for pageMatch and createWorkUnlessPresent <!-- id:nhv0kxy -->+  - Extend IntentReadsTests.swift+  - Entry match by raw URL and by a site rule candidate; work match across scheme case, host case, a tracking parameter and a stored https:// prefix; no match across a fragment or trailing slash+  - Unattached-entry match; work match beats entry match; an entry with a work reports the work+  - No match creates toRead, ongoing, with the confirmed URL, as createWork would; a matching entry inserted before the commit makes createWorkUnlessPresent return .present+  - Blank title, off-host URL and a refusing diagnosis still refuse+  - Blocked-by: nhv0kxx (Implement WorkSummary and the three workSummaries reads in LibraryRepository+Intents)+  - Stream: 1+  - Requirements: [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6)++- [x] 6. Implement pageMatch and createWorkUnlessPresent over a shared createWork body <!-- id:nhv0kxz -->+  - Refactor createWork in LibraryRepository.swift into a private context-taking body; createWork behaviour and tests unchanged+  - pageMatch works within HostnameNormalizer.fromRawURL's host: entries through captureLookup's candidate set, works through EntryIdentityNormalizer.key on both sides+  - createWorkUnlessPresent: one exclusive withLockedContext, one save+  - Blocked-by: nhv0kxy (Write failing tests for pageMatch and createWorkUnlessPresent)+  - Stream: 1+  - Requirements: [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [3.9](requirements.md#3.9)++- [x] 7. Add the intent-releasing-today and intent-notes-today M4 performance arms <!-- id:nhv0ky0 -->+  - M4ToleratedScalePerformanceTests.swift, modelled on todayPublication: store opened outside timing, measureDistributionAsync over 20 iterations+  - 2 s median budget via expectWithinBudget and a regression ceiling asserted outside any known-issue block+  - Update the suite and test counts in CLAUDE.md's test-performance-m4 entry from 47 to 49+  - Blocked-by: nhv0kxv (Implement IntentAnswers over todayPresentation and TodayDayPlan.build)+  - Stream: 1+  - Requirements: [6.6](requirements.md#6.6)++## App plumbing++- [x] 8. Write failing tests for IntentLibraryBroker <!-- id:nhv0ky1 -->+  - New Asterism/AsterismTests/IntentLibraryBrokerTests.swift, driving AppLibraryModel with the existing test hooks for openForApp and a temp library root+  - Resident step runs on the resident repository and refreshes after a write+  - Cold step opens via openForExtension, shuts down after, marks ExportOwed only after a write, and never creates a store in an empty root+  - Unavailable state and missing marker throw .unavailable; a step admitted during bootstrapInFlight waits and then runs on the resident repository+  - Two concurrent steps run FIFO; drain resolves only after the in-flight step; background export skips while isBusy; a cold step reuses an open backgroundSession+  - Stream: 2+  - Requirements: [6.2](requirements.md#6.2), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5)++- [x] 9. Implement IntentLibraryBroker and register dependencies in AsterismApp.init <!-- id:nhv0ky2 -->+  - New Asterism/Asterism/Intents/IntentLibraryBroker.swift and IntentLog.swift with PipelineLog category AppIntents+  - AppLibraryModel: bootstrap sets bootstrapInFlight then awaits broker.drain before teardownRepository; acquire skips while broker.isBusy; add libraryReady+  - AsterismApp.init builds model and navigation with State initialValue and registers both with AppDependencyManager.shared+  - Log open and step milliseconds and whether a scene is connected on every cold step; these lines verify the design's cold-step and App.init risks in task 14+  - Amend openForExtension's doc comment to name both callers+  - Blocked-by: nhv0ky1 (Write failing tests for IntentLibraryBroker)+  - Stream: 2+  - Requirements: [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5), [6.7](requirements.md#6.7)++- [x] 10. Write failing tests for AppNavigation intent routes and the edit guard <!-- id:nhv0ky3 -->+  - Extend Asterism/AsterismTests AppNavigation tests+  - isEditing true for each AppNavigation sheet flag and for a registered edit session, false otherwise+  - takeIntentRoute applies .today and .work; drops the route when revision moved, when isEditing, or when the work id is not in workTitlesByID+  - On the Mac path the route is applied after restoreSelection+  - Stream: 2+  - Requirements: [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6)++- [x] 11. Implement intentRoute, revision and isEditing, and register edit sessions in the editors <!-- id:nhv0ky4 -->+  - AppNavigation.swift: IntentRoute, intentRoute, revision bumped on every reader navigation, isEditing, editSessions+  - New .intentEditSession modifier; apply to WorkDetailView, SeriesDetailView, CreatorDetailView edit modes, EntryDetailView with a new EntryDetailModel.hasUnsavedChanges, and every view that presents a local sheet listed in the design's audit+  - ContentView calls takeIntentRoute when model.state becomes .ready and after restoreSelection+  - Blocked-by: nhv0ky3 (Write failing tests for AppNavigation intent routes and the edit guard)+  - Stream: 2+  - Requirements: [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6)++## Intents++- [x] 12. Write failing tests for WorkEntityQuery and ShortcutParameters <!-- id:nhv0ky5 -->+  - New Asterism/AsterismTests/WorkEntityQueryTests.swift over a broker with a resident test repository+  - entities for ids omits missing ids; matching and the property query's title contains-comparator return the same works; suggestedEntities returns reading and catchingUp works+  - Queries throw the locked error when protected data is unavailable, injected through a closure+  - ShortcutParameters.refresh calls the update closure only when the id to title set changes+  - Blocked-by: nhv0kxx (Implement WorkSummary and the three workSummaries reads in LibraryRepository+Intents), nhv0ky2 (Implement IntentLibraryBroker and register dependencies in AsterismApp.init)+  - Stream: 2+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [6.3](requirements.md#6.3)++- [x] 13. Implement WorkEntity, WorkEntityQuery and the ShortcutParameters refresh hook <!-- id:nhv0ky6 -->+  - New Asterism/Asterism/Intents/WorkEntity.swift and ShortcutParameters.swift+  - Call ShortcutParameters.refresh from AppLibraryModel.publishToday and refreshAll+  - Protected-data check is iOS only; the Mac has none+  - Blocked-by: nhv0ky5 (Write failing tests for WorkEntityQuery and ShortcutParameters)+  - Stream: 2+  - Requirements: [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [6.3](requirements.md#6.3)++- [x] 14. Implement the two read intents and AsterismShortcuts, then verify the cold path on the Mac <!-- id:nhv0ky7 -->+  - New ChaptersReleasingTodayIntent.swift, NotesFromTodayIntent.swift and AsterismShortcuts.swift in Asterism/Asterism/Intents; the share extension targets must not include the folder+  - authenticationPolicy requiresLocalDeviceAuthentication, supportedModes .background, perform on the main actor, one notice log line per run+  - Verify on the Mac with the Development app, which needs no approval: quit it, run each read intent through a shortcut with the shortcuts CLI, and read the AppIntents log for scene state and open and step milliseconds+  - Record the timings in specs/app-intents/implementation.md; if a cold step is too slow, apply the design's keep-alive fallback in the broker and log the decision before tasks 15 to 18+  - Blocked-by: nhv0kxv (Implement IntentAnswers over todayPresentation and TodayDayPlan.build), nhv0ky6 (Implement WorkEntity, WorkEntityQuery and the ShortcutParameters refresh hook)+  - Stream: 2+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.4](requirements.md#2.4), [6.1](requirements.md#6.1), [6.3](requirements.md#6.3), [6.7](requirements.md#6.7), [7.1](requirements.md#7.1)++- [x] 15. Write failing tests for AddPageToReadFlow <!-- id:nhv0ky8 -->+  - New Asterism/AsterismTests/AddPageToReadFlowTests.swift; the flow takes injected prompts, title fetcher and broker+  - No url asks for one; a non-HTTP scheme refuses with no write; a pre-check match answers with the work and status, or the unattached-chapter sentence+  - A supplied non-blank title skips fetch and prompts; a blank supplied title counts as unset+  - Fetched title offers the choice; Change title and no fetched title ask for a title and re-ask while blank+  - Cancel at any prompt writes nothing; a .present outcome at commit answers as the pre-check does; .created returns the work+  - Blocked-by: nhv0kxz (Implement pageMatch and createWorkUnlessPresent over a shared createWork body), nhv0ky7 (Implement the two read intents and AsterismShortcuts, then verify the cold path on the Mac)+  - Stream: 2+  - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [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)++- [x] 16. Implement AddPageToReadFlow and AddPageToReadIntent <!-- id:nhv0ky9 -->+  - New AddPageToReadFlow.swift and AddPageToReadIntent.swift; the intent maps prompts to requestValue and requestChoice+  - Title fetch uses BoundedPageTitleFetcher; add the intent's App Shortcut to AsterismShortcuts+  - Blocked-by: nhv0ky8 (Write failing tests for AddPageToReadFlow)+  - Stream: 2+  - Requirements: [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [3.7](requirements.md#3.7), [3.8](requirements.md#3.8), [3.9](requirements.md#3.9), [7.1](requirements.md#7.1)++- [x] 17. Write failing tests for OpenTargetFlow <!-- id:nhv0kya -->+  - New Asterism/AsterismTests/OpenTargetFlowTests.swift with injected broker, navigation and foreground closure+  - Missing work answers not found and never foregrounds; unavailable library skips the check and routes+  - isEditing answers that an edit is in progress, foregrounds and routes nothing; otherwise the route carries the current revision+  - No foreground when canContinueInForeground is false; the route waits+  - Blocked-by: nhv0ky4 (Implement intentRoute, revision and isEditing, and register edit sessions in the editors), nhv0ky7 (Implement the two read intents and AsterismShortcuts, then verify the cold path on the Mac)+  - Stream: 2+  - Requirements: [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6)++- [x] 18. Implement OpenTargetFlow, OpenTodayIntent and OpenWorkIntent with the work phrase <!-- id:nhv0kyb -->+  - New OpenTargetFlow.swift, OpenTodayIntent.swift and OpenWorkIntent.swift; supportedModes background plus dynamic foreground+  - Add both App Shortcuts to AsterismShortcuts; the open-work phrase is parameterised on the work+  - Blocked-by: nhv0kya (Write failing tests for OpenTargetFlow)+  - Stream: 2+  - Requirements: [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [4.5](requirements.md#4.5), [4.6](requirements.md#4.6), [5.4](requirements.md#5.4), [7.1](requirements.md#7.1)++## Identity++- [x] 19. Set the Devsterism display name, add the verify-identity check and update CLAUDE.md <!-- id:nhv0kyc -->+  - project.pbxproj app target: INFOPLIST_KEY_CFBundleDisplayName Devsterism for Development and Asterism for Personal+  - scripts/verify-identity.sh: new check failing when the two values are equal or missing; confirm make verify-identity fails on a deliberately equal copy and passes on the real file+  - CLAUDE.md: display-name column in the configuration table, drop the both-named-Asterism sentence, name the intent broker as the app's mirroring-off opener in the Sync section+  - Stream: 3+  - Requirements: [7.2](requirements.md#7.2), [7.3](requirements.md#7.3)

Things to double-check

Mac cold-path timing (task 14, Q60).

This is owed by the owner. Follow implementation.md ‘Task 14’ with the Development app only, and record the cold step log lines. A slow cold step triggers the keep-alive fallback.

Phone runbook (runbook.md).

This is owed by the owner, Development only. It covers Siri phrases with both apps installed (7.1–7.3), the lock screen (6.3), a Safari page by voice (3.1, 3.8), open with an editor open (4.5), a cold-created work reaching the Mac (6.5), and reopening a closed Mac window (4.1).

Untested seams.

These are covered only by review: the .intentEditSession modifier's lifecycle, ContentView's three route triggers, the release intent's composition into [WorkEntity] (Req 1.3), and verify-identity's display-name check, which was confirmed by hand.

Rebase before pushing.

origin/main is at d0596e79, past the branch base bbdcd8b6. Rebase, then re-run make test-core and make test-quick.