CLAUDE.md cut from 478 lines / 67 KB to 143 lines / ~14 KB; narratives moved verbatim to docs/agent-notes/.
make test-locales keptReady to push
Docs-only. A claims check against the code found three inaccurate statements in the new CLAUDE.md; all three were corrected. No contributor rule was lost: anything not kept in CLAUDE.md is in agent-notes. make verify-workflow-triggers and make lint pass.
dbbed46f T-2376: Cut CLAUDE.md back to a working guide 80148174 T-2376: Correct three CLAUDE.md claims found in pre-push review | Severity | Area | Finding | Resolution |
|---|---|---|---|
| minor | CLAUDE.md single-test example | Example named a nonexistent test (inherited); -only-testing would run zero tests | Now uses testMermaidDetection() in swift-testing form |
| minor | CLAUDE.md zoom renderers | Claimed MermaidRenderer renders over WebViewPool | Only SVGRenderer is attributed to the pool |
| minor | CLAUDE.md BoundedFileRead | Claimed it is the only way to read any local file; notes stores read directly | Scoped to document/image/SVG reads |
| nit | SwiftSoup mutex | Reason for the mutex dropped | Reason restored inline |
| nit | Old WKWebView security list | SVG 2 MB source limit and 10 s render timeout no longer documented | Left out; these values are in code and were never contributor rules |
8 files: 8 docs. Click to expand.
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0caefefb..00b0c922 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- CLAUDE.md cut back to a working guide (478 lines / 67 KB → 143 lines / 13.5 KB): each subsystem states the rules a change must not break and links to its agent-note; incident narratives moved verbatim into `docs/agent-notes/` (new `external-file-moves.md`, plus sections in `webview-rendering-status.md`, `footnotes.md`, `image-support.md`, `inapp-purchase.md`, `development-tooling.md`); stale descriptions of deleted SwiftUI views and the hand-maintained Source Structure tree removed (T-2376) - The per-locale test sweep no longer runs in CI; it is now a local step before merging. `localisation-tests.yml` is the only workflow that builds or runs this project's tests, and it ran the whole suite four times over on a hosted `macos-latest` runner — billed time, and time the suite could not use. In the one sweep that ran to completion, 6,661 test executions took over 30 seconds each and the slowest took 72, against sub-second times on a developer machine, so every live-WebKit and UI test holding a deadline failed: 283 of 4,725 unit tests in `en (base)`, 96% of them live-WebKit suites, and 167 of 281 UI tests, which never saw the app's interface appear at all. None of those were real defects, which is the worse half of the problem — a sweep whose red means nothing trains you to merge past it. The workflow is now `workflow_dispatch` only, so it can still be run deliberately from the Actions tab, and `make test-locales` is the documented step before a merge. What remains automatic is File Checks, SwiftLint and Stylelint, all on Linux; a green pull request now says nothing about the tests, and CLAUDE.md says so where a reader will meet it. `make verify-workflow-triggers` was taught the two shapes this file is allowed to be in — automatic, with both `paths:` filters listing every input, or disabled, with `workflow_dispatch:` alone and the local requirement recorded in CLAUDE.md — and refuses anything in between, so the sweep cannot drift back to half-triggered or lose the note that it moved to a local step. - Live-WebKit test suites no longer abort the shared test host, which used to turn a whole run into a fictional four-figure failure count (T-2219, T-2096). One process hosts the entire unit-test target, so an abort reports every still-queued test as a failure it never ran — 189 of them in one observed run, 233 in another. The cause was the one T-1541 diagnosed and fixed for a single suite: a synchronous `@MainActor` test body gets no hop-on-entry in this target's build configuration, so under load it runs on the cooperative pool and WebKit's main-thread assertion kills the process. Sixty tests across nine suites could still do that, including the two the tickets name and two suites no ticket had ever mentioned — which is why the abort kept being attributed to a different suite each time, usually whichever long-running live-WebKit test happened to be in flight. All sixty are now `async`, which hops as part of the ABI, and `make verify-test-isolation` fails the build if a synchronous test can reach WebKit again. Nothing is skipped or excluded; the number of tests executed is unchanged. **This fixed one cause, not the cascade:** T-2219 reopened twice after it landed, with the guard passing, because a second mechanism sits on a lifetime path no constructor check can see. See the two T-2219 entries under Fixed below for what actually closed it.
diff --git a/CLAUDE.md b/CLAUDE.mdindex 492f1fe5..f6a9ef36 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,283 +1,91 @@ # CLAUDE.md -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. It states the rules a change must not break; the history behind each rule lives in `docs/agent-notes/`, linked per section. ## Project Overview -Prism is a read-only markdown viewer for iOS 26+ and macOS 26+. It renders markdown files from any Files app provider with special support for mermaid diagrams displayed via rendered preview thumbnails, SVG image rendering, and image zoom/fullscreen views.+Prism is a read-only markdown viewer for iOS 26+ and macOS 26+. It renders markdown from any Files app provider, the clipboard, and remote URLs through a WebKit document surface, with mermaid diagrams, SVG and raster images, footnotes, search, and block-anchored notes. ## Build and Test Commands -Use the Makefile for all development tasks:+Use the Makefile for all development tasks (`make help` lists every target): ```bash-make help # Show all available targets make build # Build for both iOS and macOS make build-ios # Build for iOS Simulator only make build-macos # Build for macOS only make test-quick # Run unit tests on macOS (fast, no simulator) make test # Run full test suite on iOS Simulator make test-ui # Run UI tests only+make test-locales # Per-locale sweep (local step, see Testing Strategy) make lint # Run SwiftLint make lint-fix # Run SwiftLint with auto-fix-make clean # Clean build artifacts ``` To run a single test class or method: ```bash xcodebuild test -project prism.xcodeproj -scheme prism \ -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \- -only-testing:prismTests/MermaidTypeParserTests test--xcodebuild test -project prism.xcodeproj -scheme prism \- -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \- -only-testing:prismTests/MarkdownBlockParserTests/testMermaidCodeBlockDetection test+ -only-testing:'prismTests/MarkdownBlockParserTests/testMermaidDetection()' test ``` ## Architecture ### Document Flow-1. `PrismApp` uses `WindowGroup` with a manual file importer (not `DocumentGroup` due to iOS 26 issues)-2. `MarkdownDocument` (FileDocument) validates and loads markdown content (10MB limit, UTF-8 only)-3. For remote URLs, `URLDocumentLoader` downloads content via ephemeral URLSession with streaming (10MB limit), and `GitHubURLTransformer` converts GitHub blob URLs to raw URLs-4. `DocumentReaderView` selects a layout (`CompactDocumentLayout` or `RegularDocumentLayout`) that parses content into blocks via `MarkdownBlockParser` and renders them through the WebKit document path (`WebDocumentView`/`WebDocumentController` over `BlockHTMLEmitter`; see Markdown Rendering below)-5. `FileChangeObserver` (NSFilePresenter) monitors files and shows `ReloadBanner` on external changes; URL-sourced documents use a manual Refresh button instead. It also implements `presentedItemDidMove(to:)`, which is how an open document follows an external rename — see External File Moves below (T-1881)-6. A file-backed `DocumentSession` holds its own `SecurityScopedResourceLease` for the session's whole lifetime — started while the caller that produced the URL (file importer, resolved recent-file bookmark, or a Save As's resolved export bookmark) still holds its own live scope, so it outlives that caller's transient access and keeps `FileChangeObserver` and reload working after it returns (T-1849)--### External File Moves (T-1881)+1. `PrismApp` uses `WindowGroup` with a manual file importer, not `DocumentGroup` (iOS 26 issues).+2. `MarkdownDocument` loads files (10 MB limit, UTF-8 only). Remote URLs go through `URLDocumentLoader` (ephemeral session, streamed, 10 MB) after `GitHubURLTransformer` turns blob URLs into raw ones.+3. `DocumentSession` owns per-document state. `DocumentReaderView` picks `CompactDocumentLayout` or `RegularDocumentLayout`; both render through the WebKit path below.+4. `FileChangeObserver` (NSFilePresenter) raises `ReloadBanner` on external edits; URL documents use a manual Refresh.+5. A file-backed session holds its own `SecurityScopedResourceLease` for its whole lifetime, started while the caller's scope is still live (T-1849). -`FileChangeObserver.presentedItemDidMove(to:)` retargets the presented URL synchronously, under a `Mutex` and before any actor hop, because `presentedItemURL` is read off-actor by the coordination machinery. It then reports the move to `DocumentSession.followFileMove(to:)`, which moves `source`. That one property is the whole fix for most of the symptom: the title, the Save destination, `reloadDocument`, the persisted scroll key and the page's image context (re-based by `WebDocumentStateSynchronizer` from `source.imageSourceContext`) are all derived from it. The report is made in place when the callback is already on the main thread — `presentedItemOperationQueue` is `OperationQueue.main` — because two `Task { @MainActor }` hops are scheduled, not ordered, and a reversed A→B, B→C pair would leave `source` at B while the file is at C.+**External file moves (T-1881).** `FileChangeObserver.presentedItemDidMove(to:)` retargets synchronously and reports to `DocumentSession.followFileMove(to:)`, which moves `source` — title, Save destination, reload, scroll key and image context all derive from it. A move into a Trash directory is not a rename and is ignored. Notes are keyed by path, so they migrate through `NotesManager.startMigration(forMovedFileFrom:toFileURL:)` (never the Save As migration), driven by `session.pendingFileMove` from `DocumentReaderView`'s `.onChange(of:initial: true)`. The migration origin is `DocumentSession.notesRecordURL`, read live. A failed migration surfaces the "Note Migration Failed" alert. Why each of these rules exists: `docs/agent-notes/external-file-moves.md`. -A destination inside a Trash directory is not a rename: trashing an open document arrives as `presentedItemDidMove(to:)` naming its new home in the Trash, so `DocumentSession.isTrashed(_:)` refuses that notification outright and leaves `source` — and the notes — where they are.+### Markdown Rendering (WebKit document path, T-1542) -Only the notes do not follow `source`: they are filed under a path-derived identifier. So the move is republished as `session.pendingFileMove` and `DocumentReaderView`'s `.onChange(of:initial:)` migrates them — through the move path's **own** migration, `NotesManager.startMigration(forMovedFileFrom:toFileURL:)`, not the Save As one. Reusing the Save As migration was the first three rounds of this fix, and each of its preconditions failed here in a way that ends with the notes gone:+Native is the source of truth: parsing, search counting, notes and persistence run natively; the web view only renders HTML and reports interactions over the bridge. There is no SwiftUI/Textual renderer any more. -- **Why the move has its own migration.** `migrateNotes(fromClipboardSession:previousDestination:toFileURL:)` stays internal and is still the Save As entry (`ClipboardSaveFlow`), but it (1) opens on `guard var notes = documentNotes` — memory only — so a move consumed before the first `loadNotes` (the `initial: true` pass, where `documentNotes` is guaranteed nil) reported success having moved nothing; (2) assumes source and target cannot collide (a clipboard UUID against a file path), where a move's two sides are both file paths; and (3) is called *before* `didSave(to:)` flips `session.source`, where a move flips it first. `startMigration` is the only entry to the move path; `migrateNotesForMovedFile` is `private` and does the disk half in the returned task.-- **The synchronous claim, and the window it cannot reach.** The flip-then-migrate order means `session.source` names an identity whose notes record does not exist yet. A `loadNotes` resolving through the retargeted source — the reader's own `.task(id: session.parseRevision)`, from a reload landing near the move — fell through every guard, read the target's absent record, and `clearNoteState()` wiped the notes mid-migration; the post-save guard then read its own container as replaced and abandoned the rebind: empty panel, orphaned record under the old path (T-2231 one identity over). A note *created* in that window was worse still, and a claim cannot help it — the container it finds is the thing being judged. So `startMigration` does two synchronous things before it returns, in the turn the move is *consumed* in: it claims both the source and the target identities, and it rebinds an already-loaded container onto the target. **Neither reaches back to the `source` flip**, which happens in the presenter's callback, an earlier turn: that stretch has no claim. It is unreachable rather than covered — a move bumps no `parseRevision` and deliberately raises no reload banner, so nothing resolves notes in it. Change either and both halves have to move into `followFileMove`.-- **`retiringSourceRecordIsSafe` guards the source delete on both migrations.** It asks the store — reading the source identifier back after the save — instead of comparing identifier strings, because `DocumentIdentifier.path` is case-preserving and `readme.md` and `README.md` are therefore two identifiers and one file on a case-insensitive volume (the default on macOS and iOS): the save wrote the record, the delete removed the file it had just written. This *replaced* the pre-existing Save As delete guard, so the clipboard and save-chain suites are part of this change's regression surface, not just the move ones.-- **The migration's origin is `notesRecordURL`.** `DocumentSession.notesRecordURL` is where the record actually is; only a successful migration advances it (`notesRecordFollowedFile(to:)`), so a failed one leaves the *next* move naming the path the record is genuinely still under. `followFileMove` reports every move from there, which is what makes two moves coalescing into one `.onChange` pass (A→B, then B→C) migrate from A — reporting `(B, C)` matched nothing, skipped, and returned `true` — and a round trip A→B→A report nothing at all. The view derives the origin from that property **live** when it consumes, rather than trusting `move.from`: `from` is only a snapshot taken at report time, and a move reported between a migration landing and its `notesRecordFollowedFile` carries an identifier that migration has already deleted.-- **`initial: true`, and the result is not discarded.** The session follows a move whether or not a reader view is mounted, so without the initial pass a move landing off screen is never consumed. And `startMigration` returning `false` means the store write failed and the notes reverted to the old identity while `source` is at the new one — reported through `onMoveMigrationFailed` to the same "Note Migration Failed" alert Save As uses.+1. **Parse**: `swift-markdown` → `MarkdownBlock` (`MarkdownBlockParser`).+2. **Emit**: `BlockHTMLEmitter` (`prism/Services/WebRendering/`) is a pure, deterministic, `nonisolated` function of blocks + `FootnoteData` + `RenderSettings`. One `<section>` per block with id `b-{hash}-{sourceIndex}` (`BlockDOMID`); escapes by default; never drops a block (falls back to escaped `<pre>`). `InlineHTMLRenderer` records a `DocumentSourceMap` for selection-anchored notes. HTML is emitted off-main once per `parseRevision` and cached on `DocumentSession`. `HTMLSanitizer` (SwiftSoup) calls are serialized behind a shared `Mutex`, because SwiftSoup keeps unsynchronized static pools (T-1681).+3. **Serve**: `PrismDocSchemeHandler` (`prism-doc://`) is the only I/O path: document HTML, `document.css`, and every image via `/img/?src=`. It serves the CSP (`script-src 'none'`, `connect-src 'none'`) as a header. Never use `loadHTMLString`. The handler is a struct frozen into the page configuration, so mutable context (the image source) is read per request from `DocumentImageSourceBox`; `WebDocumentStateSynchronizer` updates it and reloads (T-1784/T-1810).+4. **Host + bridge**: `WebDocumentController`/`WebDocumentView` own one `WebPage` per session (non-persistent store, `allowsContentJavaScript = false`, JS injected as user scripts in an isolated `WKContentWorld`). Every bridge message carries a generation tag; `BridgeMessageRouter` drops anything not on the allowlist or not an exact generation match. WebContent crash recovery is armed in the controller's `init` and pinned by the live test `WebContentTerminationWiringTests` — keep it passing. `WebDocumentStateSynchronizer` is the single owner that pushes native state to the page. Palette and `dynamicTypeSize` are view-fed: the palette as one `WebPaletteFeed`, and Dynamic Type folded into the typography push rather than given its own.+5. **Notes**: `NoteStateFeeder` + `NoteHTMLBuilder` produce note chrome; `prism-notes.js` injects it. Every interactive control is a native `<button>`/`<a href>`, never a `role="button"` div (T-1725). Accessible names come from native code, because the JS cannot reach the string catalog.+6. **Search**: counting and order stay in `SearchService`/`SearchCoordinator`; `prism-search.js` paints CSS Custom Highlights. The web view's find navigator stays disabled so Cmd+F reaches Prism's search.+7. **In-page libraries**: mermaid.js and highlight.js run in the page world and never post bridge messages. Bundled JS/CSS lives in `prism/Resources/WebRenderer/`. -The security-scoped lease is deliberately untouched (the extension was issued for the file and survives its rename; a URL synthesised from a move notification carries no scope of its own) and so is the recent-files entry (T-1842/T-2172/T-2173).+Pipeline detail, the crash-recovery state machine, focus-restore rules and other gotchas: `docs/agent-notes/webview-rendering-status.md`. Spec: `specs/webview-rendering/`. -### Markdown Rendering (WebKit document path, T-1542)+### Footnotes+`FootnotePreprocessor` strips `[^id]: …` definitions before parsing into a `FootnoteData` sidecar. Badges are substituted inside `InlineHTMLRenderer.render` from markers placed by `FootnoteReferenceScanner`, and only where an `<a>` is legal (text position, not inside a link); everywhere else the literal `[^id]` is restored and the occurrence still claimed (T-1945/T-1992). Taps route `prism://footnote/{id}` → `DocumentLayoutCoordinator` → `FootnotePopoverView`, a sheet that both layouts must apply via `footnotePresentation(coordinator:session:)`. The popover page has no bridge, so theme, contrast and typography are baked into its HTML and it re-presents when its `RenderKey` changes (T-1979). Detail: `docs/agent-notes/footnotes.md`. -The document is rendered by WebKit-for-SwiftUI (`WebView`/`WebPage`). The SwiftUI/Textual in-flow renderer was retired in the T-1542 cutover — there is no legacy path or render-policy switch any more (see the CHANGELOG `[Unreleased]` "Changed" entry). Native stays the source of truth: parsing, search counting, notes logic, and persistence all run natively; the web view only renders HTML and reports interactions back over the bridge.--1. **Parse**: `swift-markdown` → AST → `MarkdownBlock` enum variants (`MarkdownBlockParser`), unchanged from before. T-1558 made the model lossless for nested blockquotes, ordered-list `start`, and rich blocks inside list items (see `specs/web-markdown-fidelity/`).-2. **Emit**: `BlockHTMLEmitter` (`prism/Services/WebRendering/`) is a pure, deterministic function of `[MarkdownBlock]` + `FootnoteData` + `RenderSettings`. It emits one `<section>` per block carrying the content-hash block identity and an occurrence-qualified DOM id (`b-{hash}-{sourceIndex}`, allocated via the shared `BlockDOMID`), escapes by default, and is total (a block that fails to emit falls back to escaped-source `<pre>`, never dropped). `InlineHTMLRenderer` wraps mappable text runs in `<span data-prism-run>` and records a `DocumentSourceMap` (UTF-16 offsets, shipped as an inert `<div hidden>` data island) for selection-anchored notes. `emit` (and the model/service value types it reads) is `nonisolated`, so it runs off the MainActor: `WebDocumentControllerFactory.precomputeDocumentHTML` emits once per `parseRevision` on a `Task.detached` and caches the HTML on `DocumentSession`; the scheme handler serves that cache (synchronous on-main emit only on a miss). Its per-block/inline `HTMLSanitizer` (SwiftSoup) passes are serialized behind a shared `Mutex` because SwiftSoup keeps unsynchronized static pools (T-1681, `specs/offmain-html-emit/`).-3. **Serve**: `PrismDocSchemeHandler` (`prism-doc://` `URLSchemeHandler`) is the single audited I/O path — it serves the document HTML, `document.css` (the only asset fetched through the scheme), and mediates every image subresource through `/img/?src=` (rewritten absolute/relative URLs routed via `ImagePathResolver`/`ImageLoader`/`SVGSourceLoader`). It serves the verbatim CSP (`script-src 'none'`, `connect-src 'none'`, …) as a response header. The document is loaded via the scheme, never `loadHTMLString`. The handler is a STRUCT copied into the `WebPage.Configuration`, so anything stored in it is frozen for the life of the page — which is why the image context (scope root, source type, base URL) is not stored but held by reference, in the shared `DocumentImageSourceBox` (`DocumentImageSource.swift`) it reads per request. `didSave(to:)` re-bases a clipboard document onto a file IN PLACE — same session id, same parse output, no `parseRevision` bump — so nothing rebuilds the page, and a captured context left the saved document resolving every relative image as an unsaved paste (no scope root, so all rejected) until it was closed and reopened (T-1784). `WebDocumentStateSynchronizer` owns the update: the context is a domain of its observation pass, and a change writes the box and issues a same-revision `reloadDocument` — the images already on screen failed against the old context and WebKit will not re-request them, and that reload restores the stored reading position — except when the page's `parseRevision` is behind the session's, where it is deferred because the owed revision load fetches every image against the new context anyway, and a second reload would only discard the first's scroll restore (T-1810). Its first pass only seeds (the initial load has not happened yet).-4. **Host + bridge**: `WebDocumentController`/`WebDocumentView` (`prism/ViewModels/`, `prism/Views/`) own one `WebPage` per session (non-persistent store, `allowsContentJavaScript = false`, all JS injected as user scripts via `WebDocumentControllerFactory.userScripts()`). The native↔JS bridge runs in a dedicated isolated `WKContentWorld`; every message in both directions carries a generation tag (sessionID, parseRevision, processGeneration). `BridgeMessageRouter` validates inbound messages against an enumerated allowlist + exact-generation match and drops forged/stale/malformed ones; `WebDocumentMessageRouter` routes accepted messages onto the existing native session/coordinator state. Outbound commands queue until `ready`; scroll restore waits for `layoutSettled`; on WebContent termination the controller bumps the process generation, reloads, and replays one coalesced state snapshot. That termination is observed by `startNavigationObservation()`, armed from the controller's `init` — it was missing entirely until T-1943, so the whole recovery path was dead code in production. `WebPage` offers no delegate callback and no Observable property for a crash: it surfaces as `WebPage.NavigationError.webContentProcessTerminated` **thrown** by `page.navigations`, which ENDS the sequence — and which also throws for ordinary navigation failures — so the observer classifies the error (`drainNavigationStream`) and re-subscribes (`applyNavigationOutcome`), or the first failed navigation would silently disarm crash recovery for the rest of the session. A recovery reload that fails as an ORDINARY navigation is the same failure wearing a different error, so `recoveryInFlight` makes a `.navigationFailed` legible: during a recovery it is charged and retried, outside one it is a benign bad link. Recovery gives up after `maxUnproductiveRecoveries` consecutive attempts that never reach the stability milestone that resets the budget — `layoutSettled`, not merely `ready` — rather than reloading in a hot loop; `ready` alone used to reset it, so a crash landing after `ready` but before `layoutSettled` restarted the chain at attempt one every time and could reload forever without ever hitting the cap (T-2107). Giving up is neither silent nor permanent: it clears the observation task handle, raises `recoveryAbandoned` (the banner in `DocumentScrollContent`), and any fresh `load` restores the budget and re-arms observation. Because a direct-invocation test cannot see missing wiring (that is exactly how T-1943 survived the cutover and every review), the production subscription is pinned by a live test over a real `WebPage`: `WebContentTerminationWiringTests.controllerObservesItsOwnPageNavigationStream`. `WebDocumentStateSynchronizer` (T-1719) is the single production owner that pushes native truth (sections, details open-state, table modes, notes, typography, comment visibility) to the controller and routes navigation targets (TOC/fragment via `session.pendingAnchorScroll`, notes via `coordinator.noteNavigationTarget`, search current match) through `controller.scrollTo` with `BlockDOMID.navigationDOMID` id translation — Observation-framework driven, so it works with no view mounted; `DocumentScrollContent` mounts the whole assembly via `WebDocumentStateSynchronizer.makeAssembly`. Two inputs are view-fed, because both are view-world environment values: the palette, pushed via `applyTheme(themeKey:contrast:)` — the colorScheme-resolved theme key plus `colorSchemeContrast`, grouped as a `WebPaletteFeed` so a single `.onChange` pushes them together and they can never be applied out of step (T-1829) — and `dynamicTypeSize`, fed in via `start(dynamicTypeSize:)` / `applyDynamicTypeSize(_:)`, which gets NO push of its own: the synchronizer folds it into the typography domain, because `applyTypography` carries one variables dict that wholly replaces the snapshot's typography, so a second pusher would drop the settings-derived half from the recovery replay (T-1828, font-settings Decision 18).-5. **Notes**: `NoteStateFeeder` (`prism/Services/WebRendering/`) maps `NotesManager` state onto `setNoteIndicators`/`setInlineNotes` payloads; `NoteHTMLBuilder` renders the (escaped) bubble/banner HTML natively; `prism-notes.js` (isolated world) injects it as `data-prism-chrome` and posts interaction messages back. Every interactive piece of that chrome is a NATIVE `<button>` or `<a href>` (T-1725) — never a `div`/`span` with `role="button"` — so the user agent supplies focusability, tab order, and Enter/Space activation, and there is no synthetic key handling to keep in sync. Those elements suppress their UA appearance, so `document.css` must reset it; the indicator dot's `font-size: 1em` is load-bearing rather than cosmetic, since the dot's whole gutter geometry is expressed in em. Accessible names are native-owned because the JS cannot reach the string catalog: the indicator's name rides the `setNoteIndicators` payload (`label`, pluralised via `NoteRenderStrings.noteIndicator`), the bubble's action label is baked in by `NoteHTMLBuilder` as visually-hidden text (an `aria-label` there would *replace* the note's own text in the accessible name), and the add-note "+" reads `<main data-prism-add-note-label>`. Both push handlers rebuild all chrome, so each control carries a `data-prism-focus-key` and `prism-notes.js` captures/restores focus around the rebuild. The restore is gated on `document.hasFocus()` — never pull focus into a document the user is not in — and a restore the gate refuses is DEFERRED as `pendingFocusKey`, not discarded, then consumed by a `window` `focus` listener when the document actually comes back (T-2059); discarding it lost the return address for every note edited through a native sheet. The shared writer, `focusOrDefer`, is called from BOTH `restoreFocusKey` and `suppressAddNote`'s "+"-to-dot handoff — the add-note "+" carries no focus key of its own (`makeAddNoteControl`), so before this the handoff had nothing to defer and lost focus outright on the more common add-a-note sequence (stand on a block's "+", tap it, save from the sheet); `focusOrDefer` falls back to the successor's OWN `data-prism-focus-key` so that path is covered too. `focusControl` verifies `document.activeElement === element` after calling `.focus()` rather than trusting the call, because a suppressed "+" stays in the DOM (`display:none`) and a no-op `.focus()` on it must not read as success. The pending key is invalidated by `bridge.onExplicitNavigation`, matching the sibling deferrals in `prism-search.js` (`revealPending`) and `prism-scroll.js` (`reflowAnchor`) — safe because a note's own bridge messages (indicator/bubble tap, block-context "+") never scroll, so the invalidation cannot cancel the restore it exists to deliver. The consuming `window` `focus` listener also refuses while `bridge.searchIsActive()` (prism-search.js, sourced from `SearchCoordinator.isSearchActive`), mirroring native's `restoreBodyFocusIfIdle` (`RegularDocumentLayout.swift`) — the key stays pending rather than discarded, so it still fires once search is no longer active.-6. **Search**: counts and navigation order stay in `SearchService`/`SearchCoordinator`. `SearchStateFeeder` translates that into a per-block `setSearchState` payload; `prism-search.js` re-finds the query in each block's rendered text and registers ranges on two named **CSS Custom Highlights** (`prism-search`, `prism-search-current`), windowed to the viewport. The web view's built-in find navigator stays disabled so Cmd+F routes to Prism's search.-7. **Security**: `HTMLSanitizer` (over SwiftSoup) reduces raw HTML embedded in markdown to an allowlist subset on load (Req 1.8/8.1); its `plainText` feeds searchable text. Combined with `allowsContentJavaScript = false` and the served CSP, active-content vectors are blocked by construction.-8. **In-page render libraries**: mermaid.js and highlight.js (+ their thin Prism drivers) run in the **page world** (they only render DOM, never post bridge messages). The bundled JS lives in `prism/Resources/WebRenderer/`.--Implementation history and gotchas (the `<script>` data-island CSP trap, the native selection overlay, the live-test harness): `docs/agent-notes/webview-rendering-status.md`. Spec: `specs/webview-rendering/`.--### Footnote System-1. `FootnotePreprocessor` extracts `[^id]: content` definitions from raw markdown before `swift-markdown` parsing, producing cleaned source + `FootnoteData` sidecar-2. `MarkdownBlockParser.parseWithFootnotes()` integrates the preprocessor into the parsing pipeline; `parseFragment()` renders footnote content in popovers without the full pipeline-3. `DocumentSession` stores `FootnoteData` alongside parsed blocks; both are bundled in `ParseResult`-4. Badge substitution happens inside `InlineHTMLRenderer.render`, NOT by splitting the source in the emitter (T-1716/T-1945). `FootnoteReferenceScanner.scan` walks the block's inline SOURCE once and marks every occurrence that is spelled verbatim (no backslash escape anywhere in the token) and resolvable, rewriting only its identifier characters into a reserved Private Use Area window. The marker is length-preserving (runs come out in block coordinates — no rebasing, `rebased` is gone) and parse-shape-preserving (`[`, `^`, `]` untouched, so cmark builds the same tree). The whole marked source is then parsed ONCE-5. `InlineHTMLRenderer.Walker` turns a marker into a badge only where a badge is legal: TEXT position **and** not nested inside an element that cannot contain an anchor. Text position alone is not sufficient — the badge is itself an `<a>`, so a `Link` ancestor disqualifies it (`<a>` inside `<a>` is invalid HTML), tracked by the walker's `linkDepth` counter. Every other landing place — a code span, a link's destination or title, an image `src`/`alt`/title, raw inline HTML, or text inside a link — is restored to the literal `[^id]` the author wrote (titles excepted: the emitter renders no `title` attribute, so there is nothing to restore). Classification is never inferred from parsed text, which is the failure class the redesign removes. Restoring is only half of it: a landing place that declines the badge must ALSO claim the occurrence and step the cursor past it (`claimOccurrences`), or a later live reference with the same identifier binds to the attribute's occurrence — zero-length source-map run for the prose before the real badge, wrong offset in `badgeSourceStarts` (T-1992). The claim is POSITIONAL, never keyed on the identifier, and fails closed: an attribute cmark hands back normalised rather than verbatim does not locate and claims nothing, which leaves the T-1992 symptom standing for two shapes (T-2033). Mechanism, the autolink exclusion, and the residual: `docs/agent-notes/webview-rendering-status.md`. `BlockHTMLEmitter.footnoteBadge` builds the styled pill-badge anchor (`prism://footnote/{id}`, display number from `FootnoteData`) carrying `data-prism-chrome`: inert, unselectable, covered by no source-map run-6. Badge taps produce `prism://footnote/{id}` links → `linkActivated` over the bridge → `WebDocumentMessageRouter` → `DocumentLayoutCoordinator` popover state (`PrismLinkRoute.footnotePrefix`)-7. `FootnotePopoverView` displays rendered footnote content (paragraphs, lists, blockquotes only) over a shared, non-persistent `FootnotePopoverWebPage` (emitter-rendered fragment). Since the WebKit cutover it is presented as a sheet on every platform via the shared `FootnotePresenter` modifier (`View.footnotePresentation(coordinator:session:)`), which **both** `CompactDocumentLayout` and `RegularDocumentLayout` must apply — the regular layout lacking it is T-1893. The web-rendered badge has no SwiftUI anchor view, so the anchored popover the original footnotes spec called for (Req 3.1/3.6/3.7) no longer applies; `FootnotePopoverView` self-sizes per platform. The popover page is bridge-less, so everything the document surface receives over the bridge must instead be BAKED into the emitted HTML via `RenderSettings`. Baked today: the palette — theme key **and** Increase Contrast state, carried as one `WebPaletteFeed` so they can never be applied out of step (T-1542/T-1829), emitted as `data-prism-theme`/`data-prism-contrast` by `BlockHTMLEmitter.paletteAttributes`; and the typography custom properties (T-1978, emitted as a validated `<html style>` by `BlockHTMLEmitter.rootStyleAttribute`). Not baked: the mermaid theme config and the note/search/section state, none of which a footnote fragment can contain. `FootnotePopoverView.renderSettings(settings:colorScheme:contrast:dynamicTypeSize:)` is the single pure builder of that render input — it reuses `WebDocumentControllerFactory.typographyVariables` rather than resolving fonts again (font-settings Decision 18), and its equatable result is one half of the re-present key. Because a bake can only be applied by re-emitting, an OPEN popover stays current only by re-presenting: `FootnotePopoverWebPage.RenderKey` (footnote id + the resolved `FootnoteDefinition` + that `RenderSettings`) is the equatable trigger, and `FootnotePopoverView` drives it with one `.onChange(of: renderKey, initial: true)` — evaluated in `body`, which is what registers the `AppSettings` reads with Observation (reading them only inside `onAppear` registered nothing). `present` no-ops on an unchanged key (an identical re-emit would blank the live page mid-read) and `renderGeneration` guards overlapping loads so a superseded one cannot win; it also varies the document URL's `rev`. Keying on `footnoteId` alone was T-1979: the identifier is the one input that does not move when the theme, contrast, typography, comment visibility, or a same-id definition does-8. `FootnoteStripping` removes `[^id]` references from heading text used in ToC entries, anchor IDs, and window titles-9. Search integration: `searchableText(with:)` appends footnote content to host blocks; badge highlighting indicates matches--### Mermaid Diagram System-1. `MarkdownBlockParser` detects mermaid code blocks → creates `.mermaid(source:byteOffset:)` blocks-2. `MermaidPreviewCard` renders diagrams in background via `BackgroundDiagramRenderer`, displays inline thumbnails with Liquid Glass overlay buttons (show code, copy code)-3. `MermaidPlaceholderCard` serves as fallback when background rendering fails-4. Tapping thumbnail opens `MermaidDiagramSheet` (iOS) or diagram window (macOS) with pinch-zoom/pan gestures-5. `MermaidRenderer` uses hidden WKWebView with bundled `mermaid.min.js` (v11.x) for on-demand sheet rendering-6. `BackgroundDiagramRenderer` delegates pool management to `WebViewPool` for concurrent background snapshot rendering (separate from `MermaidRenderer`)-7. `RenderingUtilities` provides the shared timeout race, JSON-encoded innerHTML injection, and dimension-JSON parsing used by all three renderers (`MermaidRenderer` uses only the timeout helper; the others use all three)-8. `DiagramCache` (actor) caches rendered SVG strings by SHA-256 hash; `SnapshotCache` caches rasterized thumbnail images--### Image Rendering System-1. `MarkdownBlockParser` detects image-only paragraphs → creates `.image(source:alt:title:link:width:height:)` blocks-2. `HTMLImageParser` extracts `<img>`, `<figure>`, and `<picture>` elements from HTML blocks → routes through same image pipeline-3. `ImageBlockView` resolves paths at render time via `ImagePathResolver` using environment-injected base URL-4. `ImagePathResolver` handles relative paths (file, URL, bundled), absolute URLs, data URIs, SVG files, and scheme validation-5. SVG sources detected via `ImagePathResolver.isSVG()` are loaded as strings by `SVGSourceLoader` and rasterized by `SVGRenderer` (delegates to `WebViewPool`; strict CSP: `script-src 'none'`)-6. Raster images loaded by `ImageLoader` (actor) from file, network, or data URI. Two entry points, both funnelling into the guard below: `load(_:)` for the native SwiftUI surfaces, `loadPageBytes(_:fallbackMIMEType:)` for the rendered page (the only raster entry `PrismDocSchemeHandler` uses). The handler builds a loader PER REQUEST and every page image is now a request, so `ImageLoader` and `SVGSourceLoader` each hold ONE process-wide `URLSession` rather than building one per instance: a delegate-backed session is retained until `invalidateAndCancel()`, which nothing calls, so a session per loader is a leak scaled by the document's image count. The session is shared, not the loader — one shared actor would serialise every caller behind the synchronous `readLocalFile`. An injected configuration still gets its own session so a test's `URLProtocol` stub cannot sit in front of production traffic-7. **Memory admission (T-2132/T-2149/T-2151/T-1867)**: `ImageMemoryGuard` (`prism/Services/`) is the single place that decides whether image bytes may be materialised and at what decoded cost, and the only place in production that may turn ENCODED IMAGE BYTES into pixels — create a `CGImageSource`, call `PlatformImage(data:)`, decode a `CGImage`, or encode one back to bytes. That claim is narrower than "the only bitmap allocation", deliberately: `WebViewPool.captureSnapshot` has WebKit rasterise a rendered page (mermaid/SVG thumbnails) for up to ~144 MB (2000 pt square at 3x) against no byte budget — it has no encoded bytes and no header to size, so it is bounded by the pool's slot count and `SVGRenderer`'s 2000-point frame clamp instead, and it carries a `prism-memory-exempt` marker so a SECOND such site has to be argued for. It decides from the **header** (`CGImageSourceCopyPropertiesAtIndex`), never from a decode, and the per-pixel size comes from the header too (`kCGImagePropertyDepth` + `kCGImagePropertyColorModel`), NOT a hardcoded 4: a 16-bit PNG decodes at 8 bytes/px and a 32-bit float TIFF at 16, so a fixed 4 under-counted them 2x and 4x and "retained ≤ 64 MB" was not a bound the code enforced (`ImageCache.estimatedMemoryCost` was already depth-aware on the other side of the decode). The component counts are an UPPER BOUND on what CoreGraphics allocates, not an identity with it: opaque RGB is counted as 4 because ImageIO's default decode is 32 bits/px with a skip byte (CoreGraphics does have a packed 24-bit format, so this is the bound, not the only possibility), grey costs 1, and palette PNG and 16-bit opaque RGB are knowingly over-counted. Over-counting costs a boundary image a downsample it did not need; only under-counting could admit an image the budget cannot pay for, and none does. An unreadable depth or colour model is `refuseUnsizable`, same as unreadable dimensions — empirically free, since every format ImageIO can size reports both. Four verdicts: `decodeWhole` (decoded whole, or on the page path served VERBATIM, since re-encoding validated bytes buys nothing and costs three allocations), `downsampleFirstFrame` (frame 0 declares ≤ 256 MB — bounded decode to `retainedDimensionCap(bytesPerPixel:)`, which is 4096 px at 4 B/px but 2896 at 8 and 2048 at 16, because a thumbnail KEEPS the source's bit depth), `refuseOversized` (past 256 MB) and `refuseUnsizable` (no readable dimensions, depth, or colour model). The verdict is taken **per consumer**, which is a correctness rule not a refinement: `.native` uses the eager all-frame model `NSImage(data:)` actually pays (every frame's declared size sums into the retained budget, scan bounded at `maxScannedFrames`); `.page` budgets frame 0 alone, because WebKit decodes progressively. Applying the native model to the page is what stopped animated GIFs past 64 frames from animating — a 100x100 100-frame GIF is ~4 MB decoded and was refused, then served as a re-encoded still. The 256 MB ceiling is load-bearing rather than belt-and-braces: PNG/GIF/TIFF have no subsampled decode, so `CGImageSourceCreateThumbnailAtIndex` may inflate the whole source bitmap before scaling — bounding the transient peak is only possible by bounding what may be *declared*. Sending every over-budget raster to the thumbnail path was the first T-2132 fix, and why it was reopened. `BoundedFileRead` is the byte-level twin: it preflights the file size AND bounds the read chunk by chunk, so a file that grows in between is still cut off. Two details are load-bearing for its documented `limit + chunkSize` residency bound and both are invisible from outside (the reported `byteCount` is identical either way, so the pin is structural in `ImageMaterializationChokepointTests`): the running total is tested BEFORE the chunk is appended, not after — appending first commits the memory the cap is refusing — and the reservation comes from the preflight, going straight to `limit` in one step when the preflight is missing or stale, because `Data.append`'s geometric growth otherwise holds ~2x the cap live across the last reallocations — every local read of a document, image, or SVG goes through it, including `SessionFileManager.readContent`, which restores a persisted document body. `ImageMaterializationChokepointTests` scans production source and fails when a banned call appears outside those two files without a per-line `// prism-memory-exempt: <why>` marker; its line-scanning machinery is shared with `URLChokepointAdoptionTests` via `ProductionSourceScan` (the duplication cost real coverage: the URL scan had already learned that `.init(string:)` is `URL(string:)`, and the copied image scan was blind to `.init(data:` all over again). A companion test asserts the chokepoint files still contain the calls, so the rule cannot be satisfied by gutting the guard. Honest limits: retained bitmap ≤ 64 MB/image, transient peak ≤ that image's declared size (≤ 256 MB); what WebKit decodes for a verbatim-served image is not accounted at all-8. Concurrency: `SharedConcurrency` owns the global network semaphore (6 concurrent fetches) and a 4-slot local-read semaphore; both permits are held until materialisation FINISHES, so a compressed body can only exist while its owner holds one (that ordering is the T-2151 fix — releasing early let bodies pile up behind the decode gate). Decode concurrency is `ImageMemoryGuard.budget`, an `ImageMemoryBudget` actor weighted in BYTES, not slots: a four-slot count bounded nothing when one image costs 250 MB and the next 8 MB. One reservation covers decode and re-encode together. Render concurrency is managed per-pool by `WebViewPool` instances-9. Inline `data:` rasters never reach the scheme handler (the CSP permits `img-src data:`), so admission happens at emit time in `BlockHTMLEmitter.rewriteImageSrc`, judged with the `.page` consumer: an admissible payload passes through unchanged, anything else is rewritten to `PrismDocSchemeHandler.blockedImageURLString` (`prism-doc://img/blocked`), which routes to `.rejected(.imagePolicy)` so the page renders its existing catalog-localised image-error placeholder. Refusing rather than downsampling leaves a deliberate asymmetry — the byte-identical image written as a FILE reference is downsampled and shown — and the justification is memory, not convenience: downsampling inline means decoding and re-encoding during emit (a pure, cheap, off-main function of the blocks, run per parse revision) and then re-inlining the base64 result INTO the document HTML, where it is retained for the whole session; a file reference has somewhere else to put the downsampled bytes. The refusal address carries no `?src=` payload, which `prism-media.js`'s `isLocalImage` must treat as "not local" — reading the missing parameter back as `""` offered an iOS "Grant Folder Access" picker for a picture that lives in the markdown and has no folder to grant-10. `ImageCache` (`NSCache`-based) caches raster images; `SnapshotCache` (`NSCache`-based) caches SVG/mermaid rasterized snapshots-11. Tap-to-zoom: `ImageDetailSheet` (iOS) / `ImageDetailWindow` (macOS) with `ZoomableImageView` providing pinch-zoom and pan gestures-12. `DirectoryAccessManager` handles iOS sandbox directory bookmarks for sibling image access-13. `ImageErrorPlaceholder` displays styled placeholders with alt text, source path, and error reason-14. Linked images show a two-button overlay ("View Image" / "Follow Link") matching the MermaidPreviewCard pattern: iOS uses tap-to-reveal with 3s auto-dismiss; macOS uses hover--### In-App Purchase System-1. `StoreManager` (`@Observable @MainActor`) owns StoreKit 2 product fetching, entitlement verification, and the export counter — everything scoped to the ACCOUNT. It owns no paywall presentation state: that is per-scene and lives on `PaywallPresenter` (T-1779). `productLoadError` means "the catalog did not return the unlock product", empty or merely partial — StoreKit omits identifiers it cannot resolve rather than failing, and testing `fetched.isEmpty` left a partial catalog with `unlockProduct` nil and the flag false, a combination neither the paywall nor the Settings row has a branch for, so both spun forever (T-1841). A missing individual TIP is tolerated: the unlock product gates the paywall, the tips only fill the tip jar, so the two are selected independently and neither short-circuits the other — an early return on a missing unlock silently emptied an already-unlocked user's tip jar. The rule lives on `StoreManager.Catalog.loadFailed`, not at the assignment in `fetchProducts()`, because that method assigns to `Product`-typed properties and StoreKit will not let a test construct a `Product` — with the rule at the assignment, reverting it to `fetched.isEmpty` left the whole suite green. The selection itself is the pure `selectCatalog(from:)` over the `StoreProduct` seam (Decision 14)-2. `EntitlementState` is tri-state (`.loading` / `.locked` / `.unlocked`); the paywall and Settings UI branch on it. All writes flow through one commit point ordered by a monotonic observation clock — recency of information wins, never completion order — because a verification scan suspends mid-read and MainActor isolation does not cover that reentrancy window (T-1868). The StoreKit scan sits behind the injectable `EntitlementSource` seam (and `AppStore.sync()` behind `AppStoreSyncing`) so the ordering rules are unit-testable. That clock records who last STAMPED, which is not who last PUBLISHED, so `verifyEntitlements()` answers its own caller through a second watermark, `lastCommittedObservation` — `lastCommittedObservation >= observation ? entitlementState : result`, i.e. the shared property only when something at or after this call's own observation actually committed, and this scan's own finding otherwise, because a newer scan that has merely stamped leaves that property STALER than the scan being answered, which is how `restorePurchases()` came to tell a genuine owner "No purchases to restore" (T-2237, Decision 15)-3. `ExportCounter` tracks the export count with iCloud KVS sync and a UserDefaults mirror; reconciles on init and on external KVS change notifications-4. `KeyValueStoreProtocol` abstracts `NSUbiquitousKeyValueStore` so unit tests can inject a stub-5. `PaywallPresenter` (`prism/Views/PaywallPresenter.swift`, `@Observable @MainActor`) is the PER-SCENE owner of `isPresented` and `pendingExportAction`. `MainContentView` holds one as `@State` per window and the macOS `Settings` scene holds its own; each attaches the shared `paywallPresentation(presenter:storeManager:settings:systemObserver:)` host, which owns the sheet and calls `handleDismiss(entitlementState:)`. Holding those fields on the app-wide `StoreManager` meant every window's sheet bound to one flag — the paywall presented and dismissed in all windows, a second blocked export overwrote the first window's retry, and a Settings-initiated unlock presented over a document window (T-1779). What must NOT move per-scene is the purchase signal: the split first narrowed a `didCompletePurchase` flag along with everything else, which regressed the cross-scene purchase (block in window A, unlock from the Settings window, dismiss A → A's export silently dropped) because entitlement is account-scoped while the flag was set on whichever presenter ran the purchase. That flag is gone; see 8-6. Export gating: callers use `PaywallPresenter.runGatedExport(storeManager:retry:perform:)`, which returns `.loading` (no-op), presents THAT scene's paywall on `.blocked`, or invokes the perform closure on `.allowed` / `.allowedWithNudge`. The gate decision itself stays on `StoreManager.checkExport()`; only the presentation side effect is per-scene-7. `PaywallSheet` runs the purchase flow with explicit ready / processing / pending (Ask to Buy) / error states and surfaces restore success / "no purchases" / failure to the user-8. The presenter's `pendingExportAction` is re-run by its own `handleDismiss` when the APP-WIDE entitlement moved to `.unlocked` while that scene's paywall was up: the presenter captures the entitlement alongside the retry on the `.blocked` gate and compares at dismissal. Watching the shared entitlement rather than a per-scene purchase flag is what lets a purchase or restore completed in ANY scene finish the blocked scene's export, while still separating it from a swipe-away or an Ask to Buy awaiting approval, where the entitlement never moves. The captured baseline is always `.locked` today (only a `.locked` store yields a `.blocked` gate), so it coincides with testing `.unlocked` at dismissal; it is kept because it states that invariant rather than silently depending on it-9. Free-tier mechanics: 20 free exports total. Toast nudge fires on the 10th completion (event: `count >= nudgeThreshold - 1` pre-increment); persistent indicator shows once the count is at or above 10 (state: `count >= nudgeThreshold` post-increment)-10. Gated actions: copy notes, share notes, file export with inline notes. Reading features and code/mermaid copy remain free-11. `Products.storekit` (in `prism/Resources/`) supplies the four products (1 non-consumable unlock, 3 consumable tips) for local StoreKit testing; the scheme references it via `StoreKitConfigurationFileReference`--### Security for WKWebView Rendering-- All WKWebViews use `websiteDataStore: .nonPersistent()`-- **Mermaid CSP**: allows script execution for mermaid.js; blocks external resources-- **SVG CSP**: `script-src 'none'`; blocks all script execution; `img-src data:`; `style-src 'unsafe-inline'`-- Content injected via JSON encoding (prevents XSS)-- Navigation blocked except initial load-- 10-second render timeout-- SVG source size limit: 2 MB--### macOS WKWebView Entitlement Requirement-WKWebView on macOS requires the `com.apple.security.network.client` entitlement even when loading only local/bundled content. This is because WKWebView spawns separate processes (WebContent, GPU) that communicate via network IPC. Without this entitlement, the WebContent process fails to launch silently, causing features like mermaid rendering to appear broken with no visible error to the user. The entitlement is configured in `prism/prism.entitlements`.+### Mermaid, Images, and Zoom+- Mermaid blocks render in the page (mermaid.js, `securityLevel: 'strict'`). Tapping a diagram or image goes through `DocumentLayoutCoordinator` to `MediaZoomPresenter`: iOS sheets (`MermaidDiagramSheet`, `WebImageDetailSheet`), macOS windows (`MermaidDiagramWindow`, `ImageDetailWindow`). Zoom views render diagrams with `MermaidRenderer` and SVGs with `SVGRenderer` (over `WebViewPool`).+- Image paths resolve through `ImagePathResolver`; bytes load through `ImageLoader` / `SVGSourceLoader`, each holding one process-wide `URLSession`.+- **`ImageMemoryGuard` is the only production code that may decode encoded image bytes** (`CGImageSource`, `PlatformImage(data:)`, …), and it decides from the header. Every local read of a document, image or SVG goes through `BoundedFileRead`. `ImageMaterializationChokepointTests` enforces both; a deliberate exception needs a `// prism-memory-exempt: <why>` marker.+- Inline `data:` images are admitted at emit time (`BlockHTMLEmitter.rewriteImageSrc`); refused ones become `prism-doc://img/blocked`.+- `SharedConcurrency` caps network (6) and local reads (4); permits are held until materialisation finishes (T-2151). -## Key Dependencies+Memory-admission verdicts, per-consumer budgets and their history: `docs/agent-notes/image-support.md`, `docs/agent-notes/webview-pool.md`. -SPM dependencies (the Textual fork and HighlightSwift were dropped in the T-1542 cutover):+### In-App Purchase+`StoreManager` owns account-scoped state (products, `EntitlementState`, export counter); `PaywallPresenter` owns per-scene presentation (T-1779) — don't move either across that line. Exports go through `PaywallPresenter.runGatedExport(storeManager:retry:perform:)`. Entitlement writes are ordered by an observation clock, not completion order (T-1868/T-2237). Free tier: 20 exports, nudge at 10. Gated: copy/share notes and export with inline notes. Local testing uses `prism/Resources/Products.storekit`. Detail: `docs/agent-notes/inapp-purchase.md`. -- **swift-markdown** (0.7.3): Markdown parsing to AST-- **SwiftSoup** (2.13.x): HTML sanitization for raw HTML embedded in markdown (`HTMLSanitizer`)+### WebKit Requirements+- Every WebKit page uses a non-persistent data store.+- macOS needs the `com.apple.security.network.client` entitlement (`prism/prism.entitlements`) even for local content: without it the WebContent process silently fails to launch. -Bundled (offline) web-render assets in `prism/Resources/` — injected as user scripts in the page world, never fetched from the network:+## Key Dependencies -- **highlight.js** (11.9.0): in-page syntax highlighting for code blocks-- **mermaid.js** (classic bundle, 11.x, `securityLevel: 'strict'`): in-page diagram rendering+- **swift-markdown** (0.7.3): markdown parsing+- **SwiftSoup** (2.13.x): HTML sanitization (`HTMLSanitizer`)+- Bundled, never fetched: **highlight.js** (11.9.0) and **mermaid.js** (11.x, classic bundle) -## Source Structure+## Source Layout -```-prism/-├── prismApp.swift # App entry point, WelcomeView-├── App/-│ ├── MarkdownDocument.swift # FileDocument for markdown files-│ └── ExportableDocument.swift-├── Models/-│ ├── MarkdownBlock.swift # Block enum with 11 variants (image has 6 associated values), ColumnAlignment, TableDisplayMode-│ ├── DocumentSession.swift # Per-document state management-│ ├── DocumentSource.swift # Document source enum (file, clipboard, bundled, url)-│ ├── FootnoteData.swift # FootnoteDefinition, FootnoteData, ParseResult, environment key-│ ├── ImageDetailWindowData.swift # macOS image detail window data + identifier-│ ├── SVGRenderError.swift # SVG rendering error types-│ ├── NoteModels.swift # User annotations, NoteAnchor sub-block targeting-│ ├── TOCEntry.swift # Table of contents entries-│ ├── EntitlementState.swift # Tri-state enum (loading/locked/unlocked)-│ ├── ExportGateResult.swift # Export gating result (allowed/allowedWithNudge/blocked/loading)-│ ├── PurchaseResult.swift # Purchase outcome enum (success/pending/cancelled)-│ ├── StoreError.swift # StoreKit verification error type-│ └── ...Error.swift # Error types-├── Services/-│ ├── MarkdownBlockParser.swift # AST → blocks (includes HTML image extraction, footnote pipeline)-│ ├── FootnotePreprocessor.swift # Extract footnote definitions from raw markdown-│ ├── FootnoteStripping.swift # Strip [^id] from heading text for ToC/anchors/titles-│ ├── HTMLImageParser.swift # HTML <img>/<figure>/<picture> extraction-│ ├── MermaidTypeParser.swift # Detects 20+ diagram types-│ ├── MermaidRenderer.swift # WKWebView rendering (on-demand for sheets)-│ ├── BackgroundDiagramRenderer.swift # Delegates to WebViewPool for mermaid thumbnail rendering-│ ├── RenderingUtilities.swift # Shared timeout race, JSON-encoded innerHTML injection, and dimension-JSON parsing for the three renderers-│ ├── SVGRenderer.swift # Delegates to WebViewPool for SVG rasterization-│ ├── SVGSourceLoader.swift # Loads SVG content as strings-│ ├── WebViewPool.swift # Shared WKWebView pool with scoped access and per-pool semaphore-│ ├── SharedConcurrency.swift # Global network (6) + local-read (4) semaphores-│ ├── ImageMemoryGuard.swift # Single admission point for image materialisation: header-derived verdict + byte-weighted budget-│ ├── BoundedFileRead.swift # Reads a file within a cap (preflight + bounded chunks) instead of measuring one afterwards-│ ├── DiagramCache.swift # Actor-based SVG string cache-│ ├── SnapshotCache.swift # NSCache for SVG/mermaid rasterized snapshots-│ ├── ImagePathResolver.swift # Image source resolution (incl. SVG support)-│ ├── ImageLoader.swift # Async image loading with concurrency limiting-│ ├── ImageCache.swift # NSCache-based session image cache-│ ├── ImageDetailWindowManager.swift # macOS image detail window lifecycle-│ ├── DirectoryAccessManager.swift # iOS sandbox directory bookmarks-│ ├── FileChangeObserver.swift # NSFilePresenter-│ ├── SecurityScopedResourceLease.swift # RAII lease over URL's start/stopAccessingSecurityScopedResource, held for a session's lifetime-│ ├── GitHubURLTransformer.swift # GitHub blob → raw URL conversion-│ ├── URLDocumentLoader.swift # Remote URL download and validation-│ ├── NotesManager.swift # User notes persistence-│ ├── StoreManager.swift # In-app purchase state, products, entitlements, export gating-│ ├── ExportCounter.swift # Export count with iCloud KVS sync and UserDefaults mirror-│ ├── KeyValueStoreProtocol.swift # Abstraction over NSUbiquitousKeyValueStore for tests-│ ├── TableRowContextQuote.swift # Context quote generation for table row notes-│ ├── StatePersistence.swift # Session state persistence-│ ├── ClipboardService.swift # Platform-specific clipboard-│ ├── ConvergenceProbe.swift # Debug-only scroll-convergence probe (Tools/convergence-probe.sh)-│ └── FontUtilities.swift # Cached font enumeration and classification-├── Views/-│ ├── DocumentReaderView.swift # Platform-adaptive layout selector-│ ├── CompactDocumentLayout.swift # iPhone layout (platform-specific shell)-│ ├── RegularDocumentLayout.swift # iPad/macOS layout (platform-specific shell)-│ ├── DocumentLayoutCoordinator.swift # Shared state for both layouts + ExportNotesFlow (screen-level Share-with-Notes flow)-│ ├── ScenePresentationAnchor.swift # Scene-local presentation anchor + reader modifier so Share-with-Notes presents in the tapped scene (T-1831)-│ ├── CopyNotesButton.swift # Shared copy-notes button for all four copy surfaces + toolbar helper-│ ├── DocumentScrollContent.swift # Shared scroll content body for both layouts-│ ├── SharedBlockViews.swift # Shared block rendering, scroll helpers, navigation title-│ ├── SharedCollapsibleSections.swift # Shared collapsible section logic-│ ├── MarkdownBlockView.swift-│ ├── FootnotePopoverView.swift # Popover/sheet for footnote content display-│ ├── HighlightedInlineText.swift # Markdown text with search + footnote badge rendering-│ ├── MermaidPreviewCard.swift # Mermaid thumbnail with overlay buttons-│ ├── MermaidPlaceholderCard.swift # Fallback card for failed mermaid renders-│ ├── MermaidDiagramSheet.swift-│ ├── ImageBlockView.swift # Image/SVG rendering with loading states and tap-to-zoom-│ ├── ImageDetailSheet.swift # iOS fullscreen image zoom/pan/share-│ ├── ImageDetailWindow.swift # macOS image detail window-│ ├── ZoomableImageView.swift # Pinch-zoom and pan gesture view-│ ├── ZoomControls.swift # iOS shared zoom logic (ZoomMath/ZoomConfig), toolbar buttons, % overlay-│ ├── DiagramZoomWebView.swift # iOS mermaid native WKWebView scroll-view zoom + DiagramZoomController-│ ├── ImageErrorPlaceholder.swift # Error placeholder for failed images-│ ├── RawSourceView.swift # Raw markdown toggle view-│ ├── TableOfContentsSheet.swift-│ ├── NotesPanel.swift-│ ├── URLInputSheet.swift # URL input dialog for remote files-│ ├── PaywallSheet.swift # In-app purchase paywall UI-│ ├── PaywallPresenter.swift # Per-scene paywall presentation + gated-export runner-│ ├── RemainingExportsLabel.swift # Persistent indicator shown once free quota crosses nudge threshold-│ ├── FontPickerView.swift # Font picker with platform variants-│ ├── TypographyModifier.swift # Document content font application-│ └── ...-├── ViewModels/-│ └── RawSourceViewModel.swift-├── Theme/-│ ├── ThemeColors.swift # Color definitions-│ ├── PrismTheme.swift # Theme coordination-│ ├── TypographyResolver.swift # Font computation from settings-│ └── ... # Platform-specific colors-├── Settings/-│ ├── AppSettings.swift # User preferences-│ └── SettingsView.swift-└── Resources/- ├── mermaid.min.js- ├── mermaid-template.html- ├── svg-template.html # HTML template for SVG rendering (strict CSP)- └── Products.storekit # StoreKit testing configuration (1 unlock + 3 tip products)-```+`prism/` holds `App/`, `Models/`, `Services/` (with `Services/WebRendering/` for the emit/serve pipeline), `ViewModels/`, `Views/`, `Theme/`, `Settings/`, `Utilities/` and `Resources/`. Tests are in `prismTests/` (shared helpers in `prismTests/Support/`) and `prismUITests/`. ## Specs and Documentation -Feature specifications live in `specs/` with subfolders for each feature:-- `prism-v1/`: Core viewer functionality (requirements, design, tasks, decision log)-- `macos-support/`: macOS platform support-- `notes/`: User annotation system-- `themes/`: Theming and appearance modes-- `table-of-contents/`: Document navigation-- `raw-source-toggle/`: Raw markdown view-- `clipboard-render/`: Clipboard/paste functionality-- `custom-markdown-renderer/`: Textual fork integration for search highlighting-- `open-from-url/`: Opening markdown files from remote URLs-- `image-support/`: Block-level image rendering with path resolution and caching-- `enhanced-images/`: SVG rendering, image zoom/fullscreen, HTML image parsing, mermaid preview thumbnails-- `footnotes/`: Footnote reference badges, popover display, search integration-- `wide-tables/`: Horizontal scroll toggle for wide tables-- `readable-tables/`: Readable table display mode with 300pt max column width-- `macos-save-to-file/`: macOS File > Export... menu command via NSSavePanel-- `table-row-notes/`: Row-level note support for markdown tables with indicator column and export/import-- `inapp-purchase/`: One-time non-consumable unlock for unlimited annotation exports plus 3 consumable tip products; 20-export free tier--Each feature folder contains `requirements.md`, `design.md`, `tasks.md`, and `decision_log.md`.+Each feature lives in `specs/<feature>/` (`requirements.md`, `design.md`, `tasks.md`, `decision_log.md`, or `smolspec.md` for small changes); `specs/OVERVIEW.md` indexes them. Several older specs describe the retired SwiftUI renderer. Subsystem notes and gotchas: `docs/agent-notes/`. ## Localisation @@ -286,193 +94,50 @@ catalog is produced at `$DERIVED_FILE_DIR/Localizable.merged.xcstrings` during build by `Tools/validate-localisation.py`. When adding UI text:-- Prefer literals: `Text("Settings")`, `Button("Done") { … }`, `Label("Notes", systemImage: "note.text")`. Xcode auto-extracts these as catalog keys; the `LocalizedStringKey` overload is selected automatically.-- For non-literal text, use `LocalizedStringKey` or `LocalizedStringResource` — not `String`:- ```swift- let title: LocalizedStringKey = "settings.section.appearance"- ```-- Accessibility modifiers always use an explicit `LocalizedStringKey` wrapper for literals:- ```swift- .accessibilityLabel(LocalizedStringKey("settings.licence.button"))- ```- Bare-literal forms like `.accessibilityLabel("settings.licence.button")` are banned.+- Prefer literals: `Text("Settings")`, `Button("Done") { … }`, `Label("Notes", systemImage: "note.text")`. Xcode auto-extracts these as catalog keys.+- For non-literal text, use `LocalizedStringKey` or `LocalizedStringResource` — not `String`.+- Accessibility modifiers always wrap literals: `.accessibilityLabel(LocalizedStringKey("settings.licence.button"))`. - Service/model errors use `String(localized: "key", defaultValue: "…")`.-- Pluralised counts use the catalog's plural variation, not concatenation:- ```swift- Text("paywall.exports.remaining \(count)")- ```+- Pluralised counts use the catalog's plural variation: `Text("paywall.exports.remaining \(count)")`. - Numeric values use `.formatted()`; dates use `Date.FormatStyle`. Banned patterns (PR review will flag):-- `Text(plainStringVariable)`, `Button(plainStringVariable, …)` where the variable is a `String` (vs. `LocalizedStringKey` or `LocalizedStringResource`)-- Bare-literal accessibility modifiers without `LocalizedStringKey` wrapper+- `Text(plainStringVariable)`, `Button(plainStringVariable, …)` where the variable is a `String`+- Bare-literal accessibility modifiers without the `LocalizedStringKey` wrapper - `"\(count) items"` — use the plural catalog key - `error.localizedDescription` concatenated into another sentence — wrap with `String(localized: "template.\(error.localizedDescription)", defaultValue: "...")`-- Raw `"\(count)"` or `"\(date)"` interpolation in user-facing strings — use `.formatted()` / `Date.FormatStyle`+- Raw `"\(count)"` or `"\(date)"` interpolation in user-facing strings -Adding an en-AU divergence:-- Edit `specs/localisation/en-AU-overrides.json`. Each entry needs `value` (or `plural`) and `source` (the dictionary or style guide that justifies the divergence). The schema is in `specs/localisation/design.md`.-- Run `make test-locales` to verify.+en-AU divergences go in `specs/localisation/en-AU-overrides.json` (each entry needs `value` or `plural`, plus `source`; schema in `specs/localisation/design.md`). Run `make test-locales` to verify. ## Testing Strategy ### When to Run Which Tests -- **During development**: Use `make test-quick` — runs unit tests on macOS without the simulator, fast feedback loop-- **Before pushing (pre-push-review)**: Use `make build-ios`, `make build-macos`, `make test`, and `make test-ui` — both builds must pass with zero warnings and zero errors-- **Before merging**: Use `make test-locales` — the per-locale sweep is a LOCAL step, not a CI one-- **For commits**: No tests required — lint only (`make lint`)+- **During development**: `make test-quick` — unit tests on macOS, no simulator+- **Before pushing (pre-push-review)**: `make build-ios`, `make build-macos`, `make test`, `make test-ui` — both builds with zero warnings and zero errors+- **Before merging**: `make test-locales` — the per-locale sweep is a LOCAL step, not a CI one+- **For commits**: lint only (`make lint`) <!-- ci-sweep: manual-only --> **The per-locale sweep does not run in CI.** `localisation-tests.yml` is-`workflow_dispatch` only as of 2026-09-06, so nothing on a push or a pull-request builds or runs this project's tests: what remains in CI is File Checks,-SwiftLint and Stylelint, all on Linux. Run `make test-locales` yourself before-merging, and treat a green PR as saying nothing about the tests.--It was disabled because the sweep runs the whole suite four times over on a-hosted `macos-latest` runner — billed time, and time the suite cannot use. In-the one sweep that ran to completion, 6,661 test executions took over 30-seconds each (72 s at worst) where the same tests are sub-second locally, so-everything holding a deadline failed: 283 of 4,725 unit tests in `en (base)`,-96% of them live-WebKit suites, and 167 of 281 UI tests, which never saw the-app's interface appear at all. None were real defects. Re-enabling it means-restoring both `paths:` filters in full — `make verify-workflow-triggers`-refuses any state between the two modes.--### Why the Make Targets Look Paranoid--Every target that runs tests writes its own `-resultBundlePath` and hands it to `Tools/check-test-results.sh`, which fails the run when the bundle reports zero executed tests. `test-locales` does this per locale configuration. This is not belt-and-braces: the CI sweep reported success while running zero tests for months (T-1983), and a `-only-testing:` filter that matches nothing does the same locally.--Two related traps live in the Makefile:--- `/usr/bin/make` on macOS is **GNU Make 3.81**, which silently ignores `.SHELLFLAGS`. Recipes therefore get no `-e` and no `pipefail`, so `xcodebuild | xcbeautify` reports xcbeautify's exit 0 over a failed build. Any recipe whose failure must be believed is prefixed with `$(STRICT)`.-- CI has no signing certificate, so the workflow runs `make test-locales-adhoc`, which signs ad-hoc against `prism/prism-ci.entitlements` (the app's entitlements minus the iCloud keys, which would demand a provisioning profile).--`make verify-make-guards` asserts both and runs on every push.--The third way a run reports something fictional is the host abort, and it has its-own guard. `make verify-test-isolation` (`Tools/check-webkit-test-isolation.py`,-a prerequisite of `test-quick`, `test` and `test-locales`) fails when a `@Test` in-`prismTests` can reach a WebKit constructor from a **synchronous** body. A sync-`@MainActor` function gets no hop-on-entry in this target's build configuration,-so under load it runs on the cooperative pool, WebKit's main-thread assertion-aborts the shared host, and every still-queued test is reported failed without-having run — 189 fictional failures in one T-2219 run, 233 in another. The rule-is: **touch WebKit only from an `async` test in a `@MainActor` suite**-(T-1541, T-2096, T-2219). Both halves matter — `async` buys a hop to the-ENCLOSING actor, so without `@MainActor` there is no actor to hop to and the-body runs on the cooperative pool exactly as a synchronous one would. The check-is static because the abort is a scheduling race — the guilty suite passes in-isolation every time, and the suite the cascade *names* is usually not the guilty-one. See `docs/agent-notes/development-tooling.md`.--That guard covers one of TWO mechanisms, and the second is not a construction at-all (T-2219, third pass). A captured crash report-(`prism-2026-08-30-213219.ips`) reads, main thread, bottom-up:-`runJobInEstablishedExecutorContext` -> WebKit -> `+[NSException raise:format:]`--> `objc_exception_throw` -> **`_swift_exceptionPersonality`** ->-`swift::fatalError` -> `abort`. A WebKit API raises an ObjC exception on a Swift-async job; the exception unwinds into a Swift frame; Swift's personality routine-refuses and aborts **inside the throw**. Three things follow, and each one cost-this ticket a pass: nothing catches it (`try`/`catch` cannot, and it never-reaches `_objc_terminate`, so `NSSetUncaughtExceptionHandler` is unreachable — a-recorder built on it was armed, reproduced the abort, and logged nothing); the-exception's text dies with the process; and the test the bundle blames is-whichever job was resumed at that instant, twice `URLEncodingCorpusTests`, which-touches no WebKit. The path here that reaches it is a `WKURLSchemeTask` given-anything after WebKit stopped it, so `PrismDocSchemeHandler` produces only-through `SchemeTaskSink`, which stops producing once its task is cancelled —-failures included. That is HARDENING, not a closed door, and the distinction is-written into the type: the cancellation arrives from `continuation.onTermination`-on an unstructured task, i.e. only once the continuation is already inert, so the-guard can never pre-empt a stop — what it buys is that the producer stops feeding-an unbounded buffer the consumer has abandoned. A bounded buffering policy is not-the missing piece (`AsyncStream` has no back-pressure at any policy: it would DROP-a `.response` or a `.data` rather than slow the producer, serving a truncated-document). `PrismDocSchemeTaskSinkContractTests` fails the build if a production-point bypasses the sink; a behavioural test is impossible, because reproducing the-race aborts the process running it.--`make verify-test-isolation` also enforces the CONDITION that abort needs.-swift-testing runs tests concurrently inside one host with no cap-(`-parallel-testing-worker-count 1` bounds host PROCESSES), and the live-WebKit-tests are the slowest in the target, so they pile up: 230 WebKit helper-processes started by one host, **226 alive simultaneously** in the instant it-died, 4 ever reclaimed. Every CLEAN run peaks in the same place, so the pile-up-is the condition rather than the trigger — and it is why the abort is-load-dependent and never reproduces a suite in isolation. `@Suite(.liveWebKit)`-(`prismTests/Support/LiveWebKitBudget.swift`) charges a suite against a-32-permit budget; measured peak 226 -> 59. The guard fails when a suite that can-reach WebKit is uncovered, using the SAME predicate as the synchronous rule-(`_reaches_webkit`) so a suite cannot be visible to one and invisible to the-other, and `verify_budget_exists` refuses the other direction (deleting the-budget, or emptying `provideScope` of its `semaphore.acquire`, while every suite-keeps its annotation).--Know the boundary of both rules: reachability into the PRODUCTION target is-seeded, not followed. `PRODUCTION_WEBKIT_TYPES` in the guard is an explicit list,-and a production type that builds a page but is not named there is invisible to-both checks — every test driving it scans clean and its suite is never asked to-carry `.liveWebKit`. Nothing can discover that omission (discovering it is the-whole-target Swift parser the list exists to avoid), and it has already cost-once: `WebViewPool` and `SVGRenderer` were missing, so `SVGRendererTests` drove a-real pooled `WKWebView` unchecked and uncapped until T-2219's review. **When a-production type starts building WebKit, add it to that list in the same change.**--The fourth way is for the tests never to be scheduled at all.-`localisation-tests.yml` is the only workflow that runs `xcodebuild`, and its-`paths` filters omitted `prismTests/**`, `prismUITests/**`, `prism.xctestplan`,-`prism.xcodeproj/**` and `samples/**`, so a test-only change skipped it and-merged green having tested nothing (T-2198). That sweep is now-`workflow_dispatch` only and the per-locale run is a local step (see "When to-Run Which Tests"), so today NO push or pull request runs any test — which is-the same hole T-2198 closed, held open deliberately and recorded where a reader-will meet it rather than left to be discovered.--`make verify-workflow-triggers` (`Tools/check-workflow-triggers.py`, run by-`checks.yml` on every push) enforces which of the two modes the file is in and-refuses anything between them. While the sweep is DISABLED it asserts CLAUDE.md-still carries the `<!-- ci-sweep: manual-only -->` marker and names-`make test-locales`, so the local requirement cannot be lost the way the paths-list was. The moment either automatic trigger returns it goes back to the full-contract: both filters list every input that can change what the sweep builds-or runs, filter keys it cannot read are refused (`paths-ignore:`, quoted or-not, would otherwise pass as "unfiltered"), a `!` negation is refused-(membership cannot see an exclusion, so `['prismTests/**', '!prismTests/**']`-listed every required path and triggered on none of them), and a required path-that no longer exists in the repository fails. The required list is derived-from what the suite READS AT RUN TIME, not from what Xcode compiles:-`samples/**` is compiled by no target and opened from disk by three suites-(`ParityFixtureSupport.samplesDirectory()`, `SamplesComplianceTests`,-`OffMainEmitTests`), which is how the guard's first pass shipped still missing-it. The guard also checks its own runner — a `paths` filter on `checks.yml`, or-the loss of the step that invokes it, would silence it by the same mechanism.--### Tests Never Touch the User's Session Store (T-2275)-`SessionFileManager` is a `struct` over an **injected** directory, not a-static-only type over one. It has to be: with a single process-wide store, a-test that wants a clean slate can only say "empty *the* store", and-`StatePersistenceIntegrationTests` said exactly that — enumerating the app's real-`Application Support/UnsavedSessions/` and deleting every entry, before and after-most of its tests. Under the test host that is the live app container, so a test-run destroyed the user's recoverable unsaved documents; and because suites run-concurrently, the same blanket delete removed files two sibling suites were-mid-way through using. `@Suite(.serialized)` never helped — it serialises within-a suite, and the collision was across suites. The three persistence suites no-longer carry it.-Two things keep it fixed, and only the second is mechanical. `StatePersistence`-and `DocumentServices` take the store with **no default**, so the production-store is not reachable by omission — the compiler enforces that. And-`SessionStoreIsolationTests` scans `prismTests/` (via `ProductionSourceScan`,-whose `directoryName` now varies — this is the first scan that reads the test-tree rather than `prism/`) and fails on any test naming `SessionFileManager.shared`-without a `// prism-session-store-exempt: <reason>` marker. Use-`SessionFileManager.temporary()` from `prismTests/Support/IsolatedSessionStore.swift`.-The one live exemption asserts where the production store lives and never writes.+`workflow_dispatch` only, so no push or pull request builds or runs this+project's tests; CI runs only File Checks, SwiftLint and Stylelint. Run+`make test-locales` yourself before merging, and treat a green PR as saying+nothing about the tests. Re-enabling the workflow means restoring both `paths:`+filters in full — `make verify-workflow-triggers` refuses any state in between.++### Guards That Must Stay Green++- **Zero-test runs fail.** Every test target writes a result bundle checked by `Tools/check-test-results.sh`. Recipes whose failure matters are prefixed `$(STRICT)` because macOS `/usr/bin/make` (GNU Make 3.81) ignores `.SHELLFLAGS`. `make verify-make-guards` checks both.+- **WebKit only from an `async` test in a `@MainActor` suite**, and any suite that can reach WebKit carries `@Suite(.liveWebKit)` (`prismTests/Support/LiveWebKitBudget.swift`). `make verify-test-isolation` enforces both. When a production type starts building WebKit, add it to `PRODUCTION_WEBKIT_TYPES` in `Tools/check-webkit-test-isolation.py` in the same change.+- **`PrismDocSchemeHandler` produces only through `SchemeTaskSink`**; `PrismDocSchemeTaskSinkContractTests` pins it.+- **Tests never touch the user's session store.** Use `SessionFileManager.temporary()` (`prismTests/Support/IsolatedSessionStore.swift`); `SessionStoreIsolationTests` fails on `SessionFileManager.shared` in tests without a `// prism-session-store-exempt: <reason>` marker.+- `make verify-workflow-triggers` checks the workflow trigger mode and this file's marker above.++Why each guard exists (host aborts, phantom failure cascades, the months of zero-test CI runs): `docs/agent-notes/development-tooling.md`.+ ### Test Coverage -- Unit tests (`prismTests`): parsers, cache, file observer, models-- UI tests (`prismUITests`): mermaid card interaction, sheet states-- Performance tests: <100ms cache hits, <2s parsing for 500KB docs-- Tests use `@testable import prism` for internal access+- Unit tests (`prismTests`) use `@testable import prism`; UI tests live in `prismUITests`+- Performance targets: <100ms cache hits, <2s parsing for 500KB docs
diff --git a/docs/agent-notes/development-tooling.md b/docs/agent-notes/development-tooling.mdindex 2270830c..9806a7e4 100644--- a/docs/agent-notes/development-tooling.md+++ b/docs/agent-notes/development-tooling.md@@ -310,3 +310,151 @@ rather than implying the suite passed. - The in-app side is `prism/Services/ConvergenceProbe.swift` (Debug-only, `PRISM_CONVERGENCE_PROBE=<path>` env var). The app is sandboxed even in Debug (Xcode injects the entitlement at signing) — the script stages fixtures into the app container at `~/Library/Containers/me.nore.ig.prism/Data/tmp/`; don't pass arbitrary repo paths directly. - `proxy.scrollTo` jumps alone do NOT reproduce the historical selection layout-loop; continuous scrolling (the script's clip-view stepping wheel pass) is required. - Don't run other builds/tests in parallel with a probe run — they skew the main-loop gap measurements and can flip a CONVERGES into DEGRADED.++## Architecture detail moved from CLAUDE.md (T-2376, 2026-10-02)++Moved verbatim when CLAUDE.md was cut back to invariants. Read this for the *why* behind each rule.++### Why the per-locale sweep is manual-only++It was disabled because the sweep runs the whole suite four times over on a+hosted `macos-latest` runner — billed time, and time the suite cannot use. In+the one sweep that ran to completion, 6,661 test executions took over 30+seconds each (72 s at worst) where the same tests are sub-second locally, so+everything holding a deadline failed: 283 of 4,725 unit tests in `en (base)`,+96% of them live-WebKit suites, and 167 of 281 UI tests, which never saw the+app's interface appear at all. None were real defects. Re-enabling it means+restoring both `paths:` filters in full — `make verify-workflow-triggers`+refuses any state between the two modes.++### Why the Make Targets Look Paranoid++Every target that runs tests writes its own `-resultBundlePath` and hands it to `Tools/check-test-results.sh`, which fails the run when the bundle reports zero executed tests. `test-locales` does this per locale configuration. This is not belt-and-braces: the CI sweep reported success while running zero tests for months (T-1983), and a `-only-testing:` filter that matches nothing does the same locally.++Two related traps live in the Makefile:++- `/usr/bin/make` on macOS is **GNU Make 3.81**, which silently ignores `.SHELLFLAGS`. Recipes therefore get no `-e` and no `pipefail`, so `xcodebuild | xcbeautify` reports xcbeautify's exit 0 over a failed build. Any recipe whose failure must be believed is prefixed with `$(STRICT)`.+- CI has no signing certificate, so the workflow runs `make test-locales-adhoc`, which signs ad-hoc against `prism/prism-ci.entitlements` (the app's entitlements minus the iCloud keys, which would demand a provisioning profile).++`make verify-make-guards` asserts both and runs on every push.++The third way a run reports something fictional is the host abort, and it has its+own guard. `make verify-test-isolation` (`Tools/check-webkit-test-isolation.py`,+a prerequisite of `test-quick`, `test` and `test-locales`) fails when a `@Test` in+`prismTests` can reach a WebKit constructor from a **synchronous** body. A sync+`@MainActor` function gets no hop-on-entry in this target's build configuration,+so under load it runs on the cooperative pool, WebKit's main-thread assertion+aborts the shared host, and every still-queued test is reported failed without+having run — 189 fictional failures in one T-2219 run, 233 in another. The rule+is: **touch WebKit only from an `async` test in a `@MainActor` suite**+(T-1541, T-2096, T-2219). Both halves matter — `async` buys a hop to the+ENCLOSING actor, so without `@MainActor` there is no actor to hop to and the+body runs on the cooperative pool exactly as a synchronous one would. The check+is static because the abort is a scheduling race — the guilty suite passes in+isolation every time, and the suite the cascade *names* is usually not the guilty+one. See `docs/agent-notes/development-tooling.md`.++That guard covers one of TWO mechanisms, and the second is not a construction at+all (T-2219, third pass). A captured crash report+(`prism-2026-08-30-213219.ips`) reads, main thread, bottom-up:+`runJobInEstablishedExecutorContext` -> WebKit -> `+[NSException raise:format:]`+-> `objc_exception_throw` -> **`_swift_exceptionPersonality`** ->+`swift::fatalError` -> `abort`. A WebKit API raises an ObjC exception on a Swift+async job; the exception unwinds into a Swift frame; Swift's personality routine+refuses and aborts **inside the throw**. Three things follow, and each one cost+this ticket a pass: nothing catches it (`try`/`catch` cannot, and it never+reaches `_objc_terminate`, so `NSSetUncaughtExceptionHandler` is unreachable — a+recorder built on it was armed, reproduced the abort, and logged nothing); the+exception's text dies with the process; and the test the bundle blames is+whichever job was resumed at that instant, twice `URLEncodingCorpusTests`, which+touches no WebKit. The path here that reaches it is a `WKURLSchemeTask` given+anything after WebKit stopped it, so `PrismDocSchemeHandler` produces only+through `SchemeTaskSink`, which stops producing once its task is cancelled —+failures included. That is HARDENING, not a closed door, and the distinction is+written into the type: the cancellation arrives from `continuation.onTermination`+on an unstructured task, i.e. only once the continuation is already inert, so the+guard can never pre-empt a stop — what it buys is that the producer stops feeding+an unbounded buffer the consumer has abandoned. A bounded buffering policy is not+the missing piece (`AsyncStream` has no back-pressure at any policy: it would DROP+a `.response` or a `.data` rather than slow the producer, serving a truncated+document). `PrismDocSchemeTaskSinkContractTests` fails the build if a production+point bypasses the sink; a behavioural test is impossible, because reproducing the+race aborts the process running it.++`make verify-test-isolation` also enforces the CONDITION that abort needs.+swift-testing runs tests concurrently inside one host with no cap+(`-parallel-testing-worker-count 1` bounds host PROCESSES), and the live-WebKit+tests are the slowest in the target, so they pile up: 230 WebKit helper+processes started by one host, **226 alive simultaneously** in the instant it+died, 4 ever reclaimed. Every CLEAN run peaks in the same place, so the pile-up+is the condition rather than the trigger — and it is why the abort is+load-dependent and never reproduces a suite in isolation. `@Suite(.liveWebKit)`+(`prismTests/Support/LiveWebKitBudget.swift`) charges a suite against a+32-permit budget; measured peak 226 -> 59. The guard fails when a suite that can+reach WebKit is uncovered, using the SAME predicate as the synchronous rule+(`_reaches_webkit`) so a suite cannot be visible to one and invisible to the+other, and `verify_budget_exists` refuses the other direction (deleting the+budget, or emptying `provideScope` of its `semaphore.acquire`, while every suite+keeps its annotation).++Know the boundary of both rules: reachability into the PRODUCTION target is+seeded, not followed. `PRODUCTION_WEBKIT_TYPES` in the guard is an explicit list,+and a production type that builds a page but is not named there is invisible to+both checks — every test driving it scans clean and its suite is never asked to+carry `.liveWebKit`. Nothing can discover that omission (discovering it is the+whole-target Swift parser the list exists to avoid), and it has already cost+once: `WebViewPool` and `SVGRenderer` were missing, so `SVGRendererTests` drove a+real pooled `WKWebView` unchecked and uncapped until T-2219's review. **When a+production type starts building WebKit, add it to that list in the same change.**++The fourth way is for the tests never to be scheduled at all.+`localisation-tests.yml` is the only workflow that runs `xcodebuild`, and its+`paths` filters omitted `prismTests/**`, `prismUITests/**`, `prism.xctestplan`,+`prism.xcodeproj/**` and `samples/**`, so a test-only change skipped it and+merged green having tested nothing (T-2198). That sweep is now+`workflow_dispatch` only and the per-locale run is a local step (see "When to+Run Which Tests"), so today NO push or pull request runs any test — which is+the same hole T-2198 closed, held open deliberately and recorded where a reader+will meet it rather than left to be discovered.++`make verify-workflow-triggers` (`Tools/check-workflow-triggers.py`, run by+`checks.yml` on every push) enforces which of the two modes the file is in and+refuses anything between them. While the sweep is DISABLED it asserts CLAUDE.md+still carries the `<!-- ci-sweep: manual-only -->` marker and names+`make test-locales`, so the local requirement cannot be lost the way the paths+list was. The moment either automatic trigger returns it goes back to the full+contract: both filters list every input that can change what the sweep builds+or runs, filter keys it cannot read are refused (`paths-ignore:`, quoted or+not, would otherwise pass as "unfiltered"), a `!` negation is refused+(membership cannot see an exclusion, so `['prismTests/**', '!prismTests/**']`+listed every required path and triggered on none of them), and a required path+that no longer exists in the repository fails. The required list is derived+from what the suite READS AT RUN TIME, not from what Xcode compiles:+`samples/**` is compiled by no target and opened from disk by three suites+(`ParityFixtureSupport.samplesDirectory()`, `SamplesComplianceTests`,+`OffMainEmitTests`), which is how the guard's first pass shipped still missing+it. The guard also checks its own runner — a `paths` filter on `checks.yml`, or+the loss of the step that invokes it, would silence it by the same mechanism.++### Tests Never Touch the User's Session Store (T-2275)++`SessionFileManager` is a `struct` over an **injected** directory, not a+static-only type over one. It has to be: with a single process-wide store, a+test that wants a clean slate can only say "empty *the* store", and+`StatePersistenceIntegrationTests` said exactly that — enumerating the app's real+`Application Support/UnsavedSessions/` and deleting every entry, before and after+most of its tests. Under the test host that is the live app container, so a test+run destroyed the user's recoverable unsaved documents; and because suites run+concurrently, the same blanket delete removed files two sibling suites were+mid-way through using. `@Suite(.serialized)` never helped — it serialises within+a suite, and the collision was across suites. The three persistence suites no+longer carry it.+Two things keep it fixed, and only the second is mechanical. `StatePersistence`+and `DocumentServices` take the store with **no default**, so the production+store is not reachable by omission — the compiler enforces that. And+`SessionStoreIsolationTests` scans `prismTests/` (via `ProductionSourceScan`,+whose `directoryName` now varies — this is the first scan that reads the test+tree rather than `prism/`) and fails on any test naming `SessionFileManager.shared`+without a `// prism-session-store-exempt: <reason>` marker. Use+`SessionFileManager.temporary()` from `prismTests/Support/IsolatedSessionStore.swift`.+The one live exemption asserts where the production store lives and never writes.
diff --git a/docs/agent-notes/external-file-moves.md b/docs/agent-notes/external-file-moves.mdnew file mode 100644index 00000000..d110d499--- /dev/null+++ b/docs/agent-notes/external-file-moves.md@@ -0,0 +1,17 @@+# External File Moves (T-1881)++How an open document follows an external rename, and why the notes migration for a move is separate from the Save As one. Moved verbatim from CLAUDE.md (T-2376).++`FileChangeObserver.presentedItemDidMove(to:)` retargets the presented URL synchronously, under a `Mutex` and before any actor hop, because `presentedItemURL` is read off-actor by the coordination machinery. It then reports the move to `DocumentSession.followFileMove(to:)`, which moves `source`. That one property is the whole fix for most of the symptom: the title, the Save destination, `reloadDocument`, the persisted scroll key and the page's image context (re-based by `WebDocumentStateSynchronizer` from `source.imageSourceContext`) are all derived from it. The report is made in place when the callback is already on the main thread — `presentedItemOperationQueue` is `OperationQueue.main` — because two `Task { @MainActor }` hops are scheduled, not ordered, and a reversed A→B, B→C pair would leave `source` at B while the file is at C.++A destination inside a Trash directory is not a rename: trashing an open document arrives as `presentedItemDidMove(to:)` naming its new home in the Trash, so `DocumentSession.isTrashed(_:)` refuses that notification outright and leaves `source` — and the notes — where they are.++Only the notes do not follow `source`: they are filed under a path-derived identifier. So the move is republished as `session.pendingFileMove` and `DocumentReaderView`'s `.onChange(of:initial:)` migrates them — through the move path's **own** migration, `NotesManager.startMigration(forMovedFileFrom:toFileURL:)`, not the Save As one. Reusing the Save As migration was the first three rounds of this fix, and each of its preconditions failed here in a way that ends with the notes gone:++- **Why the move has its own migration.** `migrateNotes(fromClipboardSession:previousDestination:toFileURL:)` stays internal and is still the Save As entry (`ClipboardSaveFlow`), but it (1) opens on `guard var notes = documentNotes` — memory only — so a move consumed before the first `loadNotes` (the `initial: true` pass, where `documentNotes` is guaranteed nil) reported success having moved nothing; (2) assumes source and target cannot collide (a clipboard UUID against a file path), where a move's two sides are both file paths; and (3) is called *before* `didSave(to:)` flips `session.source`, where a move flips it first. `startMigration` is the only entry to the move path; `migrateNotesForMovedFile` is `private` and does the disk half in the returned task.+- **The synchronous claim, and the window it cannot reach.** The flip-then-migrate order means `session.source` names an identity whose notes record does not exist yet. A `loadNotes` resolving through the retargeted source — the reader's own `.task(id: session.parseRevision)`, from a reload landing near the move — fell through every guard, read the target's absent record, and `clearNoteState()` wiped the notes mid-migration; the post-save guard then read its own container as replaced and abandoned the rebind: empty panel, orphaned record under the old path (T-2231 one identity over). A note *created* in that window was worse still, and a claim cannot help it — the container it finds is the thing being judged. So `startMigration` does two synchronous things before it returns, in the turn the move is *consumed* in: it claims both the source and the target identities, and it rebinds an already-loaded container onto the target. **Neither reaches back to the `source` flip**, which happens in the presenter's callback, an earlier turn: that stretch has no claim. It is unreachable rather than covered — a move bumps no `parseRevision` and deliberately raises no reload banner, so nothing resolves notes in it. Change either and both halves have to move into `followFileMove`.+- **`retiringSourceRecordIsSafe` guards the source delete on both migrations.** It asks the store — reading the source identifier back after the save — instead of comparing identifier strings, because `DocumentIdentifier.path` is case-preserving and `readme.md` and `README.md` are therefore two identifiers and one file on a case-insensitive volume (the default on macOS and iOS): the save wrote the record, the delete removed the file it had just written. This *replaced* the pre-existing Save As delete guard, so the clipboard and save-chain suites are part of this change's regression surface, not just the move ones.+- **The migration's origin is `notesRecordURL`.** `DocumentSession.notesRecordURL` is where the record actually is; only a successful migration advances it (`notesRecordFollowedFile(to:)`), so a failed one leaves the *next* move naming the path the record is genuinely still under. `followFileMove` reports every move from there, which is what makes two moves coalescing into one `.onChange` pass (A→B, then B→C) migrate from A — reporting `(B, C)` matched nothing, skipped, and returned `true` — and a round trip A→B→A report nothing at all. The view derives the origin from that property **live** when it consumes, rather than trusting `move.from`: `from` is only a snapshot taken at report time, and a move reported between a migration landing and its `notesRecordFollowedFile` carries an identifier that migration has already deleted.+- **`initial: true`, and the result is not discarded.** The session follows a move whether or not a reader view is mounted, so without the initial pass a move landing off screen is never consumed. And `startMigration` returning `false` means the store write failed and the notes reverted to the old identity while `source` is at the new one — reported through `onMoveMigrationFailed` to the same "Note Migration Failed" alert Save As uses.++The security-scoped lease is deliberately untouched (the extension was issued for the file and survives its rename; a URL synthesised from a move notification carries no scope of its own) and so is the recent-files entry (T-1842/T-2172/T-2173).
diff --git a/docs/agent-notes/footnotes.md b/docs/agent-notes/footnotes.mdindex af41d786..4ed7480a 100644--- a/docs/agent-notes/footnotes.md+++ b/docs/agent-notes/footnotes.md@@ -36,3 +36,19 @@ The Textual fork pin was updated from `6b0d7ce` (pre-footnote) to `69009d4` (inc - The helpers (`FootnoteAccessibility.resolvedReferences(in:data:)` and `FootnoteAccessibility.rebuiltAccessibilityLabel(for:data:)`) live in `prism/Services/FootnoteAccessibility.swift` and are unit-tested in `prismTests/FootnoteAccessibilityTests.swift`. Both reuse `FootnoteData.referencePattern` to keep regex behaviour aligned with the rest of the footnote pipeline. - Surrounding-prose segments between resolved `[^id]` references are run through a private `swift-markdown`-driven `InlinePlainTextCollector` (T-1259) before being appended to the rebuilt label. The collector is a `MarkupWalker` that emits the visible text of each inline construct: emphasis/strong/strikethrough/link/image wrappers fall away because the walker recurses into their children, and inline code spans emit their literal `code` content without the surrounding backticks (swift-markdown's own `InlineCode.plainText` keeps the backticks, which would defeat the point). Unbalanced markers survive as literal text, matching the visual rendering. Leading/trailing whitespace is preserved around the parsed segment so footnote substitutions don't lose their surrounding spaces. See `specs/strip-md-markers-a11y/`. - Scope limit: per-paragraph `.accessibilityActions` is exposed to VoiceOver's Actions rotor. Switch Control and Full Keyboard Access still operate at paragraph granularity; an inline-focus surface for those input methods is out of scope for T-1036.++## Architecture detail moved from CLAUDE.md (T-2376, 2026-10-02)++Moved verbatim when CLAUDE.md was cut back to invariants. Read this for the *why* behind each rule.++### Footnote system on the web document path++1. `FootnotePreprocessor` extracts `[^id]: content` definitions from raw markdown before `swift-markdown` parsing, producing cleaned source + `FootnoteData` sidecar+2. `MarkdownBlockParser.parseWithFootnotes()` integrates the preprocessor into the parsing pipeline; `parseFragment()` renders footnote content in popovers without the full pipeline+3. `DocumentSession` stores `FootnoteData` alongside parsed blocks; both are bundled in `ParseResult`+4. Badge substitution happens inside `InlineHTMLRenderer.render`, NOT by splitting the source in the emitter (T-1716/T-1945). `FootnoteReferenceScanner.scan` walks the block's inline SOURCE once and marks every occurrence that is spelled verbatim (no backslash escape anywhere in the token) and resolvable, rewriting only its identifier characters into a reserved Private Use Area window. The marker is length-preserving (runs come out in block coordinates — no rebasing, `rebased` is gone) and parse-shape-preserving (`[`, `^`, `]` untouched, so cmark builds the same tree). The whole marked source is then parsed ONCE+5. `InlineHTMLRenderer.Walker` turns a marker into a badge only where a badge is legal: TEXT position **and** not nested inside an element that cannot contain an anchor. Text position alone is not sufficient — the badge is itself an `<a>`, so a `Link` ancestor disqualifies it (`<a>` inside `<a>` is invalid HTML), tracked by the walker's `linkDepth` counter. Every other landing place — a code span, a link's destination or title, an image `src`/`alt`/title, raw inline HTML, or text inside a link — is restored to the literal `[^id]` the author wrote (titles excepted: the emitter renders no `title` attribute, so there is nothing to restore). Classification is never inferred from parsed text, which is the failure class the redesign removes. Restoring is only half of it: a landing place that declines the badge must ALSO claim the occurrence and step the cursor past it (`claimOccurrences`), or a later live reference with the same identifier binds to the attribute's occurrence — zero-length source-map run for the prose before the real badge, wrong offset in `badgeSourceStarts` (T-1992). The claim is POSITIONAL, never keyed on the identifier, and fails closed: an attribute cmark hands back normalised rather than verbatim does not locate and claims nothing, which leaves the T-1992 symptom standing for two shapes (T-2033). Mechanism, the autolink exclusion, and the residual: `docs/agent-notes/webview-rendering-status.md`. `BlockHTMLEmitter.footnoteBadge` builds the styled pill-badge anchor (`prism://footnote/{id}`, display number from `FootnoteData`) carrying `data-prism-chrome`: inert, unselectable, covered by no source-map run+6. Badge taps produce `prism://footnote/{id}` links → `linkActivated` over the bridge → `WebDocumentMessageRouter` → `DocumentLayoutCoordinator` popover state (`PrismLinkRoute.footnotePrefix`)+7. `FootnotePopoverView` displays rendered footnote content (paragraphs, lists, blockquotes only) over a shared, non-persistent `FootnotePopoverWebPage` (emitter-rendered fragment). Since the WebKit cutover it is presented as a sheet on every platform via the shared `FootnotePresenter` modifier (`View.footnotePresentation(coordinator:session:)`), which **both** `CompactDocumentLayout` and `RegularDocumentLayout` must apply — the regular layout lacking it is T-1893. The web-rendered badge has no SwiftUI anchor view, so the anchored popover the original footnotes spec called for (Req 3.1/3.6/3.7) no longer applies; `FootnotePopoverView` self-sizes per platform. The popover page is bridge-less, so everything the document surface receives over the bridge must instead be BAKED into the emitted HTML via `RenderSettings`. Baked today: the palette — theme key **and** Increase Contrast state, carried as one `WebPaletteFeed` so they can never be applied out of step (T-1542/T-1829), emitted as `data-prism-theme`/`data-prism-contrast` by `BlockHTMLEmitter.paletteAttributes`; and the typography custom properties (T-1978, emitted as a validated `<html style>` by `BlockHTMLEmitter.rootStyleAttribute`). Not baked: the mermaid theme config and the note/search/section state, none of which a footnote fragment can contain. `FootnotePopoverView.renderSettings(settings:colorScheme:contrast:dynamicTypeSize:)` is the single pure builder of that render input — it reuses `WebDocumentControllerFactory.typographyVariables` rather than resolving fonts again (font-settings Decision 18), and its equatable result is one half of the re-present key. Because a bake can only be applied by re-emitting, an OPEN popover stays current only by re-presenting: `FootnotePopoverWebPage.RenderKey` (footnote id + the resolved `FootnoteDefinition` + that `RenderSettings`) is the equatable trigger, and `FootnotePopoverView` drives it with one `.onChange(of: renderKey, initial: true)` — evaluated in `body`, which is what registers the `AppSettings` reads with Observation (reading them only inside `onAppear` registered nothing). `present` no-ops on an unchanged key (an identical re-emit would blank the live page mid-read) and `renderGeneration` guards overlapping loads so a superseded one cannot win; it also varies the document URL's `rev`. Keying on `footnoteId` alone was T-1979: the identifier is the one input that does not move when the theme, contrast, typography, comment visibility, or a same-id definition does+8. `FootnoteStripping` removes `[^id]` references from heading text used in ToC entries, anchor IDs, and window titles+9. Search integration: `searchableText(with:)` appends footnote content to host blocks; badge highlighting indicates matches
diff --git a/docs/agent-notes/image-support.md b/docs/agent-notes/image-support.mdindex e914f690..617b51d2 100644--- a/docs/agent-notes/image-support.md+++ b/docs/agent-notes/image-support.md@@ -163,3 +163,16 @@ - `ImagePathResolverTests.isSVGReturnsFalseForFailed` was fixed: `isSVG()` checks source extension first, so a `.svg` source is detected as SVG even if resolution fails. - Navigation delegate pattern: `SVGRenderer` uses `pendingNavigations: [ObjectIdentifier: CheckedContinuation]` keyed by WebView identity for tracking template load completion. Simpler than MermaidRenderer's message handler pattern since SVG rendering doesn't need JS callbacks. - Self-contained timeout (T-518): Both `SVGRenderer.loadTemplate` and `BackgroundDiagramRenderer.loadHTML` schedule a timeout `Task` inside `withCheckedThrowingContinuation`. After `timeoutSeconds`, the task checks if the continuation is still in `pendingNavigations` and resumes it with a timeout error if so. This prevents leaked continuations when WKWebView is deallocated before navigation completes. Uses `[weak self]` and `removeValue(forKey:)` for single-resume safety.++## Architecture detail moved from CLAUDE.md (T-2376, 2026-10-02)++Moved verbatim when CLAUDE.md was cut back to invariants. Read this for the *why* behind each rule.++### Image loading, memory admission, concurrency and inline data: rasters++5. SVG sources detected via `ImagePathResolver.isSVG()` are loaded as strings by `SVGSourceLoader` and rasterized by `SVGRenderer` (delegates to `WebViewPool`; strict CSP: `script-src 'none'`)+6. Raster images loaded by `ImageLoader` (actor) from file, network, or data URI. Two entry points, both funnelling into the guard below: `load(_:)` for the native SwiftUI surfaces, `loadPageBytes(_:fallbackMIMEType:)` for the rendered page (the only raster entry `PrismDocSchemeHandler` uses). The handler builds a loader PER REQUEST and every page image is now a request, so `ImageLoader` and `SVGSourceLoader` each hold ONE process-wide `URLSession` rather than building one per instance: a delegate-backed session is retained until `invalidateAndCancel()`, which nothing calls, so a session per loader is a leak scaled by the document's image count. The session is shared, not the loader — one shared actor would serialise every caller behind the synchronous `readLocalFile`. An injected configuration still gets its own session so a test's `URLProtocol` stub cannot sit in front of production traffic+7. **Memory admission (T-2132/T-2149/T-2151/T-1867)**: `ImageMemoryGuard` (`prism/Services/`) is the single place that decides whether image bytes may be materialised and at what decoded cost, and the only place in production that may turn ENCODED IMAGE BYTES into pixels — create a `CGImageSource`, call `PlatformImage(data:)`, decode a `CGImage`, or encode one back to bytes. That claim is narrower than "the only bitmap allocation", deliberately: `WebViewPool.captureSnapshot` has WebKit rasterise a rendered page (mermaid/SVG thumbnails) for up to ~144 MB (2000 pt square at 3x) against no byte budget — it has no encoded bytes and no header to size, so it is bounded by the pool's slot count and `SVGRenderer`'s 2000-point frame clamp instead, and it carries a `prism-memory-exempt` marker so a SECOND such site has to be argued for. It decides from the **header** (`CGImageSourceCopyPropertiesAtIndex`), never from a decode, and the per-pixel size comes from the header too (`kCGImagePropertyDepth` + `kCGImagePropertyColorModel`), NOT a hardcoded 4: a 16-bit PNG decodes at 8 bytes/px and a 32-bit float TIFF at 16, so a fixed 4 under-counted them 2x and 4x and "retained ≤ 64 MB" was not a bound the code enforced (`ImageCache.estimatedMemoryCost` was already depth-aware on the other side of the decode). The component counts are an UPPER BOUND on what CoreGraphics allocates, not an identity with it: opaque RGB is counted as 4 because ImageIO's default decode is 32 bits/px with a skip byte (CoreGraphics does have a packed 24-bit format, so this is the bound, not the only possibility), grey costs 1, and palette PNG and 16-bit opaque RGB are knowingly over-counted. Over-counting costs a boundary image a downsample it did not need; only under-counting could admit an image the budget cannot pay for, and none does. An unreadable depth or colour model is `refuseUnsizable`, same as unreadable dimensions — empirically free, since every format ImageIO can size reports both. Four verdicts: `decodeWhole` (decoded whole, or on the page path served VERBATIM, since re-encoding validated bytes buys nothing and costs three allocations), `downsampleFirstFrame` (frame 0 declares ≤ 256 MB — bounded decode to `retainedDimensionCap(bytesPerPixel:)`, which is 4096 px at 4 B/px but 2896 at 8 and 2048 at 16, because a thumbnail KEEPS the source's bit depth), `refuseOversized` (past 256 MB) and `refuseUnsizable` (no readable dimensions, depth, or colour model). The verdict is taken **per consumer**, which is a correctness rule not a refinement: `.native` uses the eager all-frame model `NSImage(data:)` actually pays (every frame's declared size sums into the retained budget, scan bounded at `maxScannedFrames`); `.page` budgets frame 0 alone, because WebKit decodes progressively. Applying the native model to the page is what stopped animated GIFs past 64 frames from animating — a 100x100 100-frame GIF is ~4 MB decoded and was refused, then served as a re-encoded still. The 256 MB ceiling is load-bearing rather than belt-and-braces: PNG/GIF/TIFF have no subsampled decode, so `CGImageSourceCreateThumbnailAtIndex` may inflate the whole source bitmap before scaling — bounding the transient peak is only possible by bounding what may be *declared*. Sending every over-budget raster to the thumbnail path was the first T-2132 fix, and why it was reopened. `BoundedFileRead` is the byte-level twin: it preflights the file size AND bounds the read chunk by chunk, so a file that grows in between is still cut off. Two details are load-bearing for its documented `limit + chunkSize` residency bound and both are invisible from outside (the reported `byteCount` is identical either way, so the pin is structural in `ImageMaterializationChokepointTests`): the running total is tested BEFORE the chunk is appended, not after — appending first commits the memory the cap is refusing — and the reservation comes from the preflight, going straight to `limit` in one step when the preflight is missing or stale, because `Data.append`'s geometric growth otherwise holds ~2x the cap live across the last reallocations — every local read of a document, image, or SVG goes through it, including `SessionFileManager.readContent`, which restores a persisted document body. `ImageMaterializationChokepointTests` scans production source and fails when a banned call appears outside those two files without a per-line `// prism-memory-exempt: <why>` marker; its line-scanning machinery is shared with `URLChokepointAdoptionTests` via `ProductionSourceScan` (the duplication cost real coverage: the URL scan had already learned that `.init(string:)` is `URL(string:)`, and the copied image scan was blind to `.init(data:` all over again). A companion test asserts the chokepoint files still contain the calls, so the rule cannot be satisfied by gutting the guard. Honest limits: retained bitmap ≤ 64 MB/image, transient peak ≤ that image's declared size (≤ 256 MB); what WebKit decodes for a verbatim-served image is not accounted at all+8. Concurrency: `SharedConcurrency` owns the global network semaphore (6 concurrent fetches) and a 4-slot local-read semaphore; both permits are held until materialisation FINISHES, so a compressed body can only exist while its owner holds one (that ordering is the T-2151 fix — releasing early let bodies pile up behind the decode gate). Decode concurrency is `ImageMemoryGuard.budget`, an `ImageMemoryBudget` actor weighted in BYTES, not slots: a four-slot count bounded nothing when one image costs 250 MB and the next 8 MB. One reservation covers decode and re-encode together. Render concurrency is managed per-pool by `WebViewPool` instances+9. Inline `data:` rasters never reach the scheme handler (the CSP permits `img-src data:`), so admission happens at emit time in `BlockHTMLEmitter.rewriteImageSrc`, judged with the `.page` consumer: an admissible payload passes through unchanged, anything else is rewritten to `PrismDocSchemeHandler.blockedImageURLString` (`prism-doc://img/blocked`), which routes to `.rejected(.imagePolicy)` so the page renders its existing catalog-localised image-error placeholder. Refusing rather than downsampling leaves a deliberate asymmetry — the byte-identical image written as a FILE reference is downsampled and shown — and the justification is memory, not convenience: downsampling inline means decoding and re-encoding during emit (a pure, cheap, off-main function of the blocks, run per parse revision) and then re-inlining the base64 result INTO the document HTML, where it is retained for the whole session; a file reference has somewhere else to put the downsampled bytes. The refusal address carries no `?src=` payload, which `prism-media.js`'s `isLocalImage` must treat as "not local" — reading the missing parameter back as `""` offered an iOS "Grant Folder Access" picker for a picture that lives in the markdown and has no folder to grant+10. `ImageCache` (`NSCache`-based) caches raster images; `SnapshotCache` (`NSCache`-based) caches SVG/mermaid rasterized snapshots
diff --git a/docs/agent-notes/inapp-purchase.md b/docs/agent-notes/inapp-purchase.mdindex 0246dc81..464fd3e3 100644--- a/docs/agent-notes/inapp-purchase.md+++ b/docs/agent-notes/inapp-purchase.md@@ -84,3 +84,21 @@ When two devices both export from `count=9` to `count=10` while offline, the hig ## Toast VoiceOver `ToastNotification` posts an announcement on both platforms — `UIAccessibility.post(notification:argument:)` on iOS and `NSAccessibility.post(element:notification:userInfo:)` with `.announcementRequested` and high priority on macOS. This satisfies reqs 5.5 and 11.1 cross-platform.++## Architecture detail moved from CLAUDE.md (T-2376, 2026-10-02)++Moved verbatim when CLAUDE.md was cut back to invariants. Read this for the *why* behind each rule.++### In-app purchase system++1. `StoreManager` (`@Observable @MainActor`) owns StoreKit 2 product fetching, entitlement verification, and the export counter — everything scoped to the ACCOUNT. It owns no paywall presentation state: that is per-scene and lives on `PaywallPresenter` (T-1779). `productLoadError` means "the catalog did not return the unlock product", empty or merely partial — StoreKit omits identifiers it cannot resolve rather than failing, and testing `fetched.isEmpty` left a partial catalog with `unlockProduct` nil and the flag false, a combination neither the paywall nor the Settings row has a branch for, so both spun forever (T-1841). A missing individual TIP is tolerated: the unlock product gates the paywall, the tips only fill the tip jar, so the two are selected independently and neither short-circuits the other — an early return on a missing unlock silently emptied an already-unlocked user's tip jar. The rule lives on `StoreManager.Catalog.loadFailed`, not at the assignment in `fetchProducts()`, because that method assigns to `Product`-typed properties and StoreKit will not let a test construct a `Product` — with the rule at the assignment, reverting it to `fetched.isEmpty` left the whole suite green. The selection itself is the pure `selectCatalog(from:)` over the `StoreProduct` seam (Decision 14)+2. `EntitlementState` is tri-state (`.loading` / `.locked` / `.unlocked`); the paywall and Settings UI branch on it. All writes flow through one commit point ordered by a monotonic observation clock — recency of information wins, never completion order — because a verification scan suspends mid-read and MainActor isolation does not cover that reentrancy window (T-1868). The StoreKit scan sits behind the injectable `EntitlementSource` seam (and `AppStore.sync()` behind `AppStoreSyncing`) so the ordering rules are unit-testable. That clock records who last STAMPED, which is not who last PUBLISHED, so `verifyEntitlements()` answers its own caller through a second watermark, `lastCommittedObservation` — `lastCommittedObservation >= observation ? entitlementState : result`, i.e. the shared property only when something at or after this call's own observation actually committed, and this scan's own finding otherwise, because a newer scan that has merely stamped leaves that property STALER than the scan being answered, which is how `restorePurchases()` came to tell a genuine owner "No purchases to restore" (T-2237, Decision 15)+3. `ExportCounter` tracks the export count with iCloud KVS sync and a UserDefaults mirror; reconciles on init and on external KVS change notifications+4. `KeyValueStoreProtocol` abstracts `NSUbiquitousKeyValueStore` so unit tests can inject a stub+5. `PaywallPresenter` (`prism/Views/PaywallPresenter.swift`, `@Observable @MainActor`) is the PER-SCENE owner of `isPresented` and `pendingExportAction`. `MainContentView` holds one as `@State` per window and the macOS `Settings` scene holds its own; each attaches the shared `paywallPresentation(presenter:storeManager:settings:systemObserver:)` host, which owns the sheet and calls `handleDismiss(entitlementState:)`. Holding those fields on the app-wide `StoreManager` meant every window's sheet bound to one flag — the paywall presented and dismissed in all windows, a second blocked export overwrote the first window's retry, and a Settings-initiated unlock presented over a document window (T-1779). What must NOT move per-scene is the purchase signal: the split first narrowed a `didCompletePurchase` flag along with everything else, which regressed the cross-scene purchase (block in window A, unlock from the Settings window, dismiss A → A's export silently dropped) because entitlement is account-scoped while the flag was set on whichever presenter ran the purchase. That flag is gone; see 8+6. Export gating: callers use `PaywallPresenter.runGatedExport(storeManager:retry:perform:)`, which returns `.loading` (no-op), presents THAT scene's paywall on `.blocked`, or invokes the perform closure on `.allowed` / `.allowedWithNudge`. The gate decision itself stays on `StoreManager.checkExport()`; only the presentation side effect is per-scene+7. `PaywallSheet` runs the purchase flow with explicit ready / processing / pending (Ask to Buy) / error states and surfaces restore success / "no purchases" / failure to the user+8. The presenter's `pendingExportAction` is re-run by its own `handleDismiss` when the APP-WIDE entitlement moved to `.unlocked` while that scene's paywall was up: the presenter captures the entitlement alongside the retry on the `.blocked` gate and compares at dismissal. Watching the shared entitlement rather than a per-scene purchase flag is what lets a purchase or restore completed in ANY scene finish the blocked scene's export, while still separating it from a swipe-away or an Ask to Buy awaiting approval, where the entitlement never moves. The captured baseline is always `.locked` today (only a `.locked` store yields a `.blocked` gate), so it coincides with testing `.unlocked` at dismissal; it is kept because it states that invariant rather than silently depending on it+9. Free-tier mechanics: 20 free exports total. Toast nudge fires on the 10th completion (event: `count >= nudgeThreshold - 1` pre-increment); persistent indicator shows once the count is at or above 10 (state: `count >= nudgeThreshold` post-increment)+10. Gated actions: copy notes, share notes, file export with inline notes. Reading features and code/mermaid copy remain free+11. `Products.storekit` (in `prism/Resources/`) supplies the four products (1 non-consumable unlock, 3 consumable tips) for local StoreKit testing; the scheme references it via `StoreKitConfigurationFileReference`
diff --git a/docs/agent-notes/webview-rendering-status.md b/docs/agent-notes/webview-rendering-status.mdindex 97533639..bb077795 100644--- a/docs/agent-notes/webview-rendering-status.md+++ b/docs/agent-notes/webview-rendering-status.md@@ -274,3 +274,22 @@ take down unrelated applications' web content. Always PID-verify, never pattern- Two more properties that read as details and are not: a re-assert does **not** announce (`performScrollToBlock(domID, false)`) — it is the same intent landing again, and injection order is bridge, scroll, theme, media, notes, search, so an announcing re-assert ran BEFORE prism-search.js's deferred-reveal listener on the same hook and cleared `revealPending` out from under a NEWER search reveal. And only an EXPLICIT navigation arms the window at all: `scrollToBlock` carries `armsReassert`, false for `WebDocumentController.restoreScroll`, because a stored-position restore is a position the reader never chose and a `<summary>` click in the first second of opening a document must not be answered by yanking them to it. `setDetailsState` gets its own bridge hook (`onDetailsStateApplied`) rather than reusing `onSectionVisibilityChanged`, whose only other listener is prism-search.js's re-window/deferred-reveal delivery. Pinned by `WebDetailsNavigationOrderingTests`, whose fixtures are deliberately order-sensitive (each asserts the scroll was clamped, or fell back to the top, BEFORE the state push lands) and whose two negative tests each end in a positive control proving the target was still armed. **Any NEW path whose correctness depends on command order still needs T-2028**, or its own immunity.++## Architecture detail moved from CLAUDE.md (T-2376, 2026-10-02)++Moved verbatim when CLAUDE.md was cut back to invariants. Read this for the *why* behind each rule.++### Pipeline (Parse → Emit → Serve → Host + bridge → Notes → Search → Security → render libraries)++The document is rendered by WebKit-for-SwiftUI (`WebView`/`WebPage`). The SwiftUI/Textual in-flow renderer was retired in the T-1542 cutover — there is no legacy path or render-policy switch any more (see the CHANGELOG `[Unreleased]` "Changed" entry). Native stays the source of truth: parsing, search counting, notes logic, and persistence all run natively; the web view only renders HTML and reports interactions back over the bridge.++1. **Parse**: `swift-markdown` → AST → `MarkdownBlock` enum variants (`MarkdownBlockParser`), unchanged from before. T-1558 made the model lossless for nested blockquotes, ordered-list `start`, and rich blocks inside list items (see `specs/web-markdown-fidelity/`).+2. **Emit**: `BlockHTMLEmitter` (`prism/Services/WebRendering/`) is a pure, deterministic function of `[MarkdownBlock]` + `FootnoteData` + `RenderSettings`. It emits one `<section>` per block carrying the content-hash block identity and an occurrence-qualified DOM id (`b-{hash}-{sourceIndex}`, allocated via the shared `BlockDOMID`), escapes by default, and is total (a block that fails to emit falls back to escaped-source `<pre>`, never dropped). `InlineHTMLRenderer` wraps mappable text runs in `<span data-prism-run>` and records a `DocumentSourceMap` (UTF-16 offsets, shipped as an inert `<div hidden>` data island) for selection-anchored notes. `emit` (and the model/service value types it reads) is `nonisolated`, so it runs off the MainActor: `WebDocumentControllerFactory.precomputeDocumentHTML` emits once per `parseRevision` on a `Task.detached` and caches the HTML on `DocumentSession`; the scheme handler serves that cache (synchronous on-main emit only on a miss). Its per-block/inline `HTMLSanitizer` (SwiftSoup) passes are serialized behind a shared `Mutex` because SwiftSoup keeps unsynchronized static pools (T-1681, `specs/offmain-html-emit/`).+3. **Serve**: `PrismDocSchemeHandler` (`prism-doc://` `URLSchemeHandler`) is the single audited I/O path — it serves the document HTML, `document.css` (the only asset fetched through the scheme), and mediates every image subresource through `/img/?src=` (rewritten absolute/relative URLs routed via `ImagePathResolver`/`ImageLoader`/`SVGSourceLoader`). It serves the verbatim CSP (`script-src 'none'`, `connect-src 'none'`, …) as a response header. The document is loaded via the scheme, never `loadHTMLString`. The handler is a STRUCT copied into the `WebPage.Configuration`, so anything stored in it is frozen for the life of the page — which is why the image context (scope root, source type, base URL) is not stored but held by reference, in the shared `DocumentImageSourceBox` (`DocumentImageSource.swift`) it reads per request. `didSave(to:)` re-bases a clipboard document onto a file IN PLACE — same session id, same parse output, no `parseRevision` bump — so nothing rebuilds the page, and a captured context left the saved document resolving every relative image as an unsaved paste (no scope root, so all rejected) until it was closed and reopened (T-1784). `WebDocumentStateSynchronizer` owns the update: the context is a domain of its observation pass, and a change writes the box and issues a same-revision `reloadDocument` — the images already on screen failed against the old context and WebKit will not re-request them, and that reload restores the stored reading position — except when the page's `parseRevision` is behind the session's, where it is deferred because the owed revision load fetches every image against the new context anyway, and a second reload would only discard the first's scroll restore (T-1810). Its first pass only seeds (the initial load has not happened yet).+4. **Host + bridge**: `WebDocumentController`/`WebDocumentView` (`prism/ViewModels/`, `prism/Views/`) own one `WebPage` per session (non-persistent store, `allowsContentJavaScript = false`, all JS injected as user scripts via `WebDocumentControllerFactory.userScripts()`). The native↔JS bridge runs in a dedicated isolated `WKContentWorld`; every message in both directions carries a generation tag (sessionID, parseRevision, processGeneration). `BridgeMessageRouter` validates inbound messages against an enumerated allowlist + exact-generation match and drops forged/stale/malformed ones; `WebDocumentMessageRouter` routes accepted messages onto the existing native session/coordinator state. Outbound commands queue until `ready`; scroll restore waits for `layoutSettled`; on WebContent termination the controller bumps the process generation, reloads, and replays one coalesced state snapshot. That termination is observed by `startNavigationObservation()`, armed from the controller's `init` — it was missing entirely until T-1943, so the whole recovery path was dead code in production. `WebPage` offers no delegate callback and no Observable property for a crash: it surfaces as `WebPage.NavigationError.webContentProcessTerminated` **thrown** by `page.navigations`, which ENDS the sequence — and which also throws for ordinary navigation failures — so the observer classifies the error (`drainNavigationStream`) and re-subscribes (`applyNavigationOutcome`), or the first failed navigation would silently disarm crash recovery for the rest of the session. A recovery reload that fails as an ORDINARY navigation is the same failure wearing a different error, so `recoveryInFlight` makes a `.navigationFailed` legible: during a recovery it is charged and retried, outside one it is a benign bad link. Recovery gives up after `maxUnproductiveRecoveries` consecutive attempts that never reach the stability milestone that resets the budget — `layoutSettled`, not merely `ready` — rather than reloading in a hot loop; `ready` alone used to reset it, so a crash landing after `ready` but before `layoutSettled` restarted the chain at attempt one every time and could reload forever without ever hitting the cap (T-2107). Giving up is neither silent nor permanent: it clears the observation task handle, raises `recoveryAbandoned` (the banner in `DocumentScrollContent`), and any fresh `load` restores the budget and re-arms observation. Because a direct-invocation test cannot see missing wiring (that is exactly how T-1943 survived the cutover and every review), the production subscription is pinned by a live test over a real `WebPage`: `WebContentTerminationWiringTests.controllerObservesItsOwnPageNavigationStream`. `WebDocumentStateSynchronizer` (T-1719) is the single production owner that pushes native truth (sections, details open-state, table modes, notes, typography, comment visibility) to the controller and routes navigation targets (TOC/fragment via `session.pendingAnchorScroll`, notes via `coordinator.noteNavigationTarget`, search current match) through `controller.scrollTo` with `BlockDOMID.navigationDOMID` id translation — Observation-framework driven, so it works with no view mounted; `DocumentScrollContent` mounts the whole assembly via `WebDocumentStateSynchronizer.makeAssembly`. Two inputs are view-fed, because both are view-world environment values: the palette, pushed via `applyTheme(themeKey:contrast:)` — the colorScheme-resolved theme key plus `colorSchemeContrast`, grouped as a `WebPaletteFeed` so a single `.onChange` pushes them together and they can never be applied out of step (T-1829) — and `dynamicTypeSize`, fed in via `start(dynamicTypeSize:)` / `applyDynamicTypeSize(_:)`, which gets NO push of its own: the synchronizer folds it into the typography domain, because `applyTypography` carries one variables dict that wholly replaces the snapshot's typography, so a second pusher would drop the settings-derived half from the recovery replay (T-1828, font-settings Decision 18).+5. **Notes**: `NoteStateFeeder` (`prism/Services/WebRendering/`) maps `NotesManager` state onto `setNoteIndicators`/`setInlineNotes` payloads; `NoteHTMLBuilder` renders the (escaped) bubble/banner HTML natively; `prism-notes.js` (isolated world) injects it as `data-prism-chrome` and posts interaction messages back. Every interactive piece of that chrome is a NATIVE `<button>` or `<a href>` (T-1725) — never a `div`/`span` with `role="button"` — so the user agent supplies focusability, tab order, and Enter/Space activation, and there is no synthetic key handling to keep in sync. Those elements suppress their UA appearance, so `document.css` must reset it; the indicator dot's `font-size: 1em` is load-bearing rather than cosmetic, since the dot's whole gutter geometry is expressed in em. Accessible names are native-owned because the JS cannot reach the string catalog: the indicator's name rides the `setNoteIndicators` payload (`label`, pluralised via `NoteRenderStrings.noteIndicator`), the bubble's action label is baked in by `NoteHTMLBuilder` as visually-hidden text (an `aria-label` there would *replace* the note's own text in the accessible name), and the add-note "+" reads `<main data-prism-add-note-label>`. Both push handlers rebuild all chrome, so each control carries a `data-prism-focus-key` and `prism-notes.js` captures/restores focus around the rebuild. The restore is gated on `document.hasFocus()` — never pull focus into a document the user is not in — and a restore the gate refuses is DEFERRED as `pendingFocusKey`, not discarded, then consumed by a `window` `focus` listener when the document actually comes back (T-2059); discarding it lost the return address for every note edited through a native sheet. The shared writer, `focusOrDefer`, is called from BOTH `restoreFocusKey` and `suppressAddNote`'s "+"-to-dot handoff — the add-note "+" carries no focus key of its own (`makeAddNoteControl`), so before this the handoff had nothing to defer and lost focus outright on the more common add-a-note sequence (stand on a block's "+", tap it, save from the sheet); `focusOrDefer` falls back to the successor's OWN `data-prism-focus-key` so that path is covered too. `focusControl` verifies `document.activeElement === element` after calling `.focus()` rather than trusting the call, because a suppressed "+" stays in the DOM (`display:none`) and a no-op `.focus()` on it must not read as success. The pending key is invalidated by `bridge.onExplicitNavigation`, matching the sibling deferrals in `prism-search.js` (`revealPending`) and `prism-scroll.js` (`reflowAnchor`) — safe because a note's own bridge messages (indicator/bubble tap, block-context "+") never scroll, so the invalidation cannot cancel the restore it exists to deliver. The consuming `window` `focus` listener also refuses while `bridge.searchIsActive()` (prism-search.js, sourced from `SearchCoordinator.isSearchActive`), mirroring native's `restoreBodyFocusIfIdle` (`RegularDocumentLayout.swift`) — the key stays pending rather than discarded, so it still fires once search is no longer active.+6. **Search**: counts and navigation order stay in `SearchService`/`SearchCoordinator`. `SearchStateFeeder` translates that into a per-block `setSearchState` payload; `prism-search.js` re-finds the query in each block's rendered text and registers ranges on two named **CSS Custom Highlights** (`prism-search`, `prism-search-current`), windowed to the viewport. The web view's built-in find navigator stays disabled so Cmd+F routes to Prism's search.+7. **Security**: `HTMLSanitizer` (over SwiftSoup) reduces raw HTML embedded in markdown to an allowlist subset on load (Req 1.8/8.1); its `plainText` feeds searchable text. Combined with `allowsContentJavaScript = false` and the served CSP, active-content vectors are blocked by construction.+8. **In-page render libraries**: mermaid.js and highlight.js (+ their thin Prism drivers) run in the **page world** (they only render DOM, never post bridge messages). The bundled JS lives in `prism/Resources/WebRenderer/`.++Implementation history and gotchas (the `<script>` data-island CSP trap, the native selection overlay, the live-test harness): `docs/agent-notes/webview-rendering-status.md`. Spec: `specs/webview-rendering/`.